1.. _sched_design_CFS: 2 3============= 4CFS Scheduler 5============= 6 7 81. OVERVIEW 9============ 10 11CFS stands for "Completely Fair Scheduler," and is the new "desktop" process 12scheduler implemented by Ingo Molnar and merged in Linux 2.6.23. It is the 13replacement for the previous vanilla scheduler's SCHED_OTHER interactivity 14code. 15 1680% of CFS's design can be summed up in a single sentence: CFS basically models 17an "ideal, precise multi-tasking CPU" on real hardware. 18 19"Ideal multi-tasking CPU" is a (non-existent :-)) CPU that has 100% physical 20power and which can run each task at precise equal speed, in parallel, each at 211/nr_running speed. For example: if there are 2 tasks running, then it runs 22each at 50% physical power --- i.e., actually in parallel. 23 24On real hardware, we can run only a single task at once, so we have to 25introduce the concept of "virtual runtime." The virtual runtime of a task 26specifies when its next timeslice would start execution on the ideal 27multi-tasking CPU described above. In practice, the virtual runtime of a task 28is its actual runtime normalized to the total number of running tasks. 29 30 31 322. FEW IMPLEMENTATION DETAILS 33============================== 34 35In CFS the virtual runtime is expressed and tracked via the per-task 36p->se.vruntime (nanosec-unit) value. This way, it's possible to accurately 37timestamp and measure the "expected CPU time" a task should have gotten. 38 39 Small detail: on "ideal" hardware, at any time all tasks would have the same 40 p->se.vruntime value --- i.e., tasks would execute simultaneously and no task 41 would ever get "out of balance" from the "ideal" share of CPU time. 42 43CFS's task picking logic is based on this p->se.vruntime value and it is thus 44very simple: it always tries to run the task with the smallest p->se.vruntime 45value (i.e., the task which executed least so far). CFS always tries to split 46up CPU time between runnable tasks as close to "ideal multitasking hardware" as 47possible. 48 49Most of the rest of CFS's design just falls out of this really simple concept, 50with a few add-on embellishments like nice levels, multiprocessing and various 51algorithm variants to recognize sleepers. 52 53 54 553. THE RBTREE 56============== 57 58CFS's design is quite radical: it does not use the old data structures for the 59runqueues, but it uses a time-ordered rbtree to build a "timeline" of future 60task execution, and thus has no "array switch" artifacts (by which both the 61previous vanilla scheduler and RSDL/SD are affected). 62 63CFS also maintains the rq->cfs.min_vruntime value, which is a monotonic 64increasing value tracking the smallest vruntime among all tasks in the 65runqueue. The total amount of work done by the system is tracked using 66min_vruntime; that value is used to place newly activated entities on the left 67side of the tree as much as possible. 68 69The total number of running tasks in the runqueue is accounted through the 70rq->cfs.load value, which is the sum of the weights of the tasks queued on the 71runqueue. 72 73CFS maintains a time-ordered rbtree, where all runnable tasks are sorted by the 74p->se.vruntime key. CFS picks the "leftmost" task from this tree and sticks to it. 75As the system progresses forwards, the executed tasks are put into the tree 76more and more to the right --- slowly but surely giving a chance for every task 77to become the "leftmost task" and thus get on the CPU within a deterministic 78amount of time. 79 80Summing up, CFS works like this: it runs a task a bit, and when the task 81schedules (or a scheduler tick happens) the task's CPU usage is "accounted 82for": the (small) time it just spent using the physical CPU is added to 83p->se.vruntime. Once p->se.vruntime gets high enough so that another task 84becomes the "leftmost task" of the time-ordered rbtree it maintains (plus a 85small amount of "granularity" distance relative to the leftmost task so that we 86do not over-schedule tasks and trash the cache), then the new leftmost task is 87picked and the current task is preempted. 88 89 90 914. SOME FEATURES OF CFS 92======================== 93 94CFS uses nanosecond granularity accounting and does not rely on any jiffies or 95other HZ detail. Thus the CFS scheduler has no notion of "timeslices" in the 96way the previous scheduler had, and has no heuristics whatsoever. There is 97only one central tunable (you have to switch on CONFIG_SCHED_DEBUG): 98 99 /sys/kernel/debug/sched/base_slice_ns 100 101which can be used to tune the scheduler from "desktop" (i.e., low latencies) to 102"server" (i.e., good batching) workloads. It defaults to a setting suitable 103for desktop workloads. SCHED_BATCH is handled by the CFS scheduler module too. 104 105In case CONFIG_HZ results in base_slice_ns < TICK_NSEC, the value of 106base_slice_ns will have little to no impact on the workloads. 107 108Due to its design, the CFS scheduler is not prone to any of the "attacks" that 109exist today against the heuristics of the stock scheduler: fiftyp.c, thud.c, 110chew.c, ring-test.c, massive_intr.c all work fine and do not impact 111interactivity and produce the expected behavior. 112 113The CFS scheduler has a much stronger handling of nice levels and SCHED_BATCH 114than the previous vanilla scheduler: both types of workloads are isolated much 115more aggressively. 116 117SMP load-balancing has been reworked/sanitized: the runqueue-walking 118assumptions are gone from the load-balancing code now, and iterators of the 119scheduling modules are used. The balancing code got quite a bit simpler as a 120result. 121 122 123 1245. Scheduling policies 125====================== 126 127CFS implements three scheduling policies: 128 129 - SCHED_NORMAL (traditionally called SCHED_OTHER): The scheduling 130 policy that is used for regular tasks. 131 132 - SCHED_BATCH: Does not preempt nearly as often as regular tasks 133 would, thereby allowing tasks to run longer and make better use of 134 caches but at the cost of interactivity. This is well suited for 135 batch jobs. 136 137 - SCHED_IDLE: This is even weaker than nice 19, but its not a true 138 idle timer scheduler in order to avoid to get into priority 139 inversion problems which would deadlock the machine. 140 141SCHED_FIFO/_RR are implemented in sched/rt.c and are as specified by 142POSIX. 143 144The command chrt from util-linux-ng 2.13.1.1 can set all of these except 145SCHED_IDLE. 146 147 148 1496. SCHEDULING CLASSES 150====================== 151 152The new CFS scheduler has been designed in such a way to introduce "Scheduling 153Classes," an extensible hierarchy of scheduler modules. These modules 154encapsulate scheduling policy details and are handled by the scheduler core 155without the core code assuming too much about them. 156 157sched/fair.c implements the CFS scheduler described above. 158 159sched/rt.c implements SCHED_FIFO and SCHED_RR semantics, in a simpler way than 160the previous vanilla scheduler did. It uses 100 runqueues (for all 100 RT 161priority levels, instead of 140 in the previous scheduler) and it needs no 162expired array. 163 164Scheduling classes are implemented through the sched_class structure, which 165contains hooks to functions that must be called whenever an interesting event 166occurs. 167 168This is the (partial) list of the hooks: 169 170 - enqueue_task(...) 171 172 Called when a task enters a runnable state. 173 It puts the scheduling entity (task) into the red-black tree and 174 increments the nr_running variable. 175 176 - dequeue_task(...) 177 178 When a task is no longer runnable, this function is called to keep the 179 corresponding scheduling entity out of the red-black tree. It decrements 180 the nr_running variable. 181 182 - yield_task(...) 183 184 This function is basically just a dequeue followed by an enqueue, unless the 185 compat_yield sysctl is turned on; in that case, it places the scheduling 186 entity at the right-most end of the red-black tree. 187 188 - wakeup_preempt(...) 189 190 This function checks if a task that entered the runnable state should 191 preempt the currently running task. 192 193 - pick_next_task(...) 194 195 This function chooses the most appropriate task eligible to run next. 196 197 - set_next_task(...) 198 199 This function is called when a task changes its scheduling class, changes 200 its task group or is scheduled. 201 202 - task_tick(...) 203 204 This function is mostly called from time tick functions; it might lead to 205 process switch. This drives the running preemption. 206 207 208 209 2107. GROUP SCHEDULER EXTENSIONS TO CFS 211===================================== 212 213Normally, the scheduler operates on individual tasks and strives to provide 214fair CPU time to each task. Sometimes, it may be desirable to group tasks and 215provide fair CPU time to each such task group. For example, it may be 216desirable to first provide fair CPU time to each user on the system and then to 217each task belonging to a user. 218 219CONFIG_CGROUP_SCHED strives to achieve exactly that. It lets tasks to be 220grouped and divides CPU time fairly among such groups. 221 222CONFIG_RT_GROUP_SCHED permits to group real-time (i.e., SCHED_FIFO and 223SCHED_RR) tasks. 224 225CONFIG_FAIR_GROUP_SCHED permits to group CFS (i.e., SCHED_NORMAL and 226SCHED_BATCH) tasks. 227 228 These options need CONFIG_CGROUPS to be defined, and let the administrator 229 create arbitrary groups of tasks, using the "cgroup" pseudo filesystem. See 230 Documentation/admin-guide/cgroup-v1/cgroups.rst for more information about this filesystem. 231 232When CONFIG_FAIR_GROUP_SCHED is defined, a "cpu.shares" file is created for each 233group created using the pseudo filesystem. See example steps below to create 234task groups and modify their CPU share using the "cgroups" pseudo filesystem:: 235 236 # mount -t tmpfs cgroup_root /sys/fs/cgroup 237 # mkdir /sys/fs/cgroup/cpu 238 # mount -t cgroup -ocpu none /sys/fs/cgroup/cpu 239 # cd /sys/fs/cgroup/cpu 240 241 # mkdir multimedia # create "multimedia" group of tasks 242 # mkdir browser # create "browser" group of tasks 243 244 # #Configure the multimedia group to receive twice the CPU bandwidth 245 # #that of browser group 246 247 # echo 2048 > multimedia/cpu.shares 248 # echo 1024 > browser/cpu.shares 249 250 # firefox & # Launch firefox and move it to "browser" group 251 # echo <firefox_pid> > browser/tasks 252 253 # #Launch gmplayer (or your favourite movie player) 254 # echo <movie_player_pid> > multimedia/tasks 255