sched-design-CFS.rst 9.9 KB

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