brintos

brintos / linux-shallow public Read only

0
0
Text · 9.9 KiB · 8786f21 Raw
257 lines · plain
1.. _sched_design_CFS:2 3=============4CFS Scheduler5=============6 7 81.  OVERVIEW9============10 11CFS stands for "Completely Fair Scheduler," and is the "desktop" process12scheduler implemented by Ingo Molnar and merged in Linux 2.6.23. When13originally merged, it was the replacement for the previous vanilla14scheduler's SCHED_OTHER interactivity code. Nowadays, CFS is making room15for EEVDF, for which documentation can be found in16Documentation/scheduler/sched-eevdf.rst.17 1880% of CFS's design can be summed up in a single sentence: CFS basically models19an "ideal, precise multi-tasking CPU" on real hardware.20 21"Ideal multi-tasking CPU" is a (non-existent  :-)) CPU that has 100% physical22power and which can run each task at precise equal speed, in parallel, each at231/nr_running speed.  For example: if there are 2 tasks running, then it runs24each at 50% physical power --- i.e., actually in parallel.25 26On real hardware, we can run only a single task at once, so we have to27introduce the concept of "virtual runtime."  The virtual runtime of a task28specifies when its next timeslice would start execution on the ideal29multi-tasking CPU described above.  In practice, the virtual runtime of a task30is its actual runtime normalized to the total number of running tasks.31 32 33 342.  FEW IMPLEMENTATION DETAILS35==============================36 37In CFS the virtual runtime is expressed and tracked via the per-task38p->se.vruntime (nanosec-unit) value.  This way, it's possible to accurately39timestamp and measure the "expected CPU time" a task should have gotten.40 41   Small detail: on "ideal" hardware, at any time all tasks would have the same42   p->se.vruntime value --- i.e., tasks would execute simultaneously and no task43   would ever get "out of balance" from the "ideal" share of CPU time.44 45CFS's task picking logic is based on this p->se.vruntime value and it is thus46very simple: it always tries to run the task with the smallest p->se.vruntime47value (i.e., the task which executed least so far).  CFS always tries to split48up CPU time between runnable tasks as close to "ideal multitasking hardware" as49possible.50 51Most of the rest of CFS's design just falls out of this really simple concept,52with a few add-on embellishments like nice levels, multiprocessing and various53algorithm variants to recognize sleepers.54 55 56 573.  THE RBTREE58==============59 60CFS's design is quite radical: it does not use the old data structures for the61runqueues, but it uses a time-ordered rbtree to build a "timeline" of future62task execution, and thus has no "array switch" artifacts (by which both the63previous vanilla scheduler and RSDL/SD are affected).64 65CFS also maintains the rq->cfs.min_vruntime value, which is a monotonic66increasing value tracking the smallest vruntime among all tasks in the67runqueue.  The total amount of work done by the system is tracked using68min_vruntime; that value is used to place newly activated entities on the left69side of the tree as much as possible.70 71The total number of running tasks in the runqueue is accounted through the72rq->cfs.load value, which is the sum of the weights of the tasks queued on the73runqueue.74 75CFS maintains a time-ordered rbtree, where all runnable tasks are sorted by the76p->se.vruntime key. CFS picks the "leftmost" task from this tree and sticks to it.77As the system progresses forwards, the executed tasks are put into the tree78more and more to the right --- slowly but surely giving a chance for every task79to become the "leftmost task" and thus get on the CPU within a deterministic80amount of time.81 82Summing up, CFS works like this: it runs a task a bit, and when the task83schedules (or a scheduler tick happens) the task's CPU usage is "accounted84for": the (small) time it just spent using the physical CPU is added to85p->se.vruntime.  Once p->se.vruntime gets high enough so that another task86becomes the "leftmost task" of the time-ordered rbtree it maintains (plus a87small amount of "granularity" distance relative to the leftmost task so that we88do not over-schedule tasks and trash the cache), then the new leftmost task is89picked and the current task is preempted.90 91 92 934.  SOME FEATURES OF CFS94========================95 96CFS uses nanosecond granularity accounting and does not rely on any jiffies or97other HZ detail.  Thus the CFS scheduler has no notion of "timeslices" in the98way the previous scheduler had, and has no heuristics whatsoever.  There is99only one central tunable (you have to switch on CONFIG_SCHED_DEBUG):100 101   /sys/kernel/debug/sched/base_slice_ns102 103which can be used to tune the scheduler from "desktop" (i.e., low latencies) to104"server" (i.e., good batching) workloads.  It defaults to a setting suitable105for desktop workloads.  SCHED_BATCH is handled by the CFS scheduler module too.106 107In case CONFIG_HZ results in base_slice_ns < TICK_NSEC, the value of108base_slice_ns will have little to no impact on the workloads.109 110Due to its design, the CFS scheduler is not prone to any of the "attacks" that111exist today against the heuristics of the stock scheduler: fiftyp.c, thud.c,112chew.c, ring-test.c, massive_intr.c all work fine and do not impact113interactivity and produce the expected behavior.114 115The CFS scheduler has a much stronger handling of nice levels and SCHED_BATCH116than the previous vanilla scheduler: both types of workloads are isolated much117more aggressively.118 119SMP load-balancing has been reworked/sanitized: the runqueue-walking120assumptions are gone from the load-balancing code now, and iterators of the121scheduling modules are used.  The balancing code got quite a bit simpler as a122result.123 124 125 1265. Scheduling policies127======================128 129CFS implements three scheduling policies:130 131  - SCHED_NORMAL (traditionally called SCHED_OTHER): The scheduling132    policy that is used for regular tasks.133 134  - SCHED_BATCH: Does not preempt nearly as often as regular tasks135    would, thereby allowing tasks to run longer and make better use of136    caches but at the cost of interactivity. This is well suited for137    batch jobs.138 139  - SCHED_IDLE: This is even weaker than nice 19, but its not a true140    idle timer scheduler in order to avoid to get into priority141    inversion problems which would deadlock the machine.142 143SCHED_FIFO/_RR are implemented in sched/rt.c and are as specified by144POSIX.145 146The command chrt from util-linux-ng 2.13.1.1 can set all of these except147SCHED_IDLE.148 149 150 1516.  SCHEDULING CLASSES152======================153 154The new CFS scheduler has been designed in such a way to introduce "Scheduling155Classes," an extensible hierarchy of scheduler modules.  These modules156encapsulate scheduling policy details and are handled by the scheduler core157without the core code assuming too much about them.158 159sched/fair.c implements the CFS scheduler described above.160 161sched/rt.c implements SCHED_FIFO and SCHED_RR semantics, in a simpler way than162the previous vanilla scheduler did.  It uses 100 runqueues (for all 100 RT163priority levels, instead of 140 in the previous scheduler) and it needs no164expired array.165 166Scheduling classes are implemented through the sched_class structure, which167contains hooks to functions that must be called whenever an interesting event168occurs.169 170This is the (partial) list of the hooks:171 172 - enqueue_task(...)173 174   Called when a task enters a runnable state.175   It puts the scheduling entity (task) into the red-black tree and176   increments the nr_running variable.177 178 - dequeue_task(...)179 180   When a task is no longer runnable, this function is called to keep the181   corresponding scheduling entity out of the red-black tree.  It decrements182   the nr_running variable.183 184 - yield_task(...)185 186   This function is basically just a dequeue followed by an enqueue, unless the187   compat_yield sysctl is turned on; in that case, it places the scheduling188   entity at the right-most end of the red-black tree.189 190 - wakeup_preempt(...)191 192   This function checks if a task that entered the runnable state should193   preempt the currently running task.194 195 - pick_next_task(...)196 197   This function chooses the most appropriate task eligible to run next.198 199 - set_next_task(...)200 201   This function is called when a task changes its scheduling class, changes202   its task group or is scheduled.203 204 - task_tick(...)205 206   This function is mostly called from time tick functions; it might lead to207   process switch.  This drives the running preemption.208 209 210 211 2127.  GROUP SCHEDULER EXTENSIONS TO CFS213=====================================214 215Normally, the scheduler operates on individual tasks and strives to provide216fair CPU time to each task.  Sometimes, it may be desirable to group tasks and217provide fair CPU time to each such task group.  For example, it may be218desirable to first provide fair CPU time to each user on the system and then to219each task belonging to a user.220 221CONFIG_CGROUP_SCHED strives to achieve exactly that.  It lets tasks to be222grouped and divides CPU time fairly among such groups.223 224CONFIG_RT_GROUP_SCHED permits to group real-time (i.e., SCHED_FIFO and225SCHED_RR) tasks.226 227CONFIG_FAIR_GROUP_SCHED permits to group CFS (i.e., SCHED_NORMAL and228SCHED_BATCH) tasks.229 230   These options need CONFIG_CGROUPS to be defined, and let the administrator231   create arbitrary groups of tasks, using the "cgroup" pseudo filesystem.  See232   Documentation/admin-guide/cgroup-v1/cgroups.rst for more information about this filesystem.233 234When CONFIG_FAIR_GROUP_SCHED is defined, a "cpu.shares" file is created for each235group created using the pseudo filesystem.  See example steps below to create236task groups and modify their CPU share using the "cgroups" pseudo filesystem::237 238	# mount -t tmpfs cgroup_root /sys/fs/cgroup239	# mkdir /sys/fs/cgroup/cpu240	# mount -t cgroup -ocpu none /sys/fs/cgroup/cpu241	# cd /sys/fs/cgroup/cpu242 243	# mkdir multimedia	# create "multimedia" group of tasks244	# mkdir browser		# create "browser" group of tasks245 246	# #Configure the multimedia group to receive twice the CPU bandwidth247	# #that of browser group248 249	# echo 2048 > multimedia/cpu.shares250	# echo 1024 > browser/cpu.shares251 252	# firefox &	# Launch firefox and move it to "browser" group253	# echo <firefox_pid> > browser/tasks254 255	# #Launch gmplayer (or your favourite movie player)256	# echo <movie_player_pid> > multimedia/tasks257