Real-Time Systems, RTOS Scheduling & WCET Questions
Building embedded and control software with timing guarantees: hard, firm and soft real-time and why fast is not the same as predictable, RTOS task scheduling (fixed-priority, rate-monotonic, earliest-deadline-first, cooperative vs preemptive, lightweight cooperative schedulers on small microcontrollers), priorities and preemption, RTOS task states and lifecycle, bounding priority-inversion blocking with inheritance and ceiling protocols in RTOS designs, schedulability and response-time analysis including blocking terms, worst-case execution time estimation (static, measurement-based, cache, pipeline and DMA bus effects), RTOS internals such as the tick, tickless idle, software timers and context switching, serving aperiodic and best-effort work beside hard periodic tasks, multicore and mixed-criticality scheduling, bounded-wait lock APIs, choosing an RTOS, and diagnosing deadline misses and jitter from timing traces. Excludes interrupt mechanism and ISR design, general-purpose OS (desktop and server) CPU scheduling, priority inversion as a generic locking hazard, general synchronization primitives and lock-free data structures, firmware architecture and power optimization, which are covered elsewhere.
What is worst-case execution time, and why does a hard real-time design need it rather than an average? Describe how it is obtained in practice and where each approach falls short.
Sample Answer
What it is. The worst-case execution time (WCET) of a piece of code is an upper bound on how long it takes on a given processor and configuration, running without interruption, over every possible input and every possible hardware state (cache contents, pipeline state, and so on). Its relatives are the average-case time (ACET) and the best-case time (BCET). A WCET figure is only useful if it is safe (never below the true worst case) and reasonably tight (not far above it).
Why a hard real-time design needs it instead of the average. Schedulability analysis (proving that every task meets its deadline, for example with response-time analysis) takes each task's computation time C as the most it can ever consume. A hard real-time system fails on the one slow run, and the average is dominated by the typical runs that hide it. The program below shows both effects. Run in a python:3.12-slim container (CPython 3.12) with a fixed random seed, it prints:
import random
from math import ceil
def insertion_sort_comparisons(a):
"""Count key comparisons: the work grows with how out of order the input is."""
a = list(a)
count = 0
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0:
count += 1
if a[j] > key:
a[j + 1] = a[j]
j -= 1
else:
break
a[j + 1] = key
return count
N = 32
rng = random.Random(2024)
samples = [insertion_sort_comparisons(rng.sample(range(1000), N)) for _ in range(10_000)]
worst = insertion_sort_comparisons(range(N, 0, -1)) # reverse-sorted input
print(f"n={N}: mean {sum(samples) / len(samples):.0f}, largest of 10,000 random inputs {max(samples)}, "
f"true worst case (reverse sorted) {worst} = n(n-1)/2 = {N * (N - 1) // 2}")
print(f"largest observed is {max(samples) / worst:.0%} of the true worst case")
def response_times(tasks):
"""tasks: (name, C, T) in rate-monotonic order; deadline = period. Returns {name: R or None}."""
out = {}
for i, (name, C, T) in enumerate(tasks):
R = C
while True:
nxt = C + sum(ceil(R / Tj) * Cj for _, Cj, Tj in tasks[:i])
if nxt == R or nxt > T:
R = nxt
break
R = nxt
out[name] = R
return out
avg = [("A", 2, 10), ("B", 5, 20), ("C", 10, 50)]
wcet = [("A", 3, 10), ("B", 9, 20), ("C", 12, 50)]
for label, ts in (("average-case C", avg), ("worst-case C", wcet)):
u = sum(C / T for _, C, T in ts)
rt = response_times(ts)
verdict = ", ".join((f"R_{n}={r} (D={T}) ok" if r <= T else f"R_{n} exceeds D={T} MISS") for (n, _, T), r in zip(ts, rt.values()))
print(f"{label:15} U={u:.2f} {verdict}")
n=32: mean 276, largest of 10,000 random inputs 389, true worst case (reverse sorted) 496 = n(n-1)/2 = 496
largest observed is 78% of the true worst case
average-case C U=0.65 R_A=2 (D=10) ok, R_B=7 (D=20) ok, R_C=19 (D=50) ok
worst-case C U=0.99 R_A=3 (D=10) ok, R_B=15 (D=20) ok, R_C exceeds D=50 MISS
- The insertion sort counts comparisons, a deterministic stand-in for time. Random inputs average 276 comparisons and never exceeded 389 in 10,000 tries, but the true worst case is 496, reached by reverse-sorted input that random tests almost never produce.
- The response-time function finds each task's worst-case response time R (release to completion) as the smallest R with R = C + the sum over higher-priority tasks of ceil(R / T_j) x C_j. For task C with worst-case values (C = 12; A is 3 every 10, B is 9 every 20): R = 12; then 12 + ceil(12/10) x 3 + ceil(12/20) x 9 = 12 + 6 + 9 = 27; then 12 + 9 + 18 = 39; then 12 + 12 + 18 = 42; then 12 + 15 + 27 = 54. That is above the 50 ms deadline, so the iteration stops there and reports MISS. With the average values the same iteration settles at 19, inside 50.
- With average-case C values the three-task set looks comfortable (U = 0.65, every deadline met). With worst-case C values U = 0.99 and the lowest-priority task misses its 50 ms deadline. A design validated on averages would ship a system that is unschedulable on its worst inputs.
How a WCET is obtained, and where each way falls short (survey: Wilhelm et al., ACM Transactions on Embedded Computing Systems, 2008).
- Static analysis. A tool reads the compiled binary, builds its control-flow graph (the possible paths through the code), bounds every loop (from annotations or inference), uses a model of the processor's pipeline, caches and memory timing (the timing model) to put a time bound on each basic block (straight-line code), and finds the longest feasible path, commonly by integer linear programming (ILP: choose how many times each block runs so that the total time is largest, subject to constraints taken from the code's structure and the annotations). A tiny illustrative example: an entry block of 5 cycles, a loop whose header costs 4 cycles, a branch inside the loop that takes either a 6-cycle block or an 11-cycle block, and an exit block of 3 cycles, with the loop bounded to 10 iterations. The tool maximises 5 + 4 x (header runs) + 6 x (short block runs) + 11 x (long block runs) + 3, subject to header runs at most 10 and short plus long equal to header runs. The maximum takes the long block every time: 5 + 40 + 110 + 3 = 158 cycles. If a reviewed flow fact says the long block (an error path) runs at most twice per call, the bound drops to 5 + 40 + 2 x 11 + 8 x 6 + 3 = 118 cycles. A flow fact is exactly this kind of statement about the program that the tool cannot derive on its own, so a wrong one silently makes the bound unsafe. AbsInt's aiT is an example of a commercial tool. It falls short in four ways: it needs an accurate and complete processor model, which is hard for complex or poorly documented cores; it needs loop bounds and flow facts, and a wrong annotation makes the result silently unsafe; it is pessimistic wherever it cannot tell which cache state applies; and it must be rerun when the compiler, flags or hardware change.
- Measurement. Run the code on the real hardware and record the longest time seen (the high-water mark, meaning the largest value observed so far). The simplest start is a GPIO pin set high at the start of the code and low at the end, read on a logic analyser. On Arm Cortex-M the next step is the cycle counter in the DWT unit (the data watchpoint and trace unit; the counter is an optional feature, and the DWT_CTRL.NOCYCCNT bit reports when it is absent). Trace is for deeper investigation: ITM (instrumentation trace, written by software) and ETM (embedded trace, a hardware record of the instructions executed). It falls short because it only covers the inputs and hardware states you exercised: the worst path or the worst cache state may never occur in testing, as the sort shows. The result is a lower bound on the true WCET, not an upper bound, and instrumentation itself disturbs the timing.
- Hybrid. Measure short code segments on the real hardware and combine them with the program's structure, taking the longest path through the graph. It falls short because each segment's measured worst case still depends on the hardware state on entry and on the tests having reached its slow state, and adding segment maxima assumes the segments are independent, which cache and pipeline state break.
What to do in practice.
- Fix the exact binary, compiler flags, clock and memory configuration first: a WCET belongs to code plus configuration.
- On a core without caches or with simple pipelines, a static or hybrid bound is tractable. On a Cortex-A class core (caches, branch prediction, out-of-order execution, where the core may run later instructions before earlier ones whose inputs are not ready, a memory bus shared with other cores) a sound bound is much harder, so reduce the variability: pin tasks to cores, partition or lock caches, or disable features for the critical code.
- Make the code analysable: bounded loops, no recursion, no dynamic allocation in the critical path.
- For hard real-time use a static or hybrid bound, with measurement as a cross-check (the measured maximum must never exceed the bound). For soft real-time a measured high-water mark plus a margin, backed by a run-time execution-time monitor, is a reasonable engineering trade.
Three periodic tasks run under rate-monotonic scheduling on one core: A with a 1 ms execution time every 4 ms, B with 2 ms every 6 ms, and C with 3 ms every 12 ms. Is the set schedulable? State the utilisation test you would apply first, what it tells you here, and what you do when it is inconclusive.
Sample Answer
Verdict: schedulable. The quick utilisation test is inconclusive, and the exact test (response-time analysis) shows every task meets its deadline. The numbers below come from the script shown in step 3, run in a python:3.12-slim container.
Step 1: RM priorities. Rate-monotonic scheduling (RM) gives the shortest period the highest priority: A (period 4 ms) > B (6 ms) > C (12 ms). Deadline equals period for all three.
Step 2: the Liu and Layland utilisation test. Utilisation U is the sum of execution time over period: 1/4 + 2/6 + 3/12 = 0.25 + 0.3333 + 0.25 = 0.8333 (5/6). Liu and Layland (1973) showed that n periodic tasks under RM are certainly schedulable if U <= n(2^(1/n) - 1). For n = 3 the bound is 3(2^(1/3) - 1) = 0.7798. Here 0.8333 > 0.7798, so the test fails to confirm schedulability. It is a sufficient test: passing proves schedulable, failing proves nothing, and the set may still be fine. (U < 1 is a necessary condition, so it is not overloaded.)
Step 3: when inconclusive, run exact response-time analysis. The worst-case response time R of a task (from release to completion) is the smallest fixed point of R = C + sum over higher-priority tasks j of ceil(R / T_j) * C_j. Start with R = C and iterate until it stops changing; stop with failure if R exceeds the deadline. The worst case is a release at the critical instant, when all tasks release together.
| Task | C | T = D | Iteration sequence for R | R | Meets D? |
|---|---|---|---|---|---|
| A | 1 | 4 | 1, 1 | 1 | yes |
| B | 2 | 6 | 2, 3, 3 | 3 | yes |
| C | 3 | 12 | 3, 6, 7, 9, 10, 10 | 10 | yes (10 <= 12) |
For C: start at 3. Next: 3 + ceil(3/4)1 + ceil(3/6)2 = 6. Then 3 + 21 + 12 = 7. Then 3 + 21 + 22 = 9. Then 3 + 31 + 22 = 10. Then 3 + ceil(10/4)*1 + ceil(10/6)*2 = 3 + 3 + 4 = 10, a fixed point, and 10 ms is within the 12 ms deadline with 2 ms of slack.
Script and output. Run with Python 3.12:
from math import ceil
tasks = [("A", 1, 4), ("B", 2, 6), ("C", 3, 12)] # name, C (ms), T = D (ms), highest priority first
def response_time(i):
c, d = tasks[i][1], tasks[i][2]
r, seq = c, [c]
while True:
nxt = c + sum(ceil(r / t) * cj for _, cj, t in tasks[:i])
seq.append(nxt)
if nxt == r or nxt > d:
return nxt, seq
r = nxt
print("U =", round(sum(c / t for _, c, t in tasks), 4), "bound =", round(3 * (2 ** (1 / 3) - 1), 4))
for i, (name, c, t) in enumerate(tasks):
r, seq = response_time(i)
print(name, "iterations", seq, "R =", r, "meets deadline:", r <= t)
U = 0.8333 bound = 0.7798
A iterations [1, 1] R = 1 meets deadline: True
B iterations [2, 3, 3] R = 3 meets deadline: True
C iterations [3, 6, 7, 9, 10, 10] R = 10 meets deadline: True
Tracing one 12 ms window by hand with all tasks released at 0 (A runs 0-1, B 1-3, C 3-4, A 4-5, C 5-6, B 6-8, A 8-9, C 9-10), C completes at 10 ms, matching the analysis. The CPU is idle for the last 2 of 12 ms, consistent with U = 5/6.
Would EDF help? EDF (earliest deadline first, dynamic priority) is schedulable if and only if U <= 1 for deadline equal to period, and 0.8333 <= 1, so EDF also schedules this set. Here EDF is not needed: RM already works. EDF matters for sets such as two tasks (C=2, T=5) and (C=4, T=7), where U = 0.9714 and RM fails (response time 8 > 7) while EDF succeeds.
What to do in practice. Sign off using the exact test, not the bound, and record the margin (here 2 ms on C). Re-run the analysis whenever a worst-case execution time estimate changes, because the margin is small. If the exact test had failed, the levers are: cut a C (optimise or split work), lengthen a period, make periods harmonic (each period divides the next, which lets RM reach U = 1), or move to EDF.
How would you verify the timing behaviour of an RTOS application from a trace? Where would you put trace points, how do you timestamp them, how do you keep the tracing from distorting the timing, and how do you pull out the worst-case occurrences?
Sample Answer
The idea
A trace is a time-ordered list of small records written by the running system: what happened (an event code), which task or interrupt, and when (a timestamp). Timing is then verified offline from the list: rebuild every job's release, start, preemptions and completion, and take the maximum. The four decisions are what to record, how to read the clock, how to keep recording from changing the timing, and how to find the worst cases.
Where to put trace points
- Scheduler hooks. Record every task switch-in and switch-out. RTOS kernels provide hook macros for this (FreeRTOS calls
traceTASK_SWITCHED_INafter a task has been selected andtraceTASK_SWITCHED_OUTbefore the next is chosen, withpxCurrentTCB, the pointer to the control block of the task that is running, identifying the task). These two events alone give each task's running intervals. - Releases and completions. Record the moment a task becomes ready (timer tick wake-up, semaphore given, queue item arrival) and the moment a job finishes (the task returns to its wait call). Release-to-completion is the response time that deadlines apply to.
- Interrupts. Record ISR (interrupt service routine) entry and exit; time stolen by interrupts is otherwise invisible in task intervals.
- Blocking. Record lock requests, acquisitions and releases, so waiting on a mutex can be told apart from being preempted.
- Application marks at the start and end of the code sections whose WCET (worst-case execution time) matters, for example one sensor-filter stage.
- A GPIO pin toggled at the same points, watched on a logic analyzer, as an independent check of the trace's own timestamps.
How to timestamp
Use a free-running hardware counter read with a single instruction or register load, not a software timer. On Cortex-M cores that have the DWT cycle counter this is DWT->CYCCNT, the cycle count register of the DWT (Data Watchpoint and Trace unit). It is switched on by setting the TRCENA bit in DEMCR (the Debug Exception and Monitor Control Register, which enables the trace blocks) and the CYCCNTENA bit in DWT->CTRL (the DWT control register, which starts the counter): a 32-bit counter that ticks at the core clock. At 100 MHz it has a 10 ns resolution and wraps every 42.9 seconds (the script below prints the figure). Two rules follow. Store the raw count and convert offline, so the hot path does not divide. And compute durations as (later - earlier) & 0xFFFFFFFF, which gives the correct difference even when the counter wrapped between the two readings, as long as no interval exceeds one wrap period. For example, with the counter 96 cycles before its wrap at the earlier reading (4294967200) and 304 cycles after it at the later one (304), the plain difference is 304 - 4294967200 = -4294966896; masking with 0xFFFFFFFF gives 400 cycles, which is 4.0 us at 100 MHz, the true elapsed time (the program prints this line). Longer traces need a periodic record that carries the wrap count, or a 64-bit extension.
Keeping tracing from distorting timing
- Cheap records. Write a fixed-size binary record (for example 8 bytes: a 32-bit timestamp, an event code and a task id) into a RAM ring buffer. No
printf, no string formatting and no blocking I/O in the hot path; a low-priority task or the debugger drains the buffer later. - Account for the cost. If a record costs 40 cycles (an assumed figure; measure the real one by toggling a pin around the write and reading the cycle count), the script below shows a 0.22 percent load for the example task set at 5550 events per second. Include that cost in the schedulability analysis, or leave the tracing compiled in for the final timing build so what is measured is what ships.
- Protect the buffer cheaply: interrupts disabled for the few cycles of the index update, or one buffer per core with an atomic index. A trace write that takes a lock can itself create the blocking you are trying to see.
- Check the probe effect (the way measuring changes the behaviour being measured) by comparison: run the same stimulus with tracing on and off and compare an externally measured quantity, such as the pin-to-pin latency on the logic analyzer. They should agree within the record cost.
- Do not lose the interesting part: use the buffer as a ring that overwrites the oldest data and stop recording when a trigger fires (a job exceeding a threshold), so the window around a worst case survives.
Pulling out the worst-case occurrences
The script generates a trace the way an RTOS hook would (raw cycle counts that wrap partway through, three fixed-priority tasks, a few jobs with extra demand), then analyses only the recorded events: it rebuilds each job's response time and the time it actually ran, picks the worst job per task, and lists who preempted the worst job of the lowest-priority task. Run in a python:3.12-slim container with python trace_check.py:
import random
CPU_MHZ = 100 # cycles per microsecond
WRAP = 1 << 32 # a 32-bit cycle counter wraps every 2^32 cycles
TRACE_COST_CYCLES = 40 # assumed cost of writing one trace record
# ---- 1. generate a trace the way an RTOS hook would: (cycle_counter, event, task) ----
# Fixed priorities, rate order. T in us, nominal C in us.
TASKS = [("H", 1000, 150), ("M", 5000, 900), ("L", 20000, 2500)]
rng = random.Random(7)
start_cycles = WRAP - 2_200_000 # the counter wraps 22 ms into the trace
DURATION_US = 200_000
def generate(duration_us=DURATION_US):
events, jobs = [], []
for prio, (name, T, C) in enumerate(TASKS):
for k in range(duration_us // T):
demand = C + (rng.randint(0, C // 2) if rng.random() < 0.05 else rng.randint(-C // 10, C // 10))
jobs.append({"t": name, "prio": prio, "rel": k * T, "left": demand})
running = None
for us in range(duration_us):
for j in jobs:
if j["rel"] == us:
events.append((us, "RELEASE", j["t"]))
ready = [j for j in jobs if j["rel"] <= us and j["left"] > 0]
nxt = min(ready, key=lambda j: (j["prio"], j["rel"])) if ready else None
if nxt is not running:
if running is not None:
events.append((us, "SWITCH_OUT", running["t"]))
if nxt is not None:
events.append((us, "SWITCH_IN", nxt["t"]))
running = nxt
if running:
running["left"] -= 1
if running["left"] == 0:
events.append((us + 1, "DONE", running["t"]))
return [((start_cycles + us * CPU_MHZ) % WRAP, ev, t) for us, ev, t in sorted(events, key=lambda e: e[0])]
trace = generate()
# ---- 2. analyse only the recorded trace ----
def delta_us(a, b): # b later than a; the mask makes counter wrap harmless
return ((b - a) & (WRAP - 1)) / CPU_MHZ
rel, run_since, ran, jobs = {}, {}, {}, {}
for cyc, ev, t in trace:
if ev == "RELEASE":
rel[t], ran[t] = cyc, 0.0
elif ev == "SWITCH_IN":
run_since[t] = cyc
elif ev == "SWITCH_OUT":
ran[t] += delta_us(run_since[t], cyc)
elif ev == "DONE":
ran[t] += delta_us(run_since[t], cyc)
jobs.setdefault(t, []).append((delta_us(rel[t], cyc), ran[t], rel[t]))
print("task jobs avg_resp_us worst_resp_us exec_in_worst_us deadline_us")
for name, T, _ in TASKS:
js = jobs[name]
worst = max(js, key=lambda j: j[0])
print(f"{name:4s} {len(js):5d} {sum(j[0] for j in js) / len(js):12.1f} {worst[0]:14.1f} {worst[1]:17.1f} {T:12d}")
worst = max(jobs["L"], key=lambda j: j[0])
print("\nwhat happened during L's worst job (release at cycle", worst[2], "):")
t0, t1 = worst[2], worst[2] + int(worst[0] * CPU_MHZ)
for cyc, ev, t in trace:
if ((cyc - t0) & (WRAP - 1)) <= (t1 - t0) and ev in ("SWITCH_IN",) and t != "L":
print(f" +{delta_us(t0, cyc):8.1f} us {t} starts")
per_s = len(trace) * 1_000_000 / DURATION_US
print(f"\ntrace volume: {len(trace)} events in {DURATION_US / 1000:.0f} ms = {per_s:.0f} events/s;",
f"cost at {TRACE_COST_CYCLES} cycles each = {per_s * TRACE_COST_CYCLES / (CPU_MHZ * 1e6) * 100:.2f} % of the CPU")
print(f"a 32-bit counter at {CPU_MHZ} MHz wraps every {WRAP / (CPU_MHZ * 1e6):.1f} s")
# ---- 3. the jobs whose interval contains the counter wrap ----
print("\njobs that were running or waiting when the counter wrapped (22 ms into the trace):")
for name, T, _ in TASKS:
for resp, ran_us, rel_cyc in jobs[name]:
if rel_cyc + round(resp * CPU_MHZ) >= WRAP:
print(f" {name}: released at {delta_us(start_cycles, rel_cyc) / 1000:.0f} ms, response {resp:.1f} us, measured across the wrap")
# a masked subtraction on its own: 96 cycles before the wrap to 304 cycles after it
earlier, later = WRAP - 96, 304
print(f"\nearlier={earlier}, later={later}: later - earlier = {later - earlier}; "
f"masked = {(later - earlier) & 0xFFFFFFFF} cycles = {delta_us(earlier, later):.1f} us")
task jobs avg_resp_us worst_resp_us exec_in_worst_us deadline_us
H 200 151.7 217.0 217.0 1000
M 40 1165.5 1605.0 1298.0 5000
L 10 4059.0 4358.0 2728.0 20000
what happened during L's worst job (release at cycle 11800000 ):
+ 0.0 us H starts
+ 140.0 us M starts
+ 1000.0 us H starts
+ 1135.0 us M starts
+ 2000.0 us H starts
+ 3000.0 us H starts
+ 4000.0 us H starts
trace volume: 1110 events in 200 ms = 5550 events/s; cost at 40 cycles each = 0.22 % of the CPU
a 32-bit counter at 100 MHz wraps every 42.9 s
jobs that were running or waiting when the counter wrapped (22 ms into the trace):
L: released at 20 ms, response 4189.0 us, measured across the wrap
earlier=4294967200, later=304: later - earlier = -4294966896; masked = 400 cycles = 4.0 us
Reading it: the lowest-priority task L has a worst response of 4358 us but ran for only 2728 us, so 1630 us was spent preempted; the listing shows H starting five times and M twice inside that job. The counter wrapped 22 ms into the trace, which falls inside L's second job (released at 20 ms, response 4189.0 us, as the last lines of the output show), and the masked subtraction measured that job correctly; the worst job listed above (released at 140 ms) did not span the wrap. The same analysis, pointed at a real trace dump, yields each task's worst response and the evidence for which interference caused it.
Two cautions that decide how much the maximum is worth. First, a trace shows what happened on that run: the worst case in the data is a lower bound on the true worst case. To approach the true one, provoke it: release all tasks together (the critical instant: the moment when every task is released at once, which gives a fixed-priority task its longest response), feed worst-case inputs and error paths, run long, and add stress such as the maximum DMA or interrupt load. Second, compare the measured maxima with the response-time analysis: an observed time above the analytic bound means a wrong WCET figure, a missing blocking term or an unmodelled interrupt, and is a finding in itself. The trace verifies the model; it does not replace it.
Your RTOS mutex only offers a blocking lock, and a hard-deadline task needs a try-lock and a lock with a timeout. Sketch the C API and implementation on a small microcontroller, say how the timeout and priority inheritance interact, and show how you would bound the worst-case time the hard task can wait on the lock.
Sample Answer
Recommendation. Keep one lock call and give it a timeout argument: rt_mutex_lock(m, timeout_ticks) where 0 is a try-lock and a special value means wait forever. Implement inheritance as "owner priority = max(own base priority, priority of every task still waiting on a mutex it owns)", recomputed whenever a waiter arrives, leaves by timeout, or receives the lock. Bound the hard task's wait by the longest critical sections of the lower-priority tasks, and set its timeout at or above that bound when the data is mandatory, below it only when the task has a degraded path (a fallback that is good enough for one cycle, such as reusing the last value, when the lock is not obtained in time).
Terms. A mutex is a lock with an owner; only the owner may release it. A try-lock returns at once with success or failure. A timed lock waits at most a given number of ticks (the RTOS's periodic timer units) and then returns a timeout status. Priority inheritance temporarily raises ("donates" to) a lock owner's priority to that of the highest-priority task waiting for it, so a medium-priority task cannot keep the owner off the CPU while the high-priority task waits. A critical section is the code between lock and unlock.
API and kernel code. The first half of the file is the kernel part, the second half a harness in which tasks are small scripts (run N ticks, lock, try-lock, unlock) scheduled preemptively by effective priority, so the interactions can be checked tick by tick. In a real kernel rt_mutex_lock would switch the task out and return the final status when it resumes; the harness prints that final status as "lock call returns". The kernel functions would run with interrupts masked (or at the kernel's critical-section level) so that the tick interrupt cannot interleave with them.
#include <stdio.h>
#include <stddef.h>
/* ---------- kernel part: what a small RTOS would implement ---------- */
#define MAXT 4
#define RT_FOREVER 0xFFFFFFFFu
typedef enum { RT_OK = 0, RT_BUSY = -1, RT_TIMEOUT = -2, RT_PENDING = -3, RT_NOT_OWNER = -4 } rt_status;
typedef enum { T_READY, T_BLOCKED, T_DONE } tstate;
typedef struct rt_mutex rt_mutex;
typedef struct rt_task {
const char *name;
int base_prio, prio; /* prio = effective priority, base_prio = assigned */
tstate state;
rt_mutex *wait_on; /* mutex this task is blocked on, if any */
unsigned deadline_tick; /* wake-up time when the wait has a timeout */
int timed;
rt_status result; /* what the blocked lock call returns when it completes */
} rt_task;
struct rt_mutex { const char *name; rt_task *owner; };
static rt_task *tasks[MAXT];
static int ntasks, use_inheritance = 1;
/* Effective priority = base priority, raised to the highest priority of any task
still waiting on a mutex this task owns. Propagates along a chain of waits. */
static void recompute(rt_task *t)
{
int p = t->base_prio;
if (use_inheritance)
for (int i = 0; i < ntasks; i++)
if (tasks[i]->state == T_BLOCKED && tasks[i]->wait_on && tasks[i]->wait_on->owner == t
&& tasks[i]->prio > p)
p = tasks[i]->prio;
if (p != t->prio) {
t->prio = p;
if (t->state == T_BLOCKED && t->wait_on && t->wait_on->owner)
recompute(t->wait_on->owner);
}
}
rt_status rt_mutex_try_lock(rt_task *self, rt_mutex *m) /* never blocks, donates no priority */
{
if (m->owner) return RT_BUSY;
m->owner = self;
return RT_OK;
}
/* timeout_ticks: 0 behaves as try_lock, RT_FOREVER waits without limit. When the task
must wait, the call returns RT_PENDING here; on a real kernel the task is switched out
and the call returns the final status (self->result) when it resumes. */
rt_status rt_mutex_lock(rt_task *self, rt_mutex *m, unsigned timeout_ticks, unsigned now)
{
if (m->owner == NULL) { m->owner = self; return RT_OK; }
if (timeout_ticks == 0) return RT_BUSY;
self->state = T_BLOCKED;
self->wait_on = m;
self->timed = timeout_ticks != RT_FOREVER;
self->deadline_tick = now + timeout_ticks;
recompute(m->owner); /* owner inherits our priority */
return RT_PENDING;
}
rt_status rt_mutex_unlock(rt_task *self, rt_mutex *m)
{
rt_task *next = NULL;
if (m->owner != self) return RT_NOT_OWNER;
for (int i = 0; i < ntasks; i++) /* highest-priority waiter wins */
if (tasks[i]->state == T_BLOCKED && tasks[i]->wait_on == m && (!next || tasks[i]->prio > next->prio))
next = tasks[i];
m->owner = next;
if (next) { next->state = T_READY; next->wait_on = NULL; next->result = RT_OK; recompute(next); }
recompute(self); /* drop the inherited priority */
return RT_OK;
}
/* Called from the tick interrupt: expire timed waits. A timed-out waiter leaves the
wait list, so the owner's inherited priority must be recomputed without it. */
void rt_tick(unsigned now)
{
for (int i = 0; i < ntasks; i++) {
rt_task *t = tasks[i];
if (t->state == T_BLOCKED && t->timed && now >= t->deadline_tick) {
rt_mutex *m = t->wait_on;
t->state = T_READY; t->wait_on = NULL; t->result = RT_TIMEOUT;
if (m->owner) recompute(m->owner);
}
}
}
/* ---------- test harness: tasks are scripts, one tick per RUN step ---------- */
typedef enum { RUN, LOCK, TRY, UNLOCK, END } opcode;
typedef struct { opcode op; unsigned arg; } step;
typedef struct { rt_task t; const step *script; int pc; unsigned left, release; int waiting; } script_task;
#define TASK(nm, prio, scr, rel) { { nm, prio, prio, T_READY, NULL, 0, 0, RT_OK }, scr, 0, 0, rel, 0 }
static rt_mutex M = { "M", NULL };
static const char *status_name(rt_status s)
{ return s == RT_OK ? "OK" : s == RT_BUSY ? "BUSY" : s == RT_TIMEOUT ? "TIMEOUT" : "PENDING"; }
static void report_resumed(script_task *st, int n, unsigned now)
{
for (int i = 0; i < n; i++)
if (st[i].waiting && st[i].t.state == T_READY) {
st[i].waiting = 0;
printf(" t=%2u %s's lock call returns %s\n", now, st[i].t.name, status_name(st[i].t.result));
}
}
static void simulate(const char *title, script_task *st, int n, unsigned horizon)
{
char row[64];
printf("%s\n", title);
ntasks = n; M.owner = NULL;
for (int i = 0; i < n; i++) { tasks[i] = &st[i].t; st[i].pc = 0; st[i].left = 0; st[i].waiting = 0; }
for (unsigned now = 0; now < horizon; now++) {
rt_tick(now);
script_task *run;
for (;;) { /* run kernel calls until a RUN tick */
report_resumed(st, n, now);
run = NULL;
for (int i = 0; i < n; i++)
if (st[i].release <= now && st[i].t.state == T_READY && (!run || st[i].t.prio > run->t.prio))
run = &st[i];
if (!run) break;
const step *s = &run->script[run->pc];
if (s->op == RUN) { if (run->left == 0) run->left = s->arg; break; }
if (s->op == END) { run->t.state = T_DONE; printf(" t=%2u %s finishes\n", now, run->t.name); continue; }
if (s->op == UNLOCK) {
rt_status u = rt_mutex_unlock(&run->t, &M); run->pc++;
if (u == RT_OK) printf(" t=%2u %s unlocks M, its priority is now %d\n", now, run->t.name, run->t.prio);
else printf(" t=%2u %s does not own M, so it skips the unlock\n", now, run->t.name);
continue;
}
rt_status r = s->op == TRY ? rt_mutex_try_lock(&run->t, &M) : rt_mutex_lock(&run->t, &M, s->arg, now);
printf(" t=%2u %s %s M -> %s", now, run->t.name, s->op == TRY ? "try-locks" : "locks", status_name(r));
if (r == RT_PENDING) printf(" (owner %s runs at priority %d)", M.owner->name, M.owner->prio);
printf("\n");
run->pc++;
if (r == RT_PENDING) run->waiting = 1;
else if (r == RT_BUSY) printf(" t=%2u %s sees BUSY, did not wait; %s still at priority %d\n",
now, run->t.name, M.owner->name, M.owner->prio);
}
row[now] = run ? run->t.name[0] : '.';
if (run) { run->left--; if (run->left == 0) run->pc++; }
}
row[horizon] = '\0';
printf(" who runs each tick: %s\n\n", row);
}
int main(void)
{
static const step low[] = { {LOCK, RT_FOREVER}, {RUN, 6}, {UNLOCK, 0}, {RUN, 1}, {END, 0} };
static const step med[] = { {RUN, 10}, {END, 0} };
static const step hi_a[] = { {LOCK, 8}, {RUN, 1}, {UNLOCK, 0}, {END, 0} };
static const step hi_b[] = { {LOCK, 3}, {RUN, 1}, {END, 0} };
static const step hi_c[] = { {TRY, 0}, {RUN, 1}, {END, 0} };
script_task a[3] = { TASK("L", 1, low, 0), TASK("M", 2, med, 3), TASK("H", 3, hi_a, 2) };
script_task b[3] = { TASK("L", 1, low, 0), TASK("M", 2, med, 3), TASK("H", 3, hi_a, 2) };
script_task c[3] = { TASK("L", 1, low, 0), TASK("M", 2, med, 3), TASK("H", 3, hi_b, 2) };
script_task d[2] = { TASK("L", 1, low, 0), TASK("H", 3, hi_c, 2) };
use_inheritance = 1;
simulate("A. Inheritance on. L holds M for 6 ticks of work; H wants it at t=2 and waits up to 8 ticks", a, 3, 16);
use_inheritance = 0;
simulate("B. Same as A with inheritance off", b, 3, 16);
use_inheritance = 1;
simulate("C. Inheritance on. H waits only 3 ticks", c, 3, 16);
simulate("D. H uses try-lock", d, 2, 16);
return 0;
}
Build and run in a gcc:14 container (GCC 14.4.0, aarch64); the program is deterministic and compiles without warnings with -std=c99 -O2 -Wall -Wextra -pedantic. It prints:
A. Inheritance on. L holds M for 6 ticks of work; H wants it at t=2 and waits up to 8 ticks
t= 0 L locks M -> OK
t= 2 H locks M -> PENDING (owner L runs at priority 3)
t= 6 L unlocks M, its priority is now 1
t= 6 H's lock call returns OK
t= 7 H unlocks M, its priority is now 3
t= 7 H finishes
who runs each tick: LLLLLLHMMMMMMMMM
B. Same as A with inheritance off
t= 0 L locks M -> OK
t= 2 H locks M -> PENDING (owner L runs at priority 1)
t=10 H's lock call returns TIMEOUT
t=11 H does not own M, so it skips the unlock
t=11 H finishes
t=14 M finishes
who runs each tick: LLLMMMMMMMHMMMLL
C. Inheritance on. H waits only 3 ticks
t= 0 L locks M -> OK
t= 2 H locks M -> PENDING (owner L runs at priority 3)
t= 5 H's lock call returns TIMEOUT
t= 6 H finishes
who runs each tick: LLLLLHMMMMMMMMMM
D. H uses try-lock
t= 0 L locks M -> OK
t= 2 H try-locks M -> BUSY
t= 2 H sees BUSY, did not wait; L still at priority 1
t= 3 H finishes
t= 7 L unlocks M, its priority is now 1
t= 8 L finishes
who runs each tick: LLHLLLLL........
Reading the code.
rt_taskholds what the kernel needs per task:base_prio(assigned) andprio(effective, possibly inherited), the state, which mutex it waits on (wait_on), the tick at which a timed wait ends (deadline_tick) andresult, the status the blocked lock call will return when the task resumes.recompute(t)sets t's effective priority to the highest priority among its own base priority and the tasks blocked on a mutex t owns. If t is itself blocked, the change must reach the owner of the mutex t waits on, so it calls itself on that owner: this follows a chain of waits (H waits on a mutex owned by M, M waits on a mutex owned by L, so L must inherit H's priority too).rt_mutex_locktakes the lock if free; returnsRT_BUSYat once for timeout 0; otherwise it marks the task blocked with its deadline tick, callsrecomputeon the owner so the owner inherits, and returnsRT_PENDING.RT_PENDINGis an artefact of this harness, which cannot suspend a C function: a real kernel would switch the task out inside the call and return the final status later.rt_mutex_unlockchecks ownership, hands the lock to the highest-priority waiter (the waiter'sresultbecomesRT_OK) and recomputes both the new owner and the old one (dropping its inherited priority).rt_tickruns every tick: a blocked task whosedeadline_tickhas passed becomes ready withRT_TIMEOUT, and the owner is recomputed without it.- In the harness, each task is a script of steps (
RUN nuses n ticks of CPU,LOCK t,TRY,UNLOCK,END); theTASK(...)macro fills in a task's name, base priority, script and release tick;simulateloops over ticks, runs the kernel steps of the highest-priority ready task until it reaches aRUNtick, and records which task used the tick in thewho runs each tickrow.
What the four runs show.
- A (inheritance on, 8-tick timeout): H asks at tick 2 while L is part way through a 6-tick critical section. L inherits priority 3, so M (priority 2, 10 ticks of CPU work, released at tick 3) cannot preempt it. L unlocks at tick 6, H gets the lock after 4 ticks of waiting, which is exactly L's remaining critical-section work.
- B (same, inheritance off): M runs for ticks 3 to 9 while L sits behind it, and H's wait only ends because its timeout fires at tick 10. The timeout limited the damage to 8 ticks, but it did not give H the lock: the lock was not available, so H took its timeout path. Here the wait was set by M's CPU time, not by L's critical section.
- C (inheritance on, 3-tick timeout): H times out at tick 5, and at that moment L's inherited priority is dropped because the waiter is gone (
rt_tickrecomputes the owner). Once H finishes its tick, M takes the CPU from L, which still holds the lock with one tick of work left. This is the interaction between timeout and inheritance: the boost lasts only while someone is waiting, so after a timeout the next requester starts from scratch, with L's critical section stretched by M. A timeout bounds the caller's wait; it does not repair the inversion. - D (try-lock): H gets
BUSYat once and L stays at priority 1. A try-lock never waits, so it never donates priority: a hard task that polls with try-lock must not assume the owner is being helped, and must not spin on it (spinning burns its own deadline slack while the owner may not run).
Bounding the worst-case wait. On a single processor with priority inheritance, a task can be blocked by each lower-priority task at most once, and by at most min(n, m) critical sections, where n is the number of lower-priority tasks that can block it and m the number of mutexes that can block it (Sha, Rajkumar and Lehoczky, "Priority Inheritance Protocols: An Approach to Real-Time Synchronization", IEEE Transactions on Computers, 1990). Under the priority ceiling protocol the same paper bounds blocking by one longest critical section. That blocking time B goes into the task's response-time equation as R = C + B + interference from higher-priority tasks. For example, take two lower-priority tasks and two mutexes, so n = 2 and m = 2 and at most two critical sections can block the hard task: the longest one of each lower task, here 100 us and 80 us, which the program below adds up to 180 us. The program applies it to a concrete case: the logger holds the UART for at most 100 us and the SPI bus for at most 60 us, a telemetry task holds the SPI bus for at most 80 us, and the hard task's lock call has a 150 us timeout.
# Worst-case wait of the hard task H for a mutex, from the lower-priority tasks' critical sections.
# Each lower-priority task: {mutex: longest time it holds that mutex, in microseconds}.
lower = {"logger": {"uart": 100, "spi": 60}, "telemetry": {"spi": 80}}
timeout_us = 150
n, m = len(lower), len({k for d in lower.values() for k in d})
longest = sorted((max(d.values()) for d in lower.values()), reverse=True)
pi_bound = sum(longest[:min(n, m)]) # inheritance: up to min(n, m) critical sections
ceiling_bound = max(max(d.values()) for d in lower.values()) # ceiling: one longest critical section
print(f"lower-priority tasks n = {n}, mutexes m = {m}")
print(f"inheritance bound : {pi_bound} us (sum of the min(n, m) = {min(n, m)} longest, one per task)")
print(f"ceiling bound : {ceiling_bound} us (one longest critical section)")
print(f"timed lock of {timeout_us} us waits at most min(timeout, bound): inheritance {min(timeout_us, pi_bound)} us, ceiling {min(timeout_us, ceiling_bound)} us")
lower-priority tasks n = 2, mutexes m = 2
inheritance bound : 180 us (sum of the min(n, m) = 2 longest, one per task)
ceiling bound : 100 us (one longest critical section)
timed lock of 150 us waits at most min(timeout, bound): inheritance 150 us, ceiling 100 us
So the hard task's wait is at most 180 us with inheritance and 100 us with a ceiling. These bounds are in microseconds but the API's timeout is in ticks: with a 1 ms tick the smallest timeout that guarantees a wait of at least one tick is 2 ticks (see the rounding rule below), so a 150 us figure is a budget to check, not a value that can be passed. The timeout then fires after 1 to 2 ms, which detects an overrun long after the budget; a sub-tick budget needs a finer hardware timer, or a time stamp taken when the lock call returns and compared with the budget. Two consequences for the timeout. With inheritance a timeout of 150 us is below the 180 us bound, so the lock call can legitimately time out even though nothing is wrong; if the data is mandatory the timeout must be at least the bound plus the tick rounding below. With a ceiling the 100 us bound is under the timeout, so the timeout can only fire if a critical section overruns its budget, which makes it a useful fault detector.
Details that cause bugs.
- Tick rounding: timeouts counted in ticks started part-way through a tick can expire after as little as N - 1 full ticks of real time (with a 1 ms tick, a 5-tick timeout requested 0.2 ms into a tick ends when the fifth tick interrupt arrives, 4.8 ms later, not 5 ms), so ask for N + 1 ticks when the wait must be at least N, and quote the bound in ticks including that one.
- A task whose lock call timed out does not own the mutex and must not unlock it:
rt_mutex_unlockchecks the owner and returnsRT_NOT_OWNER(the harness shows H skipping the unlock in run B). - The kernel's own critical section grows with the task count: one
recomputescans all n tasks, and it follows a chain of waits at most n deep, so the worst case is O(n^2) (O(n) per level of the chain); on a small microcontroller n is small, and that scan time counts as kernel blocking for every task. - Inheritance bounds the blocking but does not prevent deadlock with nested locks; a ceiling protocol does, which is the argument for a ceiling when the design has nested locks.
- A mutex of this kind cannot be used from an ISR: the ISR has no task priority to donate and cannot wait.
Test. Keep the printed traces of the cases above as expected output and diff every run against them (the harness itself asserts nothing, so a changed trace is the failure signal), add chains (H waits on a mutex owned by M, which waits on one owned by L) and a timeout that coincides with the unlock tick, and on the target measure the longest real critical section to confirm the figures that feed B.
You have a small microcontroller with no MMU and 8 periodic jobs running from 1 Hz to 1 kHz. Design a lightweight cooperative scheduler for it. What does a task look like, where does time come from, and how do you keep behaviour deterministic with minimal stack?
Sample Answer
Design in one paragraph
A cooperative scheduler runs tasks one at a time and never interrupts a task: a task runs until it returns (run-to-completion). With no MMU there is no memory isolation anyway, so the simplest design is a table of run-to-completion functions, a periodic timer interrupt that counts milliseconds, and a main loop that picks the most urgent task that is due. Because tasks never block and never preempt each other, the whole system needs one stack, tasks need no locks against each other, and the timing can be bounded with a short formula.
What a task looks like
A task is a function that does one period's work and returns. It must never wait (no busy loops on hardware flags, no delay calls). Anything that needs to wait becomes a small state machine: run one step, store the state in a static variable, return, and be called again next period. The table entry holds the function, its period in ticks and the tick count of its next release:
#ifndef SCHED_H
#define SCHED_H
#include <stdint.h>
typedef struct {
void (*run)(void); /* run-to-completion: must return, never block */
uint32_t period; /* in ticks (1 tick = 1 ms here) */
uint32_t next_due; /* tick count at which the next release happens */
} task_t;
/* Table order is priority order: index 0 is the most urgent task.
Runs at most one task and returns its index, or -1 if nothing is due.
The signed subtraction keeps working when the 32-bit tick counter wraps. */
static inline int sched_step(task_t *tab, unsigned n, uint32_t now)
{
for (unsigned i = 0; i < n; i++) {
if ((int32_t)(now - tab[i].next_due) >= 0) {
tab[i].next_due += tab[i].period; /* drift-free: add, never "now + period" */
tab[i].run();
return (int)i;
}
}
return -1;
}
#endif
Table order is priority order (index 0 is the most urgent). For the eight jobs from 1 kHz down to 1 Hz the periods are 1, 2, 5, 10, 20, 100, 200 and 1000 ms, so the tick is 1 ms and every period is a whole number of ticks.
Where time comes from
One hardware timer (on a Cortex-M core, SysTick) interrupts every millisecond and increments a 32-bit counter; that is all the interrupt does. The main loop reads the counter and calls sched_step. Two details keep it correct for years of uptime:
(int32_t)(now - next_due) >= 0compares counters with a signed subtraction, which stays right when the unsigned counter wraps (a millisecond counter wraps after 49.7 days).next_due += periodinstead ofnow + periodstops drift: a late task does not push every later release later.
When nothing is due the loop executes wfi (wait for interrupt), so the core sleeps until the next tick.
Keeping behaviour deterministic
The rules are: no dynamic allocation, no blocking calls, every task has a known worst-case execution time, and priority is the table order. The key consequence is a bound on lateness. A task that becomes due can wait for one lower-priority task that already started (it cannot be interrupted), plus all higher-priority releases that arrive before it starts. For task i with execution time Ci, blocking B = the longest lower-priority task, and higher-priority tasks j with period Tj and execution time Cj, the start delay w satisfies w = B + sum over j of (floor(w / Tj) + 1) x Cj, and the response time is w + Ci. The terms: w is the time from release until the task starts running. B is paid once, because a task already running cannot be interrupted, but it can only be one lower-priority task. Each higher-priority task j contributes its cost Cj once per release that happens before task i starts. The count is floor(w / Tj) + 1, not the ceil(R / Tj) of the preemptive recurrence, because here the window is [0, w] with both ends included: a higher-priority job released at exactly the instant w still runs before task i, since task i has not started, and the +1 is the release at time 0 itself. In the preemptive formula the window is the half-open interval [0, R), where a release at exactly R falls after the task has finished, so ceil is right there. Example from the first table below, task 2: B = 700 (the longest lower-priority cost), w = 700 + (floor(700/1000) + 1) x 80 + (floor(700/2000) + 1) x 100 = 880, which is stable (the floors stay 0), so the bound is 880 + 150 = 1030 us. The simulator below (a virtual clock on the host, with each task only adding its cost) computes that bound and compares it with the worst response it observes over two 1000 ms hyperperiods (the time after which every release pattern repeats). Run in a gcc:14 container (GCC 14.4, aarch64) with gcc -O2 -Wall -Wextra -o coop_sim coop_sim.c && ./coop_sim, the code in sched.h above and this file print:
#include <stdio.h>
#include <stdlib.h>
#include "sched.h"
#define N 8
static const uint32_t period_ms[N] = {1, 2, 5, 10, 20, 100, 200, 1000};
static uint32_t cost_us[N] = {80, 100, 150, 200, 300, 400, 600, 700};
static uint64_t now_us; /* virtual clock */
static const uint32_t tick0 = 0xFFFFFE00u; /* start 512 ticks before the 32-bit wrap */
static int current;
#define TASK(i) static void task##i(void) { now_us += cost_us[i]; }
TASK(0) TASK(1) TASK(2) TASK(3) TASK(4) TASK(5) TASK(6) TASK(7)
int main(int argc, char **argv)
{
if (argc > 1) cost_us[N - 1] = (uint32_t)atoi(argv[1]);
void (*fn[N])(void) = {task0, task1, task2, task3, task4, task5, task6, task7};
task_t tab[N];
for (int i = 0; i < N; i++)
tab[i] = (task_t){fn[i], period_ms[i], tick0}; /* all released together */
uint64_t worst_resp[N] = {0};
unsigned runs[N] = {0}, misses[N] = {0};
uint64_t end_us = 2000000; /* two hyperperiods of 1000 ms */
while (now_us < end_us) {
uint32_t now = tick0 + (uint32_t)(now_us / 1000); /* what the tick ISR would have counted */
uint32_t due_before[N];
for (int i = 0; i < N; i++) due_before[i] = tab[i].next_due;
current = sched_step(tab, N, now);
if (current < 0) { /* idle: sleep until the next tick */
now_us = (now_us / 1000 + 1) * 1000;
continue;
}
uint64_t release_us = (uint64_t)(due_before[current] - tick0) * 1000;
uint64_t resp = now_us - release_us;
if (resp > worst_resp[current]) worst_resp[current] = resp;
if (resp > period_ms[current] * 1000ull) misses[current]++;
runs[current]++;
}
/* Non-preemptive fixed-priority bound, integer microseconds:
B = longest lower-priority task; w = B + sum_hp (floor(w/Tj)+1)*Cj; R = w + Ci */
printf("task period_ms cost_us runs worst_resp_us bound_us misses\n");
for (int i = 0; i < N; i++) {
uint64_t B = 0;
for (int j = i + 1; j < N; j++) if (cost_us[j] > B) B = cost_us[j];
uint64_t w = B, prev;
do {
prev = w;
w = B;
for (int j = 0; j < i; j++) w += (prev / (period_ms[j] * 1000ull) + 1) * cost_us[j];
} while (w != prev && w < 10000000);
printf("%4d %9u %7u %4u %13llu %8llu %6u\n", i, period_ms[i], cost_us[i], runs[i],
(unsigned long long)worst_resp[i], (unsigned long long)(w + cost_us[i]), misses[i]);
}
return 0;
}
task period_ms cost_us runs worst_resp_us bound_us misses
0 1 80 2000 690 780 0
1 2 100 1000 790 880 0
2 5 150 400 330 1030 0
3 10 200 200 530 1310 0
4 20 300 100 830 1610 0
5 100 400 20 1230 2010 0
6 200 600 10 1910 2790 0
7 1000 700 2 2610 2610 0
The columns are runs (jobs completed in 2000 ms), the worst observed response (release to completion), the bound from the formula and the number of responses longer than the period. Task 0 is the case with no higher-priority task: its bound is B + C0 = 700 + 80 = 780 us, the time it can wait behind the 700 us task plus its own run, against 690 us observed. The bound is never below the observation, and for the slowest task they coincide. The costs are illustrative figures chosen to total 20.3 percent utilisation. Lengthening the slowest task to 1500 us (./coop_sim 1500) shows what the rule "no task longer than the shortest deadline minus the fastest task's cost" protects. Here the fastest task has a 1000 us deadline and costs 80 us, so no task may run longer than 1000 - 80 = 920 us; the 700 us task passes (bound 780 us for task 0, under 1000) and the 1500 us task breaks the rule (bound 1500 + 80 = 1580 us, over 1000):
task period_ms cost_us runs worst_resp_us bound_us misses
0 1 80 2000 1490 1580 2
1 2 100 1000 1670 1760 0
2 5 150 400 330 1910 0
3 10 200 200 530 2110 0
4 20 300 100 830 2590 0
5 100 400 20 1230 2990 0
6 200 600 10 1910 3590 0
7 1000 1500 2 3410 3410 0
Task 0 now has a bound of 1580 us against a 1000 us period and is observed missing twice: in each hyperperiod the release at 2 ms waits behind the long task, which has just started, and completes 1490 us after its release. The fix is to split the long task into steps of under about 900 us (a state machine that does part of the work per call), not to add preemption.
The same scheduler on a Cortex-M3, run in QEMU
The sched.h file above also runs unchanged on an emulated Cortex-M3 (QEMU lm3s6965evb, 50 MHz core clock assumed for the 1 ms reload; the file is bare-metal start-up code, so the notes after the output say what each unusual part is for), with a real SysTick interrupt, a vector table, and output over the UART:
#include <stdint.h>
#include "sched.h"
#define UART0_DR (*(volatile uint32_t *)0x4000C000u)
#define SYST_CSR (*(volatile uint32_t *)0xE000E010u)
#define SYST_RVR (*(volatile uint32_t *)0xE000E014u)
#define SYST_CVR (*(volatile uint32_t *)0xE000E018u)
static volatile uint32_t g_ticks;
static volatile uint32_t isr_sp, main_sp;
static void put(const char *s) { while (*s) UART0_DR = (uint8_t)*s++; }
static void putu(uint32_t v)
{
char b[11]; int n = 0;
do { b[n++] = (char)('0' + v % 10); v /= 10; } while (v);
while (n) UART0_DR = (uint8_t)b[--n];
}
/* The handler stub records SP exactly as the hardware left it, then calls C. */
void SysTick_C(uint32_t sp_after_stacking)
{
isr_sp = sp_after_stacking;
g_ticks++;
}
__attribute__((naked)) void SysTick_Handler(void)
{
__asm volatile("mov r0, sp\n b SysTick_C\n");
}
static volatile uint32_t count[8];
#define TASK(i) static void task##i(void) { count[i]++; }
TASK(0) TASK(1) TASK(2) TASK(3) TASK(4) TASK(5) TASK(6) TASK(7)
static task_t tab[8] = {
{task0, 1, 0}, {task1, 2, 0}, {task2, 5, 0}, {task3, 10, 0},
{task4, 20, 0}, {task5, 100, 0}, {task6, 200, 0}, {task7, 1000, 0},
};
int main(void)
{
SYST_RVR = 50000 - 1; /* 1 ms if the core clock is 50 MHz */
SYST_CVR = 0;
SYST_CSR = 7; /* enable, tick interrupt, core clock */
while (g_ticks < 2000) {
if (sched_step(tab, 8, g_ticks) < 0) {
__asm volatile("mov %0, sp" : "=r"(main_sp));
__asm volatile("wfi");
}
}
SYST_CSR = 0;
put("ticks "); putu(g_ticks); put("\n");
for (int i = 0; i < 8; i++) { put("task"); putu((uint32_t)i); put(" period "); putu(tab[i].period); put(" runs "); putu(count[i]); put("\n"); }
put("sp in main loop minus sp after exception entry: "); putu(main_sp - isr_sp); put(" bytes\n");
/* semihosting: SYS_EXIT (0x18) */
register uint32_t r0 __asm("r0") = 0x18, r1 __asm("r1") = 0x20026;
__asm volatile("bkpt 0xAB" :: "r"(r0), "r"(r1));
for (;;) {}
}
extern uint32_t _estack;
extern uint32_t _sdata, _edata, _sidata, _sbss, _ebss;
void Reset_Handler(void)
{
for (uint32_t *s = &_sidata, *d = &_sdata; d < &_edata;) *d++ = *s++; /* copy .data from flash */
for (uint32_t *d = &_sbss; d < &_ebss;) *d++ = 0; /* zero .bss */
main();
for (;;) {}
}
__attribute__((section(".vectors"), used)) const void *vectors[] = {
&_estack, Reset_Handler, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SysTick_Handler,
};
with the linker script
MEMORY { FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 256K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 64K }
_estack = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS {
.text : { KEEP(*(.vectors)) *(.text*) *(.rodata*) } > FLASH
_sidata = LOADADDR(.data);
.data : { _sdata = .; *(.data*) _edata = .; } > RAM AT > FLASH
.bss : { _sbss = .; *(.bss*) *(COMMON) _ebss = .; } > RAM
}
Built with arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -O1 -Wall -Wextra -ffreestanding -nostdlib -T link.ld coop_m3.c -o coop_m3.elf and run with qemu-system-arm -M lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel coop_m3.elf (GCC 14.2.1 arm-none-eabi, QEMU 10.0.13), it prints:
arm-none-eabi-gcc (15:14.2.rel1-1) 14.2.1 20241119
QEMU emulator version 10.0.13 (Debian 1:10.0.13+ds-0+deb13u1)
ticks 2000
task0 period 1 runs 2000
task1 period 2 runs 1000
task2 period 5 runs 400
task3 period 10 runs 200
task4 period 20 runs 100
task5 period 100 runs 20
task6 period 200 runs 10
task7 period 1000 runs 2
sp in main loop minus sp after exception entry: 32 bytes
What the unusual parts are for. UART0_DR, SYST_CSR, SYST_RVR and SYST_CVR are memory-mapped I/O (MMIO): hardware registers that appear at fixed addresses, accessed through volatile pointers so that the compiler really performs every read and write. SysTick is the Cortex-M core's built-in countdown timer; SYST_RVR is its reload value (50,000 - 1 counts of a 50 MHz clock is 1 ms), SYST_CVR its current value, and SYST_CSR = 7 enables it, its interrupt and the core clock source. wfi is the instruction that sleeps the core until an interrupt. The vector table is an array the core reads at reset and on exceptions: the first entry is the initial stack pointer, the second the reset handler, and entry 15 the SysTick handler. Reset_Handler runs before main: it copies the .data section (initialised global variables, stored in flash) into RAM and zeroes .bss (global variables without an initial value), which C assumes already happened. naked tells the compiler to emit no function prologue or epilogue, so sp is still the value the hardware left on exception entry; mov r0, sp then passes that value as the first argument (register r0, per the Arm calling convention) to SysTick_C. The final bkpt 0xAB is a semihosting call, a mechanism where code running under an emulator or debugger asks the host to do something, here to end the program; register ... __asm("r0") pins the two values into the registers that call reads. The linker script places the vector table and code in flash at address 0, .data in RAM with a load copy in flash, and defines the symbols (_estack, _sdata, _sidata, ...) that the C code refers to.
Over 2000 ticks each task ran exactly 2000 / period times, and the 32 bytes between the main loop's stack pointer and the stack pointer on entry to the interrupt handler are the 8-word frame (r0-r3, r12, lr, pc, xPSR) the core pushes on an exception when no floating-point state is saved. QEMU does not model cycle-accurate timing, so this run shows the scheduling logic and the stack cost, not the microsecond figures; those come from the host simulator's cost model, to be replaced by measured execution times.
Stack, with minimal waste
There is one stack, shared by everything. Its worst-case depth is the main loop's frame, plus the deepest task's frame (tasks are called from the loop and return, so only one is live), plus one exception frame of 32 bytes for the tick interrupt (more if the interrupt calls deeper code, and larger frames if floating-point state is stacked). Compare with an RTOS design, which needs one stack per task: eight tasks times 256 to 512 bytes each would cost 2 to 4 KB before any interrupt. Measure the real worst case by filling the stack with a known pattern at start-up and checking how much is overwritten (a high-water mark) after a long run.
Limits to state in a review
- Responsiveness is set by the longest task, so any task longer than the tightest deadline is a defect (see the 1500 us run).
- One tick of extra latency is possible if the tick fires between the last
sched_stepreturning and thewfi, because the loop then sleeps until the following tick. Releases are quantised to ticks already, so budget one tick of release jitter. - Anything with a sub-millisecond deadline (a motor commutation, a receive buffer) belongs in an interrupt handler that sets a flag or fills a ring buffer, with the cooperative task doing the slow part afterwards.
- If one task cannot be shortened, move to a preemptive RTOS rather than patch the scheduler.
Unlock Full Question Bank
Get access to all 32 Real-Time Systems, RTOS Scheduling & WCET interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.