ENع
→Fair-share scheduling and CFS
الدرس 16 · CPU scheduling

Fair-share scheduling and Linux CFS

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة9 خطوات5 أسئلةIntermediate
عن هذا الدرس

The multi-level feedback queue guesses which jobs are short. A fair-share scheduler asks a different question: has every task had its share of the CPU? Linux's Completely Fair Scheduler (CFS) answers it with one counter per task, the virtual runtime. It keeps runnable tasks sorted by that counter in a red-black tree and always runs the leftmost one. Weights from the nice value set each task's share, and a waking task is lifted so it cannot hog the CPU. Follow three tasks through 144 ms on one core: two ordinary ones and a nice one, one of which sleeps on the disk. The lessons on round robin and the time slice and on the multi-level feedback queue are the background; the context switch from the processes module is what happens each time a task leaves the CPU.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 16 · تفاعلي
01 / 09

Fair share, not priority

Fair share means every task gets its share of the CPU. Linux's Completely Fair Scheduler (CFS) keeps no priority queues. It counts each task's virtual runtime (vruntime): roughly, how much CPU it has had. The task with the least runs next.

ideal: n tasks, each gets 1/n of the CPU at once
real:  one core, one task at a time, so CFS keeps
       a counter per task and repairs the gap

vruntime   the task's CPU time, scaled by its weight
rule       run the task with the smallest vruntime

period     sched_latency = 48 ms: every runnable task
           runs once in this time
