Real-time scheduling and priority inversion
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A real-time task is only correct if it is also on time. See how rate monotonic scheduling gives each periodic task a priority, how a simple utilisation test (and its EDF cousin) promises every deadline, and how one lock quietly breaks that promise. Step through a 13 ms run on Linux SCHED_FIFO where a high-priority task misses its deadline behind a medium one, then replay it with priority inheritance and watch it finish 6 ms early. This builds on the CPU scheduling module (Round robin and the time slice) and on Locks, spinlocks and atomic instructions; the Embedded lesson Priority inversion and priority inheritance shows the same bug on a microcontroller.
On time, not just fast
A real-time task is late if it finishes after its deadline, even when the answer is right. Each of our three periodic tasks wakes every period, needs some work time (the longest it can ever take), and must finish before its next wake-up.
task period work deadline H control 10 ms 2 ms end of its period M video 20 ms 8 ms end of its period L logger 40 ms 3 ms end of its period H steers the machine; needs the bus for 1 ms M encodes video; never touches the bus L writes a log over the bus for 3 ms real time = predictable, not fast (Berkeley CS162)
اقرأ الدرس خطوة بخطوة
On time, not just fast
A real-time task is late if it finishes after its deadline, even when the answer is right. Each of our three periodic tasks wakes every period, needs some work time (the longest it can ever take), and must finish before its next wake-up.
task period work deadline H control 10 ms 2 ms end of its period M video 20 ms 8 ms end of its period L logger 40 ms 3 ms end of its period H steers the machine; needs the bus for 1 ms M encodes video; never touches the bus L writes a log over the bus for 3 ms real time = predictable, not fast (Berkeley CS162)Rate monotonic priorities
Rate monotonic scheduling gives the shortest period the highest priority: H gets 3, M gets 2, L gets 1. In our example they run as Linux SCHED_FIFO threads: the CPU always runs the highest-priority ready thread and preempts lower ones at once.
rate monotonic: shorter period -> higher priority H period 10 ms -> priority 3 M period 20 ms -> priority 2 L period 40 ms -> priority 1 Linux SCHED_FIFO (sched(7)): priorities 1 (low) to 99 (high) a higher-priority thread that becomes ready preempts no time slice: a thread runs until it blocks or yieldsThe utilisation test
Add up work divided by period: U = 0.675. Liu and Layland proved rate monotonic meets every deadline when U is at most 0.780 for three tasks. EDF, earliest deadline first, can go up to 1. But both assume tasks never wait for each other.
U = sum of work / period H 2 / 10 = 0.200 M 8 / 20 = 0.400 L 3 / 40 = 0.075 total = 0.675 rate monotonic bound n(2^(1/n) - 1), n = 3 = 0.780 0.675 <= 0.780 -> every deadline met (a sufficient test) as n grows the bound falls toward ln 2 = 0.693 EDF (run the nearest deadline first) every deadline met if and only if U <= 1 Linux SCHED_DEADLINE is EDF plus a bandwidth server (CBS) both tests assume independent tasks: no locksL takes the bus lock
Now add a lock. At 0 ms only L is awake. It locks the bus mutex and starts its 3 ms of bus work. Our mutex is a plain one, with no priority tricks.
the bus code, run by H and L: 1 pthread_mutex_lock(&bus); 2 use_bus(); 3 pthread_mutex_unlock(&bus); t = 0 ms L awake, nothing else is L: pthread_mutex_lock(&bus) -> owner L mutex protocol PTHREAD_PRIO_NONE (the default)H wakes and preempts
At 1 ms H wakes up. It outranks L, so the CPU switches to H at once. L is paused in the middle of its bus work and still owns the lock.
t = 1 ms H wakes (priority 3 > 1) -> preempts L H runs 1 ms of plain work L is ready but paused, still the owner H deadline = 1 + 10 = 11 msH blocks on the lock
At 2 ms H needs the bus and calls lock, but L owns it. H must sleep until L unlocks. That is fine so far: L only has 2 ms of bus work left.
t = 2 ms H: pthread_mutex_lock(&bus) -> owned by L H blocks (sleeps, uses no CPU) L is the highest ready thread: L runs L bus work left: 2 ms, then 1 ms a high task waiting for a low one is expected here: the wait is as long as L's critical section (critical section = the code run while holding the lock)M runs ahead of H
At 3 ms M wakes. It needs no lock, and it outranks L, so it preempts L and runs for 8 ms. H waits on L, and L waits on M: the highest-priority task is stuck behind a medium one. This is priority inversion.
t = 3 ms M wakes (priority 2 > L's 1) -> preempts L t = 3..11 M runs 8 ms H blocked on the lock, L ready but outranked unbounded: H now waits as long as ANY medium task runs, not just for L's short critical section timeline so far LHLMMMMMMMMH misses its deadline
M finishes at 11 ms. L does its last 1 ms of bus work and unlocks at 12 ms, which wakes H. H finishes at 13 ms, 2 ms after its deadline. The utilisation test said it was safe.
t = 11 L runs its last bus millisecond t = 12 L: pthread_mutex_unlock(&bus) -> H wakes, owner H t = 12 H runs 1 ms on the bus t = 13 H done deadline 11 late by 2 ms plain mutex LHLMMMMMMMMLH H blocked from 2 to 12 ms: 10 msL inherits H's priority
Same run, with priority inheritance. At 2 ms H blocks on the lock, and the kernel lends its priority 3 to L, the owner. At 3 ms M wakes but cannot preempt L now. L finishes its bus work.
mutex protocol PTHREAD_PRIO_INHERIT the owner runs at the higher of its own priority and the priority of its highest waiter t = 0 L locks the bus t = 1 H wakes and preempts L t = 2 H blocks on the lock -> L runs at priority 3 t = 3 M wakes: 2 < 3, M waits t = 4 L unlocks -> back to priority 1; H owns the lockH finishes on time
L unlocks at 4 ms and drops back to priority 1. H gets the lock and finishes at 5 ms, 6 ms early. M runs afterwards. H now waits at most one critical section of L, never for M.
t = 4 H owns the lock, runs 1 ms t = 5 H done deadline 11 6 ms to spare t = 5..13 M runs 8 ms, done at 13 plain mutex LHLMMMMMMMMLH H done at 13 inheritance LHLLHMMMMMMMM H done at 5 H blocked: 10 ms -> 2 ms (bounded by L's 3 ms critical section) the same scheduler as a Python simulation: # name: (priority, release ms, [(needs_lock, ms), ...]) TASKS = {"H": (3, 1, [(False, 1), (True, 1)]), "M": (2, 3, [(False, 8)]), "L": (1, 0, [(True, 3)])} def run(inherit): work = {n: [list(s) for s in w] for n, (p, r, w) in TASKS.items()} holder, waiting, done, out, t = None, set(), {}, "", 0 def prio(n): p = TASKS[n][0] if inherit and n == holder and waiting: p = max([p] + [TASKS[w][0] for w in waiting]) return p while len(done) < len(TASKS): ready = [n for n in TASKS if TASKS[n][1] <= t and n not in done and n not in waiting] n = max(ready, key=prio) seg = work[n][0] if seg[0] and holder not in (None, n): waiting.add(n) # blocked on the lock continue if seg[0]: holder = n out += n seg[1] -= 1 t += 1 if seg[1] == 0: work[n].pop(0) if seg[0] and not (work[n] and work[n][0][0]): holder, waiting = None, set() # unlock wakes waiters if not work[n]: done[n] = t return out, done["H"] for inherit in (False, True): order, h = run(inherit) print("inherit" if inherit else "plain ", order, "H done at", h) prints: plain LHLMMMMMMMMLH H done at 13 inherit LHLLHMMMMMMMM H done at 5Turning it on
On Linux a program asks for this when it makes the mutex: PTHREAD_PRIO_INHERIT. The kernel then boosts the owner while a higher thread waits. Mars Pathfinder kept resetting in 1997 until engineers switched on the same kind of option in its VxWorks mutex.
C99, POSIX threads (cc -std=c99 -pthread): #define _POSIX_C_SOURCE 200809L #include <pthread.h> #include <stdio.h> int main(void) { pthread_mutexattr_t attr; pthread_mutex_t bus; int proto = PTHREAD_PRIO_NONE; pthread_mutexattr_init(&attr); pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT); pthread_mutex_init(&bus, &attr); pthread_mutexattr_getprotocol(&attr, &proto); pthread_mutex_lock(&bus); /* while held, the owner runs at the */ pthread_mutex_unlock(&bus); /* priority of its highest waiter */ puts(proto == PTHREAD_PRIO_INHERIT ? "inheritance on" : "off"); pthread_mutex_destroy(&bus); pthread_mutexattr_destroy(&attr); return 0; } prints: inheritance on threads become SCHED_FIFO with pthread_setschedparam() (needs privilege, else EPERM); in the kernel, rt-mutexes and PI-futexes do the boosting.
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Under rate monotonic scheduling, which task gets the highest priority?
Rate monotonic priorities depend only on the period: the shorter the period (the higher the rate), the higher the priority. Here H (10 ms) gets 3, M (20 ms) gets 2 and L (40 ms) gets 1.
02Three independent periodic tasks have total utilisation U = 0.675. What does the Liu and Layland test say about rate monotonic scheduling?
For n tasks the sufficient bound is n(2^(1/n) - 1), about 0.780 for three. U = 0.2 + 0.4 + 0.075 = 0.675 is below it, so every deadline is met, as long as the tasks never block each other.
03In the plain-mutex run, why does H finish 2 ms late?
H blocks on the lock that L owns. M outranks L, so it runs first; H is stuck behind a medium task it outranks. That is unbounded priority inversion.
04What does priority inheritance do?
With PTHREAD_PRIO_INHERIT the owner runs at the higher of its own priority and its highest waiter's. M can no longer preempt L, so H waits only for the rest of L's critical section, then drops back.
05Which Linux scheduling policy implements earliest deadline first?
SCHED_DEADLINE is an EDF scheduler with a Constant Bandwidth Server. SCHED_FIFO and SCHED_RR use fixed priorities from 1 to 99.
المسرد
- Real-time task
- A task whose result is only correct if it arrives before a deadline. Real time means predictable, not necessarily fast.
- Period
- How often a periodic task wakes up. Here each task's deadline is the end of its period, when it wakes again. Its work time is the longest it can ever need per period.
- Rate monotonic scheduling
- A fixed-priority rule: the task with the shortest period gets the highest priority.
- Utilisation
- The share of the CPU a task needs: its work time divided by its period. The total U is the sum over all tasks.
- EDF (earliest deadline first)
- A dynamic-priority rule: always run the ready task whose deadline is nearest. On one CPU it meets every deadline exactly when U is at most 1.
- Priority inversion
- A high-priority task waits for a lower-priority one. It becomes unbounded when a medium task, which needs no lock, keeps the lock holder from running.
- Priority inheritance
- While a thread waits on a mutex, the owner runs at the waiter's higher priority until it unlocks, so the wait is bounded by one critical section (the code that runs while a thread holds the lock).
- SCHED_FIFO
- The Linux real-time policy with fixed priorities 1 to 99 and no time slice: the highest-priority ready thread runs and preempts lower ones.
الملاحظات والمصادر
- The three tasks and their times are our own example, chosen so the numbers are small. The scheduler rules (fixed priorities, preemption, a lock that blocks, priority inheritance) are the ones POSIX and Linux SCHED_FIFO follow.
- The figure plays one 13 ms window, from L waking at 0 ms. In a full run each task wakes again every period; the deadline shown is the one for H's first wake-up, at 1 + 10 = 11 ms.
- The rate monotonic test is sufficient, not necessary: a task set above the bound may still meet every deadline, but one below it always does (when tasks are independent and the deadline is the end of the period). The EDF test, U at most 1, is exact.
- Priority inheritance does not remove the wait; it bounds it. Real-time analysis then adds each task's longest blocking time to the test. A related protocol, the priority ceiling, raises the owner as soon as it locks.
- Priorities 3, 2 and 1 are valid SCHED_FIFO values (Linux allows 1 to 99); real systems often leave gaps between them. Setting a real-time policy needs privilege (CAP_SYS_NICE or root).
- On Mars Pathfinder the low-priority weather (ASI/MET) task held a mutex that the high-priority bus distribution task needed, medium tasks ran in between, and a check found the bus task unfinished and reset the computer. Turning on the mutex's priority inheritance option fixed it.
- Berkeley CS162, Lecture 12: Starvation, Priority Inversion, Proportional-Share Scheduling, Realtime Scheduling
- Berkeley CS162, Lecture 11: Scheduling 2 (Linux real-time tasks, SCHED_FIFO)
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 28: Locks (aside on priority inversion)
- G. E. Reeves, What really happened on Mars? (1997)
- Linux man-pages: sched(7)
- Linux man-pages: pthread_mutexattr_getprotocol(3p)
- Linux man-pages: pthread_mutexattr_setprotocol(3p)
- Linux man-pages: pthread_setschedparam(3)
- Linux kernel documentation: RT-mutex implementation design
- Linux kernel documentation: Deadline Task Scheduling
اختبار يتاح بعد الخطوة الأخيرة.