目录
调度概念
PELT
CFS调度
linux 线程调度策略
SCHED_OTHER 分时调度策略
SCHED_FF 实时调度策略,先到先服务
SCHED_RR 实时调度策略,时间片轮转
实时调度根据优先级rt_priority (1~99) 调度,也大优先级越高;分时系统根据nice(-20~19) ,越大分配到cpu 时间越少,分到的cpu 时间调度,即曾经使用cpu 时间最小执行
linux线程调度策略 - 百度文库
kernel-4.19/Documentation/scheduler/sched-design-CFS.txt
============= 2 CFS Scheduler 3 ============= 4 5 6 1. OVERVIEW 7 8 CFS stands for "Completely Fair Scheduler," and is the new "desktop" process 9 scheduler implemented by Ingo Molnar and merged in Linux 2.6.23. It is the 10 replacement for the previous vanilla scheduler's SCHED_OTHER interactivity 11 code. 12 13 80% of CFS's design can be summed up in a single sentence: CFS basically models 14 an "ideal, precise multi-tasking CPU" on real hardware. 15 16 "Ideal multi-tasking CPU" is a (non-existent :-)) CPU that has 100% physical 17 power and which can run each task at precise equal speed, in parallel, each at 18 1/nr_running speed. For example: if there are 2 tasks running, then it runs 19 each at 50% physical power --- i.e., actually in parallel. 20 21 On real hardware, we can run only a single task at once, so we have to 22 introduce the concept of "virtual runtime." The virtual runtime of a task 23 specifies when its next timeslice would start execution on the ideal 24 multi-tasking CPU described above. In practice, the virtual runtime of a task 25 is its actual runtime normalized to the total number of running tasks. 26 27 28 29 2. FEW IMPLEMENTATION DETAILS 30 31 In CFS the virtual runtime is expressed and tracked via the per-task 32 p->se.vruntime (nanosec-unit) value. This way, it's possible to accurately 33 timestamp and measure the "expected CPU time" a task should have gotten. 34 35 [ small detail: on "ideal" hardware, at any time all tasks would have the same 36 p->se.vruntime value --- i.e., tasks would execute simultaneously and no task 37 would ever get "out of balance" from the "ideal" share of CPU time. ] 38 39 CFS's task picking logic is based on this p->se.vruntime value and it is thus 40 very simple: it always tries to run the task with the smallest p->se.vruntime 41 value (i.e., the task which executed least so far). CFS always tries to split 42 up CPU time between runnable tasks as close to "ideal multitasking hardware" as 43 possible. 44 45 Most of the rest of CFS's design just falls out of this really simple concept, 46 with a few add-on embellishments like nice levels, multiprocessing and various 47 algorithm variants to recognize sleepers. 48 49 50 51 3. THE RBTREE 52 53 CFS's design is quite radical: it does not use the old data structures for the 54 runqueues, but it uses a time-ordered rbtree to build a "timeline" of future 55 task execution, and thus has no "array switch" artifacts (by which both the 56 previous vanilla scheduler and RSDL/SD are affected). 57 58 CFS also maintains the rq->cfs.min_vruntime value, which is a monotonic 59 increasing value tracking the smallest vruntime among all tasks in the 60 runqueue. The total amount of work done by the system is tracked using 61 min_vruntime; that value is used to place newly activated entities on the left 62 side of the tree as much as possible. 63 64 The total number of running tasks in the runqueue is accounted through the 65 rq->cfs.load value, which is the sum of the weights of the tasks queued on the 66 runqueue. 67 68 CFS maintains a time-ordered rbtree, where all runnable tasks are sorted by the 69 p->se.vruntime key. CFS picks the "leftmost" task from this tree and sticks to it. 70 As the system progresses forwards, the executed tasks are put into the tree 71 more and more to the right --- slowly but surely giving a chance for every task 72 to become the "leftmost task" and thus get on the CPU within a deterministic 73 amount of time. 74 75 Summing up, CFS works like this: it runs a task a bit, and when the task 76 schedules (or a scheduler tick happens) the task's CPU usage is "accounted 77 for": the (small) time it just spent using the physical CPU is added to 78 p->se.vruntime. Once p->se.vruntime gets high enough so that another task 79 becomes the "leftmost task" of the time-ordered rbtree it maintains (plus a 80 small amount of "granularity" distance relative to the leftmost task so that we 81 do not over-schedule tasks and trash the cache), then the new leftmost task is 82 picked and the current task is preempted. 83 84 85 86 4. SOME FEATURES OF CFS 87 88 CFS uses nanosecond granularity accounting and does not rely on any jiffies or 89 other HZ detail. Thus the CFS scheduler has no notion of "timeslices" in the 90 way the previous scheduler had, and has no heuristics whatsoever. There is 91 only one central tunable (you have to switch on CONFIG_SCHED_DEBUG): 92 93 /proc/sys/kernel/sched_min_granularity_ns 94 95 which can be used to tune the scheduler from "desktop" (i.e., low latencies) to 96 "server" (i.e., good batching) workloads. It defaults to a setting suitable 97 for desktop workloads. SCHED_BATCH is handled by the CFS scheduler module too. 98 99 Due to its design, the CFS scheduler is not prone to any of the "attacks" that 100 exist today against the heuristics of the stock scheduler: fiftyp.c, thud.c, 101 chew.c, ring-test.c, massive_intr.c all work fine and do not impact 102 interactivity and produce the expected behavior. 103 104 The CFS scheduler has a much stronger handling of nice levels and SCHED_BATCH 105 than the previous vanilla scheduler: both types of workloads are isolated much 106 more aggressively. 107 108 SMP load-balancing has been reworked/sanitized: the runqueue-walking 109 assumptions are gone from the load-balancing code now, and iterators of the 110 scheduling modules are used. The balancing code got quite a bit simpler as a 111 result. 112 113 114 115 5. Scheduling policies 116 117 CFS implements three scheduling policies: 118 119 - SCHED_NORMAL (traditionally called SCHED_OTHER): The scheduling 120 policy that is used for regular tasks. 121 122 - SCHED_BATCH: Does not preempt nearly as often as regular tasks 123 would, thereby allowing tasks to run longer and make better use of 124 caches but at the cost of interactivity. This is well suited for 125 batch jobs. 126 127 - SCHED_IDLE: This is even weaker than nice 19, but its not a true 128 idle timer scheduler in order to avoid to get into priority 129 inversion problems which would deadlock the machine. 130 131 SCHED_FIFO/_RR are implemented in sched/rt.c and are as specified by 132 POSIX. 133 134 The command chrt from util-linux-ng 2.13.1.1 can set all of these except 135 SCHED_IDLE. 136 137 138 139 6. SCHEDULING CLASSES 140 141 The new CFS scheduler has been designed in such a way to introduce "Scheduling 142 Classes," an extensible hierarchy of scheduler modules. These modules 143 encapsulate scheduling policy details and are handled by the scheduler core 144 without the core code assuming too much about them. 145 146 sched/fair.c implements the CFS scheduler described above. 147 148 sched/rt.c implements SCHED_FIFO and SCHED_RR semantics, in a simpler way than 149 the previous vanilla scheduler did. It uses 100 runqueues (for all 100 RT 150 priority levels, instead of 140 in the previous scheduler) and it needs no 151 expired array. 152 153 Scheduling classes are implemented through the sched_class structure, which 154 contains hooks to functions that must be called whenever an interesting event 155 occurs. 156 157 This is the (partial) list of the hooks: 158 159 - enqueue_task(...) 160 161 Called when a task enters a runnable state. 162 It puts the scheduling entity (task) into the red-black tree and 163 increments the nr_running variable. 164 165 - dequeue_task(...) 166 167 When a task is no longer runnable, this function is called to keep the 168 corresponding scheduling entity out of the red-black tree. It decrements 169 the nr_running variable. 170 171 - yield_task(...) 172 173 This function is basically just a dequeue followed by an enqueue, unless the 174 compat_yield sysctl is turned on; in that case, it places the scheduling 175 entity at the right-most end of the red-black tree. 176 177 - check_preempt_curr(...) 178 179 This function checks if a task that entered the runnable state should 180 preempt the currently running task. 181 182 - pick_next_task(...) 183 184 This function chooses the most appropriate task eligible to run next. 185 186 - set_curr_task(...) 187 188 This function is called when a task changes its scheduling class or changes 189 its task group. 190 191 - task_tick(...) 192 193 This function is mostly called from time tick functions; it might lead to 194 process switch. This drives the running preemption. 195 196 197 198 199 7. GROUP SCHEDULER EXTENSIONS TO CFS 200 201 Normally, the scheduler operates on individual tasks and strives to provide 202 fair CPU time to each task. Sometimes, it may be desirable to group tasks and 203 provide fair CPU time to each such task group. For example, it may be 204 desirable to first provide fair CPU time to each user on the system and then to 205 each task belonging to a user. 206 207 CONFIG_CGROUP_SCHED strives to achieve exactly that. It lets tasks to be 208 grouped and divides CPU time fairly among such groups. 209 210 CONFIG_RT_GROUP_SCHED permits to group real-time (i.e., SCHED_FIFO and 211 SCHED_RR) tasks. 212 213 CONFIG_FAIR_GROUP_SCHED permits to group CFS (i.e., SCHED_NORMAL and 214 SCHED_BATCH) tasks. 215 216 These options need CONFIG_CGROUPS to be defined, and let the administrator 217 create arbitrary groups of tasks, using the "cgroup" pseudo filesystem. See 218 Documentation/cgroup-v1/cgroups.txt for more information about this filesystem. 219 220 When CONFIG_FAIR_GROUP_SCHED is defined, a "cpu.shares" file is created for each 221 group created using the pseudo filesystem. See example steps below to create 222 task groups and modify their CPU share using the "cgroups" pseudo filesystem. 223 224 # mount -t tmpfs cgroup_root /sys/fs/cgroup 225 # mkdir /sys/fs/cgroup/cpu 226 # mount -t cgroup -ocpu none /sys/fs/cgroup/cpu 227 # cd /sys/fs/cgroup/cpu 228 229 # mkdir multimedia # create "multimedia" group of tasks 230 # mkdir browser # create "browser" group of tasks 231 232 # #Configure the multimedia group to receive twice the CPU bandwidth 233 # #that of browser group 234 235 # echo 2048 > multimedia/cpu.shares 236 # echo 1024 > browser/cpu.shares 237 238 # firefox & # Launch firefox and move it to "browser" group 239 # echo> browser/tasks 240 241 # #Launch gmplayer (or your favourite movie player) 242 # echo > multimedia/tasks
linux 4.19 中定义了6中调度策略算法;
kernel-4.19/include/uapi/linux/sched.h
kernel-4.19/include/linux/sched.h
/*
* Scheduling policies
*/
#define SCHED_NORMAL 0
#define SCHED_FIFO 1
#define SCHED_RR 2
#define SCHED_BATCH 3
/* SCHED_ISO: reserved but not implemented yet */
#define SCHED_IDLE 5
#define SCHED_DEADLINE 6
struct task_struct {
int prio;
int static_prio;
int normal_prio;
unsigned int rt_priority;
.policy = SCHED_NORMAL,
const struct sched_class *sched_class;
struct sched_entity se;
struct sched_rt_entity rt;
}
struct sched_class {
const struct sched_class *next;
#ifdef CONFIG_UCLAMP_TASK
int uclamp_enabled;
#endif
void (*enqueue_task) (struct rq *rq, struct task_struct *p, int flags);
void (*dequeue_task) (struct rq *rq, struct task_struct *p, int flags);
}
CFS 调度类
kernel-4.19/kernel/sched/fair.c
11957/*
11958 * All the scheduling class methods:
11959 */
11960const struct sched_class fair_sched_class = {
11961 .next = &idle_sched_class,
11962 .enqueue_task = enqueue_task_fair,
11963 .dequeue_task = dequeue_task_fair,
}
调度类通过next 指针链接,优先级 stop_sched_class > dl_sched_class > rt_sched_class>fair_sched_class>idle_sched_class>null ,用户空间通过sched_set/getScheduler 获取和设置
SCHED_NORMAL、SCHED_BATCH 属于cfs
SCHED_FIFO、SCHED_RR 属于rt
1821#ifdef CONFIG_SMP
1822#define sched_class_highest (&stop_sched_class)
1823#else
1824#define sched_class_highest (&dl_sched_class)
1825#endif
1826#define for_each_class(class) \
1827 for (class = sched_class_highest; class; class = class->next)
任务优先级
struct task_struct {
int prio;
int static_prio;
int normal_prio;
unsigned int rt_priority;
}
内核使用 0~139 表示进程优先级,0~99 rt 优先级,100~139给普通进程使用;另外用户空间优先级 nice -20~19 映射到普通进程优先级 100~139。
static_prio 是进程启动时分配的,内核使用,NICE_TO_PRIO() 可以将nice 和 内核优先级转换,用户可以通过nice 或sched_setscheduler 来改变。
rt_priority 实时进程优先级。
normal_prio 是基于static_prio 和 调度策略计算出来的,创建进程时会继承父进程。对应普通进程static_prio 和normal_prio 相等,对于实时进程会根据rt_priority 重新计算normal_prio(effective_prio()函数实现)
prio 对应动态优先级,有时需要暂时提供进程优先级。
# chrt -m
SCHED_OTHER min/max priority : 0/0
SCHED_FIFO min/max priority : 1/99
SCHED_RR min/max priority : 1/99
SCHED_BATCH min/max priority : 0/0
SCHED_IDLE min/max priority : 0/0
SCHED_DEADLINE min/max priority : 0/0
system_server
# chrt -p 932
pid 932's current scheduling policy: SCHED_FIFO
pid 932's current scheduling priority: 2
surfaceflinger
# chrt -p 1642
pid 1642's current scheduling policy: SCHED_OTHER
pid 1642's current scheduling priority: 0
调度实体权重
不同的调度类对应不同的调度实体,对应load_weight 对应调度权重。
struct task_struct {
struct sched_entity se;
struct sched_rt_entity rt;
}
484struct sched_entity {
485 /* For load-balancing: */
486 struct load_weight load;
487 unsigned long runnable_weight;
488 struct rb_node run_node;
489 struct list_head group_node;
490 unsigned int on_rq;
struct sched_avg avg;
}
360struct load_weight {
361 unsigned long weight;
362 u32 inv_weight;
363};
364
util_avg 和 load_avg 计算:
pelt.c
其中LOAD_AVG_MAX 对于下面的极值
对于rq runnable_load_sum 不包含rq 上睡眠任务的负载,load_sum 包含
kernel-4.19/kernel/sched/core.c
8383/*
8384 * Nice levels are multiplicative, with a gentle 10% change for every
8385 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
8386 * nice 1, it will get ~10% less CPU time than another CPU-bound task
8387 * that remained on nice 0.
8388 *
8389 * The "10% effect" is relative and cumulative: from _any_ nice level,
8390 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
8391 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
8392 * If a task goes up by ~10% and another task goes down by ~10% then
8393 * the relative distance between them is ~25%.)
8394 */
8395const int sched_prio_to_weight[40] = {
8396 /* -20 */ 88761, 71755, 56483, 46273, 36291,
8397 /* -15 */ 29154, 23254, 18705, 14949, 11916,
8398 /* -10 */ 9548, 7620, 6100, 4904, 3906,
8399 /* -5 */ 3121, 2501, 1991, 1586, 1277,
8400 /* 0 */ 1024, 820, 655, 526, 423,
8401 /* 5 */ 335, 272, 215, 172, 137,
8402 /* 10 */ 110, 87, 70, 56, 45,
8403 /* 15 */ 36, 29, 23, 18, 15,
8404};
8405
8406/*
8407 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
8408 *
8409 * In cases where the weight does not change often, we can use the
8410 * precalculated inverse to speed up arithmetics by turning divisions
8411 * into multiplications:
8412 */
8413const u32 sched_prio_to_wmult[40] = {
8414 /* -20 */ 48388, 59856, 76040, 92818, 118348,
8415 /* -15 */ 147320, 184698, 229616, 287308, 360437,
8416 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
8417 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
8418 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
8419 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
8420 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
8421 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
8422};
sched_prio_to_weight 里面将 用户空间nice 优先级 -20~19 对应cpu 执行时间权重映射,nice =0 对应 1024 ,nice 每差一个优先级,cpu 时间就相应相差 10% ;nice 对应权重约以1.25 比例增加。
A进程nice 0(权重1024),B进程nice0(权重1024),则A 、B的CPU时间,1024/(1024+1024) = 50%
A进程nice 0(权重1024),B进程nice1(权重820),则B的CPU时间,820/(1024+820) = 45%,A 的cpu 时间 55%
这里变化一个nice 优先级,CPU时间 就相差 10%
sched_prio_to_wmult[n] = (1/sched_prio_to_weight[n]) <<32
718static void set_load_weight(struct task_struct *p, bool update_load)
719{
720 int prio = p->static_prio - MAX_RT_PRIO;
721 struct load_weight *load = &p->se.load;
722
723 /*
724 * SCHED_IDLE tasks get minimal weight:
725 */
726 if (idle_policy(p->policy)) {
727 load->weight = scale_load(WEIGHT_IDLEPRIO);
728 load->inv_weight = WMULT_IDLEPRIO;
729 p->se.runnable_weight = load->weight;
730 return;
731 }
732
733 /*
734 * SCHED_OTHER tasks have to update their load when changing their
735 * weight
736 */
737 if (update_load && p->sched_class == &fair_sched_class) {
738 reweight_task(p, prio);
739 } else {
740 load->weight = scale_load(sched_prio_to_weight[prio]);
741 load->inv_weight = sched_prio_to_wmult[prio];
742 p->se.runnable_weight = load->weight;
743 }
744}
calc_delta_fair() 根据优先级及由实际运行时间到虚拟运行时间的转换;将运行的虚拟时间累加到之前已经运行的虚拟时间之上,每次选择虚拟时间最小的进程进行调度。
3.8版本之前的内核CFS调度器在计算CPU load的时候采用的是跟踪每个运行队列上的负载(per-rq load tracking)。这种粗略的负载跟踪算法显然无法为调度算法提供足够的支撑。为了完美的满足上面的所有需求,Linux调度器在3.8版中引入了PELT(Per-entity load tracking)实体负载跟踪算法。
per-entity load tracking 从两个方面反映cpu 情况:
任务的utility主要是为任务寻找合适算力的CPU,一个任务本身逻辑复杂,需要有很长的执行时间,那么随着任务的运行,内核发现其utility越来越大,那么可以根据utility选择提升其所在CPU的频率,输出更大的算力,或者将其迁移到算力更强的大核CPU上执行。Task load主要用于负载均衡算法,即让系统中的每一个CPU承担和它的算力匹配的负载。
3.8版本之前的内核CFS调度器在负载跟踪算法上比较粗糙,采用的是跟踪每个运行队列上的负载(per-rq load tracking)。它并没有跟踪每一个任务的负载和利用率,只是关注整体CPU的负载。对于per-rq的负载跟踪方法,调度器可以了解到每个运行队列对整个系统负载的贡献。这样的统计信息可以帮助调度器平衡runqueue上的负载,但从整个系统的角度看,我们并不知道当前CPU上的负载来自哪些任务,每个任务施加多少负载,当前CPU的算力是否支撑runqueue上的所有任务,是否需要提频或者迁核来解决当前CPU上负载。因此,为了更好的进行负载均衡和CPU算力调整,调度器需要PELT算法来指引方向。
PELT算法把负载跟踪算法从per rq(runqueue)推进到per-entity的层次,从而让调度器有了做更精细控制。这里per-entity中的“entity”指的是调度实体(scheduling entity),即一个进程或者control group中的一组进程。为了做到Per-entity的负载跟踪,时间被分成了1024us的序列,在每一个1024us的周期中,一个entity对系统负载的贡献可以根据该实体处于runnable状态(正在CPU上运行或者等待cpu调度运行)的时间进行计算。如果在该周期内,runnable的时间是t,那么该任务的瞬时负载应该和(t/1024)有正比的关系。类似的概念,任务的瞬时利用率应该通过1024us的周期窗口内的执行时间(不包括runqueue上的等待时间)比率来计算
per-entity load tracking 从两个方面反映cpu 情况:
任务的利用率(task utility)
任务的负载(task load)
不同优先级的任务对系统施加的负载也不同,在cfs调度算法中,高优先级的任务在一个调度周期中会有更多的执行时间,因此计算任务负载也需要考虑任务优先级,这里引入一个**负载权重(load weight)**的概念。在PELT算法中,瞬时负载Li等于
Li = load weight x (t/1024)
利用率和负载不一样,它和任务优先级无关,不过为了能够和CPU算力进行运算,任务的瞬时利用率Ui使用下面的公式计算,在手机环境中,大核最高频上的算力定义为最高算力,即1024
Ui = Max CPU capacity x (t/1024)
一个调度实体的平均负载可以表示为:
L = L0 + L1*y + L2*y2 + L3*y3 + ...
Li表示在周期pi中的瞬时负载,对于过去的负载需要乘一个衰减因子y,在目前的内核代码中,y是确定值:y ^32约等于0.5。这样选定的y值,一个调度实体的负荷贡献经过32个窗口(1024us)后,对当前时间的的符合贡献值会衰减一半。
第一个周期后 L0
第二个周期后 sum1 = L1 + y * L0
第三个周期后 sum2 = L2 + y * (L1 + y * L0) = L2 + y*sum1
第四个周期后 sum3 = L3 + y(L2 + y * (L1 + y * L0) ) = L3 + y * sum2
....
PELT算法中定义了一个struct load_weight的数据结构来表示调度实体的负载权重
struct load_weight {
unsigned long weight;
u32 inv_weight;
};
这个数据结构中的weight成员就是负载权重值,inv_weight没有实际的意义,主要是为了快速运算的。
struct load_weight可以嵌入到se或者cfs rq中,分别表示se/cfs rq的权重负载。Cfs rq的load weight等于挂入队列所有se的load weight之和。
我们可以快速计算出一个se的时间片信息:
Sched slice=sched period x se的权重/cfs rq的权重
CFS调度算法的核心就是在target latency(sched period)时间内,保证CPU资源是按照se的权重来分配的,映射到virtual runtime的世界中,cfs rq上的所有se是完全公平的。
kernel-4.19/kernel/sched/sched-pelt.h
4 #ifdef CONFIG_PELT_UTIL_HALFLIFE_32
5 static const u32 runnable_avg_yN_inv[] = {
6 0xffffffff,0xfa83b2da,0xf5257d14,0xefe4b99a,
7 0xeac0c6e6,0xe5b906e6,0xe0ccdeeb,0xdbfbb796,
8 0xd744fcc9,0xd2a81d91,0xce248c14,0xc9b9bd85,
9 0xc5672a10,0xc12c4cc9,0xbd08a39e,0xb8fbaf46,
10 0xb504f333,0xb123f581,0xad583ee9,0xa9a15ab4,
11 0xa5fed6a9,0xa2704302,0x9ef5325f,0x9b8d39b9,
12 0x9837f050,0x94f4efa8,0x91c3d373,0x8ea4398a,
13 0x8b95c1e3,0x88980e80,0x85aac367,0x82cd8698,
14 };
15
16 static const u32 runnable_avg_yN_sum[] = {
17 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
18 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
19 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
20 };
runnable_avg_yN_inv[i]=(2^32-1) * y^i
y^32=1/2
i=0~31
y~=0.9785
Static const u32 runnable_avg_yN_org[] = {
0.999, 0.978, 0.957, 0.937, 0.917, 0.897,
……
0.522, 0.510
}
runnable_avg_yN_org[i]=runnable_avg_yN_inv[i]>>32
static const u32 runnable_avg_yN_sum[] = {
0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103, 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082, 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
};
runnable_avg_yN_sum[n]=1024*(y^1+y^2+y^3+……+y^n)
1024:1ms
period=1024us
y~=0.9785; y^32=1/2
static u64 decay_load(u64 val, u64 n)
val表示n个周期前的负载值,n表示第n个周期
t0时刻负载为val,t1时刻,红色历史时间区域衰减负载值是:val*y^n=val* runnable_avg_yN_inv[n]>>32
调度器 schedule pelt 介绍【转】 - 走看看
Linux调度器:PELT(Per-entity load tracking)实体负载跟踪算法调度算法_rtoax的博客-CSDN博客_linux pelt
参考
万字长文丨深入理解Linux进程调度 - 知乎
__sched_period(...)
694 /*
695 * The idea is to set a period in which each task runs once.
696 *
697 * When there are too many tasks (sched_nr_latency) we have to stretch
698 * this period because otherwise the slices get too small.
699 *
700 * p = (nr <= nl) ? l : l*nr/nl
701 */
702 static u64 __sched_period(unsigned long nr_running)
703 {
704 if (unlikely(nr_running > sched_nr_latency))
705 return nr_running * sysctl_sched_min_granularity;
706 else
707 return sysctl_sched_latency;
708 }
709
710 /*
711 * We calculate the wall-time slice from the period by taking a part
712 * proportional to the weight.
713 *
714 * s = p*P[w/rw]
715 */
716 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
717 {
718 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
719
720 for_each_sched_entity(se) {
721 struct load_weight *load;
722 struct load_weight lw;
723
724 cfs_rq = cfs_rq_of(se);
725 load = &cfs_rq->load;
726
727 if (unlikely(!se->on_rq)) {
728 lw = cfs_rq->load;
729
730 update_load_add(&lw, se->load.weight);
731 load = &lw;
732 }
733 slice = __calc_delta(slice, se->load.weight, load);
734 }
735 return slice;
736 }
737
738 /*
739 * We calculate the vruntime slice of a to-be-inserted task.
740 *
741 * vs = s/w
742 */
743 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
744 {
745 return calc_delta_fair(sched_slice(cfs_rq, se), se);
746 }
CFS 调度中,
kernel/sched/fair.c
调度粒度、唤醒粒度、调度延迟
static unsigned int sched_nr_latency = 8;//进程数目
unsigned int sysctl_sched_min_granularity = 750000ULL;//每个进程的最小运行时间 0.75ms;调度粒度
unsigned int sysctl_sched_latency = 6000000ULL;//默认分配时间片 6ms;调度延迟
//唤醒粒度 87 unsigned int sysctl_sched_wakeup_granularity = 1000000UL; 88 static unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
将唤醒粒度按照calc_delta 换算到虚拟时间,只有被唤醒的任务虚拟时间比当前任务虚拟时间小换算的虚拟时间以上,才能唤醒强制当前任务。
/*
* delta /= w
*/
static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
{
if (unlikely(se->load.weight != NICE_0_LOAD))
delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
return delta;
}
tunable_scaling 配置上面调度粒度、唤醒粒度、调度延迟 ,默认为1 就是按照上面的值
/* 47 * The initial- and re-scaling of tunables is configurable 48 * 49 * Options are: 50 * 51 * SCHED_TUNABLESCALING_NONE - unscaled, always *1 52 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus) 53 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus 54 * 55 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus)) 56 */ 57 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
enum sched_tunable_scaling {
SCHED_TUNABLESCALING_NONE,
SCHED_TUNABLESCALING_LOG,
SCHED_TUNABLESCALING_LINEAR,
SCHED_TUNABLESCALING_END,
};
/sys/kernel/debug/sched # cat tunable_scaling
调度周期__sched_period:
当进程数 <= sched_nr_latency(8)时,值固定为sysctl_sched_latency(6ms)
当进程数 > sched_nr_latency(8)时,值为sysctl_sched_min_granularity*进程数
sched_slice 根据当前进程的权重来计算在CFS 就绪队列中可以瓜分到的调度时间。
sched_vslice根据sched_slice可以得到的虚拟时间
fork 新进程,在task_for_fair 中place_entiry,cfs_rq 父进程 ,se 新创建进程,initial 1;
cfs_rq->min_vruntime 记录就绪队列rb_tree 中最新的vruntime;这里相当新创建进程导致CFS 运行队列权重发生了变化对vruntime 进行增加一点。
static void
4033 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
4034 {
4035 u64 vruntime = cfs_rq->min_vruntime;
4036
4037 /*
4038 * The 'current' period is already promised to the current tasks,
4039 * however the extra weight of the new task will slow them down a
4040 * little, place the new task so that it fits in the slot that
4041 * stays open at the end.
4042 */
4043 if (initial && sched_feat(START_DEBIT))
4044 vruntime += sched_vslice(cfs_rq, se);
4045
4046 /* sleeps up to a single latency don't count. */
4047 if (!initial) {
4048 unsigned long thresh = sysctl_sched_latency;
4049
4050 /*
4051 * Halve their sleep time's effect, to allow
4052 * for a gentler effect of sleepers:
4053 */
4054 if (sched_feat(GENTLE_FAIR_SLEEPERS))
4055 thresh >>= 1;
4056
4057 vruntime -= thresh;
4058 }
4059
4060 /* ensure we never gain time by being placed backwards. */
4061 se->vruntime = max_vruntime(se->vruntime, vruntime);
4062
4063 place_entity_adjust_ux_task(cfs_rq, se, initial);
4064
4065 }
内核使用rb_tree 来保存可以运行(就绪)task 的节点;cfs跟踪调度实体sched_entity的虚拟运行时间vruntime,将sched_entity通过enqueue_entity()和dequeue_entity()来进行红黑树的出列入列。
schedule()->pick_next_task->pick_next_task_fair 根据cfs 调度器选择下一个任务执行;
7836 static struct task_struct *
7837 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
7838 {
7839 struct cfs_rq *cfs_rq = &rq->cfs;
7840 struct sched_entity *se;
7841 struct task_struct *p;
7842 int new_tasks;
7852 /*
7853 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
7854 * likely that a next task is from the same cgroup as the current.
7855 *
7856 * Therefore attempt to avoid putting and setting the entire cgroup
7857 * hierarchy, only change the part that actually changes.
7858 */
7859 put_prev_task(rq, prev);
7930
7931 do {
7932 se = pick_next_entity(cfs_rq, NULL);
7933 set_next_entity(cfs_rq, se);
7934 cfs_rq = group_cfs_rq(se); //null for not support cgroup
7935 } while (cfs_rq);
7936
7937 p = task_of(se);
}
put_prev_task -》put_prev_entity方法
prev->on_rq 说明线程是就绪状态,需要将任务加入到就绪队列cfs_rq红黑树上;比如try_to_wakeup 唤醒切换任务,对于非内核线程prev 是就绪状态,但是内核任务不一定是就绪状态。
就绪队列的rq clock 在tick 到来时会更新,获取当前时钟,从而得到执行的时间,再根据执行的时间得到执行的虚拟时间。
当前被调度出来的task 入cfs rq
wakeup_preempt_entity(new_se,old_se)<1
当且仅当new_se->vruntime-old_se->vruntime 小于某种最小调度粒度,认为此时的抢占是比较公平的.
pick_next_entity 选中下一个任务后,如果下一个任务之前是就绪状态,就需要将其从cfs_rq 就绪队列红黑树上摘除。
挑选结束下一个进程,接下来通过_schedule()->context_switch()进行进程切换。
进程休眠被唤醒是,根据min_vruntime 基础重新设置,给与一定的补偿,但是不是很多,就像fork 创建进程根据min_vruntime 给与一定的惩罚。
task负载计算:load_avg_contrib=runnable_avg_sum*weight/runnable_avg_period
runnable_avg_sum 总的PI 周期衰减时间,runnable_avg_sum 总的 PI 周期里面可运行状态时间衰减时间,负载就是可运行时间占比乘以一个优先级权重值。