floor      min_granularity = 6 ms: no slice is shorter
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Fair share, not priority

    Fair share means every task gets its share of the CPU. Linux's Completely Fair Scheduler (CFS) keeps no priority queues. It counts each task's virtual runtime (vruntime): roughly, how much CPU it has had. The task with the least runs next.

    ideal: n tasks, each gets 1/n of the CPU at once
    real:  one core, one task at a time, so CFS keeps
           a counter per task and repairs the gap
    
    vruntime   the task's CPU time, scaled by its weight
    rule       run the task with the smallest vruntime
    
    period     sched_latency = 48 ms: every runnable task
               runs once in this time
    floor      min_granularity = 6 ms: no slice is shorter
  2. Sorted by vruntime

    Three tasks start at 0 ms, all with vruntime 0. CFS keeps runnable tasks in a red-black tree, a structure that stays sorted, here by vruntime. The leftmost task runs next. Ties keep their arrival order, so A goes first.

    task   nice   weight
    A       0     1024
    B       5      335
    C       0     1024
    
    the tree, leftmost first:  A 0.0   B 0.0   C 0.0
    t = 0      A is leftmost: A goes onto the CPU
    
    in the figure a task stands as far right
    on the run queue as its vruntime
  3. A slice is a share

    A's slice is its share of the 48 ms period: 48 × 1024 / 2383 = 20.6 ms, where 2383 is all three weights added up. After it, A's vruntime is 20.6, so A moves right. B is now leftmost.

    slice = period × weight / (sum of runnable weights)
          = 48 × 1024 / (1024 + 335 + 1024)
          = 48 × 1024 / 2383 = 20.6 ms
    
    vruntime += runtime × 1024 / weight
    A: 0 + 20.6 × 1024 / 1024 = 20.6
    
    t = 0..20.6   A runs
    t = 20.6      A back in the tree, at the right
  4. Nice tasks count faster

    B asked to be nice: nice 5, weight 335 instead of 1024. Its slice is only 6.7 ms. But its vruntime grows about three times faster than real time: 6.7 × 1024 / 335 = 20.6. B lands level with A.

    B: slice = 48 × 335 / 2383 = 6.7 ms
       vruntime 0 + 6.7 × 1024 / 335 = 20.6
    
    each step of nice is a factor of about 1.25:
    nice 5 vs nice 0: 1024 / 335 = 3.06
    
    B as a real program (C99, POSIX):
    
    #define _XOPEN_SOURCE 700
    #include <stdio.h>
    #include <sys/resource.h>
    
    int main(void) {
        /* be nice: nice 5, so CFS gives weight 335, not 1024 */
        if (setpriority(PRIO_PROCESS, 0, 5) != 0) {
            perror("setpriority");
            return 1;
        }
        printf("nice %d\n", getpriority(PRIO_PROCESS, 0));
        volatile unsigned long x = 0;
        while (x < 50000000UL) x++;   /* CPU-bound work */
        return 0;
    }
  5. Equal vruntime is fair

    C runs 20.6 ms, then waits for the disk. After this 48 ms period all three reached vruntime 20.6. A and C each had 20.6 ms of CPU, B had 6.7 ms: shares in proportion to weight.

    t = 27.4..48.0   C runs 20.6 ms, then reads the disk
    
    task   CPU time   share   vruntime
    A      20.6 ms    43 %    20.6
    B       6.7 ms    14 %    20.6
    C      20.6 ms    43 %    20.6
    
    equal vruntime = CPU time in proportion to weight
  6. Fewer tasks, longer slices

    A sleeping task leaves the tree. Only A and B share the 48 ms period now, so both slices grow: A runs 36.2 ms, B gets 11.8 ms. A ends at vruntime 56.8, so B is leftmost and runs.

    C sleeps: it is not in the tree, it is not counted
    
    A: slice = 48 × 1024 / (1024 + 335) = 36.2 ms
    B: slice = 48 × 335 / (1024 + 335)  = 11.8 ms
    
    t = 48.0..84.2   A runs, vruntime 20.6 -> 56.8
    t = 84.2..96.0   B runs, vruntime 20.6 -> 56.8
  7. Waking up: no catching up

    At 96 ms C wakes. Its vruntime is still 20.6, far behind A and B at 56.8: it would run 36.2 ms straight to catch up. CFS instead lifts it to the smallest vruntime in the tree, 56.8.

    t = 96.0   B back in the tree at 56.8
               C wakes: vruntime 20.6
               smallest in the tree: 56.8
               C lifted to 56.8
    
    without the lift, C would be leftmost until its
    vruntime passed 56.8: 36.2 ms with A and B shut out
    
    the cost: a task that sleeps often loses a little
  8. Sharing again

    All three share again: A runs 20.6 ms, B 6.7 ms, then C 20.6 ms from 123.4 ms. Sleeping earned C no extra CPU, and A and B were never shut out. At 144 ms all three stand at 77.4.

    t =  96.0   A runs 20.6 ms   vruntime 56.8 -> 77.4
    t = 116.6   B runs  6.7 ms   vruntime 56.8 -> 77.4
    t = 123.4   C runs 20.6 ms   vruntime 56.8 -> 77.4
    
    over the 144 ms:
    A    77.4 ms of CPU
    B    25.3 ms of CPU
    C    41.3 ms of CPU
  9. Why a tree

    With thousands of tasks, a sorted list is slow to keep in order. In a red-black tree, inserting and removing a task take O(log n) steps. Linux ran CFS from 2.6.23; since 6.6 it has moved to EEVDF, which still tracks virtual run time.

    CFS as a Python simulation:
    
    LATENCY, NICE0 = 48, 1024          # ms; weight of nice 0
    weight = {"A": 1024, "B": 335, "C": 1024}   # nice 0, 5, 0
    nap = {"C": 48}                     # C waits 48 ms for the disk once
    vr = {j: 0.0 for j in weight}        # vruntime
    tree = ["A", "B", "C"]               # runnable, leftmost first
    asleep, t = {}, 0.0
    while t < 144 - 1e-9:
        for j in [j for j in asleep if asleep[j] <= t + 1e-9]:
            del asleep[j]                # wake: lift to the smallest vruntime
            vr[j] = max(vr[j], min(vr[k] for k in tree))
            tree.append(j)
        tree.sort(key=lambda j: round(vr[j], 6))   # ties keep their order
        j = tree.pop(0)                  # the leftmost task runs
        total = weight[j] + sum(weight[k] for k in tree)
        s = LATENCY * weight[j] / total  # its slice of the period
        v0 = vr[j]
        vr[j] += s * NICE0 / weight[j]
        print(f"{t:5.1f}  {j} runs {s:4.1f} ms  vruntime {v0:4.1f} -> {vr[j]:4.1f}")
        t += s
        if j in nap: asleep[j] = t + nap.pop(j)   # sleeps: leaves the tree
        else: tree.append(j)
    
    prints:
      0.0  A runs 20.6 ms  vruntime  0.0 -> 20.6
     20.6  B runs  6.7 ms  vruntime  0.0 -> 20.6
     27.4  C runs 20.6 ms  vruntime  0.0 -> 20.6
     48.0  A runs 36.2 ms  vruntime 20.6 -> 56.8
     84.2  B runs 11.8 ms  vruntime 20.6 -> 56.8
     96.0  A runs 20.6 ms  vruntime 56.8 -> 77.4
    116.6  B runs  6.7 ms  vruntime 56.8 -> 77.4
    123.4  C runs 20.6 ms  vruntime 56.8 -> 77.4

اختبار يتاح بعد الخطوة الأخيرة.