Skip to content
Tech Interview Prep
Technical interview guide

RTOS & Task Scheduling

How a real-time operating system schedules multiple tasks with timing guarantees, and the classic concurrency hazards (priority inversion, deadlock) that come with it.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: CMSIS-RTOS2 current API; CMSIS-RTX5 current configuration; current FreeRTOS and Zephyr scheduling guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Design and validate RTOS behavior for thread states.

Answer

Assumptions. Single core, preemptive priority scheduling. FreeRTOS 11.x on Cortex-M4F; Zephyr 3.x where it differs. configTICK_RATE_HZ = 1000 (1 ms tick), configMAX_PRIORITIES = 5, configUSE_PREEMPTION = 1, configUSE_TIME_SLICING = 1, configUSE_MUTEXES = 1, INCLUDE_vTaskSuspend = 1.

The model. A thread is in exactly one state, and in both kernels that state is literally which list its TCB sits on: the ready list for its priority, a blocked list owned by the object it waits on, the delayed list (a timeout), or the suspended list. The scheduler runs the highest-priority TCB on a ready list; equal priorities round-robin. Blocking is a list move, not a spin: that is why a blocked thread costs no CPU, and it is the invariant to validate against. Design around three rules: every block has a bounded wakeup, no unbounded priority inversion, and state is never read without a critical section.

StateFreeRTOSZephyrEntered byLeft by
RunningeRunning_THREAD_RUNNINGscheduler picks itpreemption, block, yield
ReadyeReady_THREAD_READYcreate, unblock, preemptscheduler picks it
BlockedeBlocked_THREAD_PENDINGxQueueReceive, xSemaphoreTakeevent or timeout
SleepingeBlocked + timeout_THREAD_SLEEPINGvTaskDelay, k_sleeptick expiry
SuspendedeSuspended_THREAD_SUSPENDEDvTaskSuspend, k_thread_suspendvTaskResume, k_thread_resume
DeletedeDeleted (TCB awaiting idle-task free)_THREAD_DEADvTaskDelete, thread returnidle task frees TCB, k_thread_join

FreeRTOS has no separate sleeping state: vTaskDelay blocks the task with a timeout, so eTaskGetState() reports eBlocked. Read state with eTaskGetState() (INCLUDE_eTaskGetState = 1) or uxTaskGetSystemState() (configUSE_TRACE_FACILITY = 1); in Zephyr, k_thread_state_str() (CONFIG_THREAD_MONITOR).

Worked trace.

C
/* FreeRTOS 11.x, Cortex-M4F */
#define PRIO_FEEDER 3
#define PRIO_WORKER 2

static QueueHandle_t q;   /* xQueueCreate(4, sizeof(uint32_t)) */

static void worker(void *arg)
{
    uint32_t item;
    for (;;) {
        if (xQueueReceive(q, &item, portMAX_DELAY) == pdTRUE) {
            process(item);
        }
    }
}

static void feeder_isr(void)
{
    BaseType_t woken = pdFALSE;
    uint32_t item = read_hw();
    xQueueSendFromISR(q, &item, &woken);
    portYIELD_FROM_ISR(woken);
}
t (ms)Eventworker TCBready listqueue count
0.00xQueueReceive, queue emptyeBlockedidle (prio 0)0
0.40ISR: xQueueSendFromISReBlocked → eReadyworker (2), idle (0)1
0.40ISR exit, PendSVeRunningidle (0)0

At t = 0.40 the ISR copies the item into the queue storage, then xTaskRemoveFromEventList() moves the worker TCB from the queue's xTasksWaitingToReceive list to ready list[2] and returns pdTRUE because the worker's priority (2) beats the interrupted task's (0). portYIELD_FROM_ISR pends PendSV; on ISR exit the worker resumes inside xQueueReceive, copies the item out, and returns pdTRUE. The item was latched in the queue, so nothing is lost. If the ISR fires before the worker blocks, the count is already 1 and xQueueReceive returns without blocking: same outcome.

A lost wakeup needs a signal that does not latch. Queues and semaphores latch, so the check-then-block race is safe with them. It bites when a binary semaphore counts events: two xSemaphoreGiveFromISR calls before the worker runs leave the count at 1, and the second event is gone. Use xSemaphoreCreateCounting or a queue of length N.

Trade-offs. A mutex (xSemaphoreCreateMutex) has priority inheritance; a binary semaphore does not. With H(3), M(2), L(1): L takes the mutex, H preempts and blocks on it, M becomes ready and preempts L. L never releases, so H waits out all of M. Inheritance raises L to 3 so it finishes and releases; the holder takes the priority of the highest-priority waiter. Zephyr's k_mutex inherits too; CONFIG_PRIORITY_CEILING switches to the ceiling protocol. Use a mutex for a shared resource, a semaphore for signalling. Tickless idle (configUSE_TICKLESS_IDLE, Zephyr CONFIG_TICKLESS_IDLE) stops the tick when idle; the cost is that every timeout now depends on reprogramming the wake timer correctly.

Failure modes and validation.

FailureSymptomDetectionCost
Lost wakeuptask blocked foreverwatchdog heartbeat, block timeoutmissed deadline
Priority inversionH never runsruntime stats show H starveddeadline miss
Suspended mutex holderall waiters blockxSemaphoreTake timeoutdeadlock
Stale handlecrash, corruptionconfigASSERT, MPU, handle validationmemory corruption
Torn state readwrong state in debuggereTaskGetState() (takes a critical section)bad diagnosis
ISR above configMAX_SYSCALL_INTERRUPT_PRIORITYconfigASSERT or corruptioncheck NVIC priority vs the config valuekernel corruption

Validate with Percepio Tracealyzer or SEGGER SystemView, then check the recorded transition sequence matches the table above. Toggle a GPIO in the ISR and at the worker's first instruction after wakeup; a scope gives wakeup latency end to end. At 100 MHz, 1 µs is 100 cycles, and a PendSV switch is roughly 100–200 cycles including tail-chaining, so expect low single-digit microseconds: measure it, don't assume it. If the delta is near a full tick instead, the ISR is not preempting: check its NVIC priority against configMAX_SYSCALL_INTERRUPT_PRIORITY. Inject faults: vTaskSuspend the mutex holder and assert the waiter times out. Stress with a 10 kHz ISR giving the semaphore and compare gives against wakeups. Note vTaskDelay(1) unblocks at the next tick boundary, so the elapsed delay is anywhere from just over zero to a full tick period depending on where in the tick period the call lands.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and validate RTOS behavior for cooperative tasks.

Answer

Assumptions: Cortex-M MCU, FreeRTOS 10.5 with configUSE_PREEMPTION=0 and configUSE_TIME_SLICING=0, 1 kHz tick, control loop deadline 500 µs. Zephyr's equivalent is a thread at a negative priority (K_PRIO_COOP), which nothing but an ISR can preempt.

Core answer. Cooperative scheduling means the scheduler switches only when the running task yields or blocks: there is no tick-driven preemption. So the design question is not "what priority" but "what is the longest run-to-completion segment, and what is the sum of all segments ahead of my deadline." Design is bounding every segment and putting a yield or block point at its end. Validation is measuring the real segment lengths, proving the sum fits the deadline, and installing a watchdog that can still fire when a task never reaches its yield point.

Mechanism. With preemption off, a ready task runs until it calls taskYIELD(), blocks on a queue/semaphore with a timeout, or calls vTaskDelay(). Response time for an event is therefore the sum of the remaining segments of every task ahead of it, not the highest-priority task's own runtime. That is the whole trade: you get race-free access to shared state between tasks (only ISRs can interleave) and simpler reasoning, and you pay for it with additive latency.

Worked budget.

tasksegment budgetmeasured worstyield point
control120 µs96 µsvTaskDelay(1)
comms250 µs310 µsqueue receive, 0 timeout
log80 µs80 µsxQueueSend to drain task

Worst case for a control tick arriving just after comms starts: 310 + 80 + 3 × 5 µs switch overhead = 405 µs against a 500 µs deadline. 95 µs margin. If comms regresses to 400 µs the margin is 5 µs and any jitter misses. The 310 µs measurement is already an overrun of the 250 µs budget and is the defect to fix, not the margin.

Enforcing it in code. Measure with the Cortex-M DWT cycle counter (CoreDebug->DEMCR |= TRCENA; DWT->CTRL |= CYCCNTENA;), 140 MHz → 120 µs = 16800 cycles:

C
#define SEG_BUDGET_CYC 16800u
void vControlTask(void *arg) {
    for (;;) {
        uint32_t t0 = DWT->CYCCNT;
        run_control_step();                 /* must not block */
        if (DWT->CYCCNT - t0 > SEG_BUDGET_CYC) g_overrun[CTRL]++;
        vTaskDelay(pdMS_TO_TICKS(1));       /* the yield point */
    }
}

Validation and failure modes. In a purely cooperative system nothing preempts a hung task, so the watchdog cannot be kicked by a task. Kick it from the SysTick ISR only if every heartbeat counter has advanced since the last tick; otherwise let the hardware watchdog (100 ms) expire. That single mechanism covers the common misses:

  • Missing yield / infinite loop: heartbeat stops, WDT resets the board. Cost: full reset, not one task.
  • Retry loop: each I2C retry is bounded but the loop around it is not. Count retries per segment, assert above 3.
  • Callback chain: driver callback invokes another. Keep a depth counter, assert at 8.
  • Work burst: a 1000-message queue drain runs in one segment. Process at most K items, then yield.
  • Unbounded library call: printf over UART at 115200 baud costs 86.8 µs/byte, so a 64-byte line is 5.5 ms, 11× the entire deadline. Wrap it in the DWT check or ban it from the segment.

Alternatives and when to pick them. Preemptive scheduling gives latency independent of other tasks' code, at the cost of per-task stacks and mutexes with priority-inheritance. Zephyr's hybrid model: negative-priority cooperative threads for short critical work, preemptible threads for the rest: gets both. Tickless idle is orthogonal: it changes power, not scheduling semantics, but it does change how you measure segment time. Decide on one number: if the sum of segments fits the deadline with margin, cooperative is simpler and needs no inter-task locking; if any segment is unbounded or the sum exceeds the deadline, go preemptive or split the task.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design and validate RTOS behavior for preemptive scheduling.

Answer

I'll assume FreeRTOS v10.4.3 on a Cortex-M4 at 168 MHz, a 1 kHz tick, and a control task that must run every 1 ms with a 200 µs deadline. The shared resource is a sensor read protected by a mutex.

Design: preemptive scheduling with distinct priorities, mutexes with priority inheritance, critical sections under 10 µs, and interrupt priorities set so only kernel-aware interrupts call the FreeRTOS API. Validate with three measurements: wake-to-run latency (GPIO toggle plus scope), a priority-inversion stress test, and maximum interrupt-disabled time (a second GPIO).

A reschedule point is where the kernel checks for a higher-priority ready task: every tick, on any API call that unblocks a task, and on interrupt exit if the ISR made a task ready. Wake-to-run latency is interrupt entry + ISR + kernel exit + context switch. A critical section that masks interrupts adds its length directly. Priority inheritance: when a high-priority task blocks on a mutex held by a low-priority task, the holder inherits the high priority, so a medium-priority task cannot preempt it. That bounds inversion to the length of the critical section.

Preemptive vs cooperative: preemptive meets hard deadlines but needs careful critical sections; cooperative avoids races but cannot preempt. Time slicing vs none: slicing gives fairness among equal priorities but adds context switches; for hard real-time, disable slicing and use distinct priorities. Priority inheritance vs priority ceiling: inheritance is simpler and needs no a-priori knowledge, but a task can be blocked once per mutex it touches, so worst-case blocking grows with the number of mutexes (chained blocking), and inheritance does not prevent deadlock from inconsistent lock ordering. Ceiling assigns each mutex the highest priority of any task that locks it; the holder runs at that ceiling, which bounds blocking to a single critical section and, with the protocol followed, prevents deadlock: at the cost of knowing all lockers upfront and raising the holder's priority even when there is no contention.

Failure modes and detection:

  • Scheduler locked: vTaskSuspendAll without xTaskResumeAll stops all tasks. Detect with a watchdog task checking a low-priority heartbeat.
  • ISR ceiling wrong: an ISR whose priority is numerically lower than configMAX_SYSCALL_INTERRUPT_PRIORITY must not call the FreeRTOS API; if it does, kernel state corrupts. Detect by asserting the priority in the ISR.
  • Equal-priority assumption: two tasks at the same priority sharing a mutex. The non-holder can preempt the holder and cause inversion. Detect in trace as a high-priority task blocked by a lower-priority one.
  • Long non-preemptible region: a critical section longer than the deadline causes missed deadlines. Detect by measuring max interrupt-disabled time with a GPIO toggle.
  • Trace changes timing: instrumentation adds microseconds and shifts scheduling. Detect by comparing latency with and without trace, or use non-intrusive ETM.
CheckPassFailHow to measure
Wake-to-run latency< 50 µs> 200 µsGPIO toggle in ISR and task, scope
Priority inversionHigh task blocked < 20 µsHigh task blocked > 100 µsStress test with medium task, trace
Interrupt-disabled time< 10 µs> 50 µsGPIO toggle around critical section, scope
Scheduler lockHeartbeat every 10 msNo heartbeat for 100 msWatchdog task

Hypothetical trace: at t=0, low-priority task holds the mutex. t=10 µs, high-priority task becomes ready and blocks on the mutex; the low-priority task inherits the high priority. t=20 µs, medium-priority task becomes ready but cannot preempt the holder. t=30 µs, low-priority task releases the mutex and the high-priority task runs. Without inheritance, the medium-priority task would run from t=20 to t=100 µs, an 80 µs inversion.

C
// Critical section: keep under 10 µs
taskENTER_CRITICAL();
// read sensor register
taskEXIT_CRITICAL();

// Mutex with priority inheritance
SemaphoreHandle_t xMutex = xSemaphoreCreateMutex();

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate RTOS behavior for tick and time.

Answer

Clarify, then assume. "Tick and time" is two clocks, not one: the monotonic tick counter the scheduler uses for timeouts and delays, and the wall clock (RTC) that something can step backwards. I'd assume FreeRTOS 11.x with configTICK_RATE_HZ = 1000, configUSE_16_BIT_TICKS = 0 (so TickType_t is uint32_t), and configUSE_TICKLESS_IDLE = 1. On Zephyr the design changes shape: k_uptime_get() is a 64-bit millisecond counter, so wrap stops being a design concern.

The design is three decisions: tick rate, tick width, comparison idiom.

Tick rate: 1000 Hz gives 1 ms resolution at the cost of a 1 kHz interrupt; 100 Hz cuts idle wakeups tenfold but quantises every timeout to 10 ms. Battery sensor node, 100 Hz. Motor control loop, 1000 Hz.

Width: 32-bit at 1 kHz wraps every 2^32/1000 s = 49.7 days. 16-bit at 1 kHz wraps every 65.5 s: inside a single soak test, so configUSE_16_BIT_TICKS = 1 is only defensible at low tick rates or with short timeouts.

Comparison: never compare absolute tick values. Compute elapsed by unsigned subtraction.

C
/* FreeRTOS 11.x, configTICK_RATE_HZ=1000, configUSE_16_BIT_TICKS=0 */
TickType_t start   = xTaskGetTickCount();
TickType_t timeout = pdMS_TO_TICKS(500);   /* 500 ticks */

for (;;) {
    if ((TickType_t)(xTaskGetTickCount() - start) >= timeout) {
        return TIMEOUT;
    }
    /* block on the event for the remaining time */
}

Why that works: TickType_t is unsigned, so now - start is evaluated modulo 2^32. As long as the true elapsed time is under 2^32 ticks, the wrapped result is the elapsed count. It is modular arithmetic, not a special case for wrap.

In production use the kernel helper, which also subtracts time already spent waiting:

C
TimeOut_t state;
TickType_t remaining = pdMS_TO_TICKS(500);
vTaskSetTimeOutState(&state);
for (;;) {
    if (xTaskCheckForTimeOut(&state, &remaining) != pdFALSE) return TIMEOUT;
    /* wait on the event with `remaining` */
}

Periodic work uses vTaskDelayUntil(&last, period) so the period does not drift by the execution time. Inside an ISR, xTaskGetTickCountFromISR().

Trace. start = 0xFFFFFF00, timeout = 500.

now(uint32)(now-start)correctnaive now >= start+timeout
0xFFFFFFF0240not expired4294967280 >= 244 → expired (wrong)
0x000000F4500expired244 >= 244 → expired
0x00000100512expired256 >= 244 → expired

Row 1 is the bug: start + timeout wrapped to 244 while now had not yet wrapped, so the naive test fires 260 ticks early.

Trade-offs. Tickless idle suppresses the tick and reprograms the wake timer, so a 1 kHz tick costs nothing while the CPU sleeps; the price is that xTaskGetTickCount() is corrected on wake, and any code that assumed the tick advances in real time needs re-checking. Zephyr's 64-bit k_uptime_get() removes wrap entirely but costs 8 bytes per timestamp and 64-bit arithmetic on a 32-bit MCU.

Failure modes, with detection.

  • Naive now >= deadline fires early or never. Detect with a unit test that seeds the tick counter near 0xFFFFFFFF and asserts the timeout fires at exactly 500 ticks.
  • Multiplication overflow: pdMS_TO_TICKS(ms) computes ms * configTICK_RATE_HZ / 1000, which overflows 32-bit at 1 kHz for ms above ~4.29 million (about 71 minutes). Use the macro, and keep timeouts well under that.
  • Zero timeout: xQueueReceive(q, &item, 0) polls and returns immediately; portMAX_DELAY (0xFFFFFFFF) blocks forever and needs INCLUDE_vTaskSuspend = 1. Swapping them turns a poll into a hang.
  • Clock stops: in tickless idle the tick is frozen for the sleep window, so a watchdog or a second timer has to cover it.
  • Wall clock adjustment: settimeofday must not touch the tick counter. Keep gettimeofday and xTaskGetTickCount separate: a timeout computed from wall clock jumps when NTP steps the clock.

Validation. Unit-test the comparison with a mocked tick counter at 0, 0xFFFFFF00, 0xFFFFFFFF and 0x00000010; run a soak past the 49.7-day wrap or force the counter; measure idle current with tickless on and off; and assert that a ±1 hour wall-clock step changes no timeout.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design and validate RTOS behavior for priority assignment.

Answer

Priority assignment is not a judgement about what matters; it is the output of a schedulability analysis. I would assume a single-core preemptive fixed-priority RTOS, periodic tasks with known periods and worst-case execution times, and ask one question: does every task meet its deadline under the assignment I picked? If yes, I validate by measurement. If no, I change the assignment, not the analysis.

Mechanism. Under fixed-priority preemptive scheduling the highest-priority ready task runs, so a task's worst-case response time is its own execution plus blocking plus the interference from every higher-priority task:

R_i = C_i + B_i + Σ_{j ∈ hp(i)} ⌈R_i / T_j⌉ · C_j

You solve it by fixed-point iteration starting from R_i = C_i + B_i. Rate-monotonic (shorter period → higher priority) is optimal among fixed-priority assignments when deadlines equal periods (Liu & Layland, 1973); deadline-monotonic is optimal when deadlines are ≤ periods. The RM utilisation bound n(2^(1/n) − 1) → ln 2 ≈ 0.693 is only a sufficient test: the response-time equation above is exact, so use it.

Worked check. Cortex-M7 at 400 MHz, FreeRTOS with configTICK_RATE_HZ = 1000, configUSE_PREEMPTION = 1, configUSE_TIME_SLICING = 0.

taskTCD
control1 ms150 µs1 ms
comms5 ms400 µs5 ms
telemetry20 ms1.2 ms20 ms
logging100 ms3 ms100 ms

RM order: control > comms > telemetry > logging. Total U = 0.15 + 0.08 + 0.06 + 0.03 = 0.32. Telemetry's response time: R₀ = 1.2 ms; R₁ = 1.2 + ⌈1.2/1⌉·0.15 + ⌈1.2/5⌉·0.4 = 1.9 ms; R₂ = 1.9 ms, converged, ≤ 20 ms. Feasible.

Now assign by importance instead: telemetry is safety-relevant, so give it priority 5 and drop control to 4. Control's response time becomes R₀ = 0.15 ms; R₁ = 0.15 + ⌈0.15/20⌉·1.2 = 1.35 ms; converged at 1.35 ms > 1 ms deadline. The control loop misses every period. That is the whole argument against importance-based assignment, in one number.

C
/* fixed-point response-time analysis, single core, fixed priority */
static uint32_t rta(uint32_t C, uint32_t B, const Task *hp, int n) {
    uint32_t R = C + B;
    for (int iter = 0; iter < 64; iter++) {
        uint32_t next = C + B;
        for (int j = 0; j < n; j++)
            next += ((R + hp[j].T - 1) / hp[j].T) * hp[j].C;  /* ceil */
        if (next == R) return R;
        R = next;
    }
    return UINT32_MAX;  /* diverged: infeasible */
}

Alternatives. RM is optimal for D = T and degrades gracefully under overload: the lowest-priority tasks miss first. DM is optimal for D ≤ T and needs no extra machinery. EDF is optimal for dynamic priority and reaches U = 1.0, but a single overload triggers the domino effect: one miss cascades into many, and you cannot predict which task fails. For a control loop with a hard deadline, fixed priority plus RM/DM is the safer default; reach for EDF only when utilisation is high and you can bound overload.

Failure modes and detection. Priority inversion: FreeRTOS queues and binary semaphores do not inherit priority. Only mutexes (configUSE_MUTEXES = 1) do, as does Zephyr's k_mutex. A low-priority task holding a binary semaphore blocks a high-priority task for its entire remaining execution. Detect with configUSE_TRACE_FACILITY or SystemView: a high-priority task in Blocked longer than the critical section it shares. Tick granularity: at 1000 Hz a 1 ms control loop released by vTaskDelayUntil carries up to 1 tick of release jitter. 100% of its period. Detect by toggling a GPIO at task entry and scoping the jitter; fix with a hardware timer. Priority drift: any vTaskPrioritySet at runtime invalidates the analysis. Log every change and assert the static table at boot.

Validation. Measure worst-case response with a GPIO toggle plus scope or the trace facility, compare against the RTA figure, and keep margin. Analysis tells you it should hold; the scope tells you it does.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design and validate RTOS behavior for periodic release.

Answer

Core answer (say this first). Pin down three things before designing: the period T, the tick rate, and whether the job's deadline equals its period (D = T) or is shorter. Then release on an absolute, monotonic tick schedule, never a relative sleep, compare deadlines with wrap-safe signed arithmetic, and choose catch-up or skip from the deadline semantics rather than from taste. Validate by measuring release jitter and missed-period counts under injected overrun, tick wrap, and suspend.

Why absolute releases. vTaskDelay(T) measures from when the task last ran, so each cycle costs T plus execution time. A 10 ms loop with a 3 ms job runs every 13 ms; after 100 releases it is 300 ms, 30 periods, behind. xTaskDelayUntil(&last, T) computes the next wake as last + T, so release n lands at t0 + n·T and only scheduler latency (typically under one tick) shows up as jitter. Phase is preserved because the base never absorbs execution time.

Wrap-safe comparison. With configUSE_16_BIT_TICKS = 0, TickType_t is uint32_t; at configTICK_RATE_HZ = 1000 it wraps every ~49.7 days. Compare with a signed difference, not >=:

C
if ((int32_t)(now - deadline) >= 0) { /* deadline passed */ }

This is correct as long as the interval is under half the tick range: 2^31 ticks ≈ 24.8 days at 1 kHz. A raw now >= deadline breaks at wrap: the task either stalls a full wrap or fires immediately.

Catch-up vs skip. Decide from the deadline, not from the mechanism:

JobPolicy on missed periodWhy
Control loop with integratorBounded catch-up (≤2), then resyncSkipping a sample corrupts the integral; unbounded catch-up saturates CPU
Sensor sampler into a queueSkip, log the gapConsumer tolerates a gap; catch-up only adds stale samples
Actuator with D = TSkip, count as a deadline missThe deadline is already gone; catching up cannot un-miss it
Telemetry / loggingSkipNo correctness impact

Zephyr gives you the counter for free: k_timer_status_sync() returns the number of expiries since the last sync.

Failure modes and how you see them.

  • Tick wrap: symptom is a task that stalls for ~49.7 days or fires a burst. Detect by forcing the tick counter near 0xFFFFFFFF in a test build and running two wraps.
  • Overrun → busy catch-up: a 3 ms job that overruns to 30 ms queues three back-to-back catch-ups, each also overrunning; CPU idle drops to zero and the watchdog resets. Detect by counting consecutive xTaskDelayUntil pdFALSE returns and alarming above a threshold.
  • Clock change: anchoring to RTC means an NTP step or DST jump moves every release. Detect by scheduling only off the monotonic tick; if RTC is unavoidable, compare k_uptime_get() against the RTC delta and resync on a step.
  • Suspended interval: a debugger halt or low-power sleep stops the tick; on resume the absolute deadline is far in the past and you get a catch-up burst. Detect by comparing now against deadline on resume and resyncing if the gap exceeds one period.
  • Phase reset after fault: a watchdog reset loses the phase base, so two tasks that were offset now collide. Detect by persisting the base in no-init RAM or recomputing it from a shared time base.

Validation. Instrument a GPIO toggle at release and at job end, capture on a logic analyzer, and compute release jitter = actual − (t0 + n·T). Acceptance: max jitter under one tick, zero missed periods in a nominal 10-minute run, catch-up count zero. Then inject: a 25 ms job for five periods (assert catch-up ≤ 2 and a resync logged), a 500 ms debugger halt (assert one resync, not fifty catch-ups), and a forced tick wrap (assert no stall). Record CPU idle time throughout, if it falls below 20% during the overrun test, the catch-up bound is too loose.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design and validate RTOS behavior for WCET.

Answer

Core answer (first 90 seconds). Assume a hard-real-time single-core Cortex-M7 at 216 MHz, fixed-priority preemptive scheduling, and deadline equal to period. WCET is not a number you measure once; it is a bound you design for and then validate. Design for analyzability first: every loop has a constant trip count the analyzer can read, no recursion, no malloc in the hot path, no flash erase or other bus-stalling operation inside a deadline-bearing task, and all shared state guarded by a priority-inheritance mutex so blocking is bounded. Then establish the bound with static WCET analysis against a processor timing model (cache, pipeline, branch prediction), cross-check it by measurement on the release binary with cold caches and interrupts enabled, add RTOS kernel overhead, and prove schedulability with response-time analysis plus a margin.

Why static analysis, not just measurement. Measurement gives the worst case you observed; it cannot cover every path and every cache state, so it is a lower bound on WCET, not an upper bound. Static analysis (abstract interpretation, e.g. AbsInt aiT) walks all feasible paths and adds a timing model, so it is an upper bound, but only if you supply flow facts (loop bounds, infeasible-path annotations) and a correct model for your exact core revision. It is pessimistic: a bound 20–40% above the true worst case is normal, and that pessimism costs schedulability headroom.

Trade-offs. Static: safe, certifiable (DO-178C and ISO 26262 expect it), expensive, needs flow facts. Measurement: cheap and fast, but no proof. Fine for soft real-time or as a cross-check. Hybrid (e.g. Rapita RapiTime) measures basic-block times and statically enumerates paths, giving a tighter bound than pure static with more evidence than pure measurement. Use measurement alone only when a deadline miss is recoverable.

Kernel overhead and blocking. Task WCET must include context switch, tick ISR, and interrupt latency. On Cortex-M3/M4 the documented exception entry is 12 cycles and tail-chaining 6 cycles; at 216 MHz that is ~56 ns and ~28 ns: small, but not zero. Priority-inheritance blocking is bounded by the longest critical section of any lower-priority task sharing the mutex.

Worked validation. Three tasks, deadline = period:

taskT (µs)static WCET C (µs)U
A10004700.47
B50009000.18
C2000024000.12

Total U = 0.77, plus ~3% kernel overhead → 0.80. The rate-monotonic sufficient bound for n=3 is 3(2^(1/3)−1) = 0.78, so 0.80 exceeds it: the bound is inconclusive and you must run exact response-time analysis. Iterating R = C + Σ⌈R/T_j⌉·C_j gives R_C = 7960 µs < 20000 µs, so the set is schedulable. That is the point: the sufficient bound failing does not mean failure, it means you do the real analysis.

Failure modes and detection. Debug build: unoptimized code is often 2–5× slower. Always measure the release binary. Warm-cache-only measurement: cold cache adds misses; flush between releases or let static analysis carry the cache term. Unbounded parse or malloc: WCET is unbounded. Detect when static analysis flags the loop, or catch it with a watchdog. Flash erase: on many MCUs it stalls the flash bus for hundreds of milliseconds to seconds per sector, so a task executing from flash misses every deadline. Detect with a bus trace, fix by deferring to a low-priority task or using dual-bank. Retry storm: a bounded retry count is still a WCET multiplier. Bound retries and count them in the analysis. Detect all of these with ETM instruction trace plus coverage, and hold a margin (commonly 20–30%) over the validated bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and validate RTOS behavior for utilization.

Answer

Assume periodic tasks, fixed-priority preemptive scheduling, deadlines equal periods. The core answer: design for utilization means compute worst-case utilization and compare it to the Liu & Layland bound for rate-monotonic (RM) scheduling: n(2^(1/n)-1), which is 69.3% as n grows (Liu & Layland, 1973). But average utilization is not enough. Validate by measuring slack and testing overload with realistic phasing.

For RM, the bound is sufficient but not necessary. For n=3, it is 77.9%; n=5, 74.3%; asymptotic 69.3%. EDF with implicit deadlines has a 100% bound, but it adds jitter and implementation complexity. Use RM when tasks are periodic and priorities are fixed; use EDF when utilization is high and you can tolerate jitter. If tasks are aperiodic, use a polling or deferrable server.

Worked trace (hypothetical): three tasks A, B, C each WCET 2 ms, period 10 ms. An ISR takes 5 ms at t=0. Average utilization over 100 ms: ISR 5% + tasks 60% = 65%, below 69.3%. But C misses its deadline.

Time (ms)RunningC's remaining time to deadline
0-5ISR10 - 5 = 5
5-7A5 - 2 = 3
7-9B3 - 2 = 1
9-11C1 - 2 = -1 (miss)

C's response time is 11 ms > 10 ms deadline. The average hid the phasing.

Validation: measure slack with a 1 kHz sampling window (1 ms) or event tracing. Run overload tests with realistic phasing: release all tasks simultaneously, add ISR bursts, and vary jitter. Check that no task misses its deadline.

Failure modes and detection:

  • Idle metric excludes ISR: measured utilization underreports. Detect by toggling a GPIO in the ISR and measuring with a scope. Cost: 5-10% unaccounted CPU can push a 65% system over the bound.
  • Short sampling: a 1 s average hides 10 ms bursts. Detect with 1 kHz sampling or event tracing. Cost: missed deadline.
  • Background starvation: low-priority task never runs. Detect with a watchdog or progress counter. Cost: lost telemetry.
  • Thermal throttling: CPU frequency drops, utilization rises. Detect with on-die temp sensor. Cost: missed deadlines.
  • Logging disabled in test: test does not reproduce production load. Detect by enabling logging in a canary. Cost: 2-5% overhead.

What would change the decision: if measured slack is consistently >20% and overload tests pass with 2x phasing jitter, ship. If not, re-partition tasks or move to EDF.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do Earliest Deadline First (EDF) and Rate Monotonic Scheduling (RMS) compare in their theoretical utilization limits, runtime scheduler overhead, and behavior under transient overload?

Answer

Rate Monotonic Scheduling (RMS) assigns fixed priorities inversely proportional to task period lengths ($T_i$). Earliest Deadline First (EDF) assigns dynamic priorities based on the closest absolute deadline ($d_i = t_{\text{release}} + D_i$).

1. Utilization Bounds

For $n$ periodic, independent, preemptible tasks with implicit deadlines ($D_i = T_i$) and execution times $C_i$:

  • RMS Utilization Bound (Liu & Layland): $$U = \sum_{i=1}^n \frac{C_i}{T_i} \le n(2^{1/n} - 1)$$ For $n=1$, $U = 1.0$ (100%). For $n=2$, $U \approx 0.828$ (82.8%). As $n \to \infty$, the guaranteed schedulability bound approaches $\ln(2) \approx 0.693$ (69.3%). If total utilization falls below this threshold, the task set is guaranteed schedulable. A task set with utilization between 69.3% and 100% may still be schedulable under RMS, but exact response-time analysis (RTA) is required.
  • EDF Utilization Bound: $$U = \sum_{i=1}^n \frac{C_i}{T_i} \le 1.0$$ EDF is optimal on a single uniprocessor: if any preemptive schedule exists where all deadlines are met, EDF will meet them up to 100% utilization without requiring harmonic task periods.

2. Runtime Overhead and Data Structures

Mainstream small-footprint real-time operating systems (FreeRTOS, CMSIS-RTOS2/RTX5, and default Zephyr) implement static-priority preemptive scheduling matching RMS principles rather than native dynamic EDF:

  • RMS Queue Operations: Because priorities do not change at runtime, ready queues can be structured as an array of doubly linked lists indexed directly by task priority, paired with a ready-group bitmask. Selecting the next task to run executes in $O(1)$ time using hardware single-cycle Count Leading Zeros (__CLZ on ARM Cortex-M). Inserting a task upon timer tick or unblock also takes $O(1)$.
  • EDF Queue Operations: Deadlines change with each instance release. The ready queue must be sorted by absolute deadline (e.g., via a min-heap or balanced red-black tree as supported in Zephyr's multi-queue choices). Ready insertion or re-keying takes $O(\log n)$ or $O(n)$ in simpler linked lists, increasing kernel ISR latency and scheduler overhead per dispatch.

3. Behavior Under Transient Overload

  • RMS (Predictable Failure): When total utilization exceeds schedulability ($U > 1.0$), task failure is strictly isolated. Lower-priority tasks (longer periods) miss deadlines or starve, while higher-priority tasks (shorter periods) execute deterministically with bounded jitter and zero deadline misses. This allows engineers to place mission-critical control loops at high priority and deferrable I/O at low priority.
  • EDF (Domino Effect): Under overload, tasks approaching an already expired or tight deadline retain the highest priority. A late task can consume the CPU trying to finish overdue work, starving subsequent tasks and precipitating a cascade of consecutive deadline misses across unrelated tasks (the domino effect). Mitigating this requires active runtime deadline policing or execution-time budgets.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Design and validate RTOS behavior for response-time budget.

Answer

What I'd say in the first two minutes

Assume a single-core Cortex-M7 at 200 MHz, fixed-priority preemptive scheduling, rate-monotonic priority assignment, deadlines equal to periods, and one shared mutex. The budget question is not "is utilization under 70%?": it is "does the worst-case response time of every task, including blocking and interference, fit inside its deadline?" Utilization is necessary, not sufficient. I'd answer with response-time analysis first, then validate the numbers it can't see: DMA, cache, ISR bursts, and instrumentation.

The mechanism

For task i, worst-case response time is

R_i = C_i + B_i + Σ_{j ∈ hp(i)} ceil(R_i / T_j) · C_j

solved by fixed-point iteration from R_i = C_i + B_i. C_i is worst-case execution, B_i is the longest time a lower-priority task can hold a mutex i needs, and the sum is higher-priority interference. B_i is bounded by priority inheritance (FreeRTOS xSemaphoreCreateMutex, Zephyr k_mutex), not by the holder's whole critical section.

Worked check (hypothetical figures, 200 MHz Cortex-M7)

taskT = DC
Sensor ISR1 ms2 µs
Control5 ms300 µs
Logger20 ms1.5 ms
Comms50 ms4 ms

Comms, lowest priority, B = 0:

  • R₀ = 4000
  • R₁ = 4000 + ceil(4000/1000)·2 + ceil(4000/5000)·300 + ceil(4000/20000)·1500 = 4000 + 8 + 300 + 1500 = 5808
  • R₂ = 4000 + ceil(5808/1000)·2 + ceil(5808/5000)·300 + 1500 = 4000 + 12 + 600 + 1500 = 6112
  • R₃ = 4000 + 14 + 600 + 1500 = 6114
  • R₄ = 6114: converged. 6.1 ms against a 50 ms deadline.

Add B = 250 µs for a shared mutex and R = 6364 µs. Still inside. The margin is what you spend on the effects below.

What RTA misses, and how to catch it

  • DMA contention. A DMA burst steals AHB cycles, so C_i inflates. Measure the task with DMA idle and active, comparing DWT->CYCCNT deltas; budget the active figure.
  • Cache cold. On Cortex-M7 a D-cache miss costs a 32-byte line fill. First iteration after a context switch or a DMA invalidate is slower than steady state. Measure both; if the gap is large, pin hot data in TCM.
  • ISR burst. Several interrupts in one tick window. Log ISR entry timestamps and take the max count inside any R window, not the average.
  • Instrumentation. SWO/ITM printf is not free and can dominate a short task. Measure with it on and off; budget the on case if it ships.
  • Unbounded blocking. A low-priority holder preempted by a medium task. Detect by timing max mutex hold with CYCCNT or a Percepio/SystemView trace. Cost is one missed deadline per inversion.

Trade-offs

RTA is conservative and cheap; measurement is accurate but only for paths you exercised. Do both: RTA to size the budget, measurement to catch what it can't see. EDF has a 100% utilization bound versus ln 2 ≈ 69% for RM, but is harder on a small RTOS and degrades badly under overload. Priority ceiling bounds blocking to one critical section and is cheaper than inheritance, but requires knowing every lock up front.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you compute the worst-case response time of a fixed-priority preemptive task set using response-time analysis, including the blocking term from priority inheritance or priority ceiling protocols, and how does the critical instant theorem justify the analysis?

Answer

Assume a uniprocessor, fixed-priority preemptive scheduler, periodic or sporadic tasks with relative deadline D_i ≤ T_i, independent except for resources guarded by a blocking protocol, no self-suspension. Then for task i:

R_i = C_i + B_i + Σ_{j∈hp(i)} ⌈R_i / T_j⌉ · C_j

solved by fixed-point iteration starting at R_i⁰ = C_i + B_i, stopping when R_i^(k+1) = R_i^(k) (schedulable if ≤ D_i) or when it exceeds D_i (not schedulable). The ceiling term is interference: each higher-priority task releases ⌈R_i/T_j⌉ times inside the window and each release costs its full C_j, because preemption can land at the worst moment.

The critical instant theorem (Liu & Layland, 1973) is what makes this a bound rather than a guess. For fixed-priority preemptive scheduling, a task's response time is maximised when it is released simultaneously with all higher-priority tasks, the synchronous release phasor, and, once blocking exists, when a lower-priority task has just entered a critical section on a resource they share. Every other phasor produces less interference, so checking the critical instant checks the worst case. That is why the analysis is a handful of iterations per task instead of a search over release offsets.

B_i depends on the protocol. Under the Priority Ceiling Protocol (or the immediate-ceiling / priority-protect variant, which is what FreeRTOS mutexes and CMSIS-RTX's priority-inheritance option give you), a task is blocked at most once per request: B_i = max over lower-priority critical sections that can block i. Under basic Priority Inheritance Protocol a task can be blocked once per conflicting critical section, so B_i is the sum of up to min(n_i, m_i) section lengths: much larger, and the reason PCP is preferred for hard real time.

Worked example, all D = T:

taskCT = DB
τ1150
τ22102
τ34200

τ2: R = 2+2+⌈R/5⌉·1 → 5 → 5. R₂ = 5 ≤ 10. τ3: R = 4+0+⌈R/5⌉·1+⌈R/10⌉·2 → 7 → 8 → 8. R₃ = 8 ≤ 20.

Utilization is 0.2+0.2+0.2 = 0.6, under the n=3 rate-monotonic bound 3(2^(1/3)−1) ≈ 0.780, so both tests agree here. Now raise B₂ to 7 and leave C, T untouched: R = 9 → 11 → 12 → 12, which exceeds D₂ = 10. Utilization is still 0.6. That is the whole argument for RTA over a utilization bound: the bound cannot see blocking, and blocking is where a nominally idle CPU misses deadlines.

Failure modes worth naming. If D_i > T_i the single-job recurrence is wrong; you need the level-i busy period and must check every job in it (Tindell et al.). Release jitter adds J_j to each interfering term. Non-preemptive regions and long ISRs add to B_i as the longest lower-priority non-preemptive stretch. Self-suspending tasks break the critical instant assumption outright. And C_i is an input, not an output: measure it with a GPIO toggle plus logic analyzer on the real binary, or take it from static WCET analysis, and re-run RTA when the toolchain or optimisation level changes. Detect a violation at runtime with a deadline-miss counter per task and a high-water mark on response time, not by trusting the offline number forever.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate RTOS behavior for priority inversion.

Answer

Assumptions: single-core Cortex-M, fixed-priority preemptive RTOS, mutexes for shared resources. The design decision is to use priority inheritance (PI) for every mutex that a lower-priority task can hold while a higher-priority task waits on it. If the RTOS supports priority ceiling and you have nested locks, use immediate ceiling priority protocol (ICPP) instead. Validate by measuring worst-case blocking time with a GPIO or cycle counter, and test with PI disabled to confirm the difference.

Priority inversion happens when H (prio 5) blocks on a mutex held by L (prio 1), and M (prio 3) becomes ready and preempts L. H waits for M's entire run. With PI, L inherits 5, so M cannot preempt. With ICPP, L runs at the ceiling priority (max priority of any task that can lock the mutex), so M cannot preempt either. FreeRTOS does not implement priority ceiling; POSIX exposes it as pthread_mutexattr_setprotocol(PTHREAD_PRIO_PROTECT) with pthread_mutexattr_setprioceiling().

Trade-offs: PI is simpler, no ceiling assignment, but nested locks cause chained blocking: H waits for L1's critical section plus L2's critical section. PI also does not prevent deadlock. Ceiling gives bounded blocking: a task can be blocked at most once by a lower-priority task, and it prevents deadlock. But ceiling can cause unnecessary blocking: a medium-priority task can be blocked by a low-priority task holding a resource with a high ceiling. Ceiling also requires static analysis to assign ceilings.

Hypothetical trace: L prio 1, M prio 3, H prio 5. L locks mutex at t=0, critical section 200 µs. H released at t=50 µs, blocks. M released at t=60 µs.

| t (µs) | event | no PI | with PI | | 0 | L locks, enters CS (200 µs) | L runs | L runs | | 50 | H released, tries lock | H blocked | H blocked; L inherits 5 | | 60 | M released | M preempts L | M ready, cannot preempt L (prio 5) | | 200 | L exits CS, unlocks | L still preempted | L unlocks; H acquires | | 5060 | M finishes | L resumes | — | | 5260 | L exits CS, unlocks | H acquires | — |

No PI: H waits 5260 - 50 = 5210 µs. With PI: H waits 200 - 50 = 150 µs. 34x reduction. The theoretical bound with PI is the longest critical section of any lower-priority task that can hold a mutex H needs; with nested locks, it's the sum along the chain. With ICPP, it's the longest critical section of any lower-priority task.

Validation: FreeRTOS, configUSE_MUTEXES=1. Create mutex with xSemaphoreCreateMutex(). Toggle GPIO in L's critical section and around H's lock. Measure with a scope. Run with xSemaphoreCreateBinary() (no PI) to see the difference. On Cortex-M, use DWT->CYCCNT for cycle-accurate timing.

C
SemaphoreHandle_t m = xSemaphoreCreateMutex(); // PI enabled
void L(void *p) {
  for (;;) {
    xSemaphoreTake(m, portMAX_DELAY);
    GPIO_L_HIGH();
    busy_wait_us(200);
    GPIO_L_LOW();
    xSemaphoreGive(m);
    vTaskDelay(pdMS_TO_TICKS(10));
  }
}
void H(void *p) {
  for (;;) {
    vTaskDelay(pdMS_TO_TICKS(100));
    GPIO_H_REQ_HIGH();
    xSemaphoreTake(m, portMAX_DELAY);
    GPIO_H_REQ_LOW();
    xSemaphoreGive(m);
  }
}

Failure modes:

  • Hidden library lock: printf() or malloc() takes an internal mutex without PI. Detection: measure H's wait when calling the library. Mitigation: avoid library calls in critical sections, or use a PI mutex wrapper.
  • Nested locks: H blocks on A held by L1, L1 blocks on B held by L2. H waits for L2's CS. Detection: trace shows H blocked on multiple mutexes. Mitigation: ICPP or lock ordering.
  • Low owner blocks: L holds mutex and blocks on I2C read inside CS. H waits for I/O. Detection: trace shows long CS. Mitigation: move I/O outside lock.
  • Unbounded cleanup: L holds mutex and does a long free loop. Detection: measure CS length. Mitigation: bound cleanup or move out.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and validate RTOS behavior for mutex ownership.

Answer

First 90 seconds. Assume a preemptive priority-based RTOS on one core: FreeRTOS V10.5.1 or Zephyr 3.x, and settle two things before designing: which resources an ISR touches, and the longest hold time. Anything an ISR touches does not get a mutex; mutexes are task-to-task exclusion only. The design is one mutex per resource, taken with a bounded timeout, never held across a blocking call, and every take/give wrapped so ownership is asserted rather than assumed. Validation is that wrapper, a three-task inversion test, and a hold-time histogram.

What ownership buys. xSemaphoreCreateMutex() gives a queue of length 1 with uxQueueType == queueQUEUE_IS_MUTEX. On take the kernel stores pxMutexHolder = pxCurrentTCB; if a higher-priority task is already waiting, xTaskPriorityInherit() raises the holder's priority to the waiter's while uxBasePriority keeps the original. On give, prvCopyDataToQueue() calls xTaskPriorityDisinherit( pxQueue->pxMutexHolder ) (the stored holder, not the caller) and then xQueueGenericSend() sets pxMutexHolder to the task that gave it. That second step is where a non-owner give does its damage. Zephyr's k_mutex is the same shape with an explicit check: k_mutex_unlock() returns -EPERM when the caller isn't the owner, and k_mutex_lock() returns 0 immediately for a thread that already owns it, incrementing lock_count. Zephyr mutexes are recursive by default, while FreeRTOS needs configUSE_RECURSIVE_MUTEXES=1 and the ...Recursive API.

Artefact 1: a wrapper that makes ownership checkable.

C
/* FreeRTOS V10.5.1, configUSE_MUTEXES=1, configASSERT() defined */
static SemaphoreHandle_t g_lock;
static TaskHandle_t      g_owner;

void lock_acquire(void)
{
    configASSERT(!xPortIsInsideInterrupt());          /* ARM Cortex-M port macro */
    configASSERT(xSemaphoreTake(g_lock, pdMS_TO_TICKS(50)) == pdTRUE);
    configASSERT(g_owner == NULL);
    g_owner = xTaskGetCurrentTaskHandle();
}

void lock_release(void)
{
    configASSERT(g_owner == xTaskGetCurrentTaskHandle());
    g_owner = NULL;
    xSemaphoreGive(g_lock);
}

xPortIsInsideInterrupt() ships with the ARM Cortex-M ports; other ports have an equivalent. The 50 ms timeout is deliberate: an unbounded take turns a bug into a hang.

Artefact 2: a non-owner give, step by step. L (prio 1), M (prio 2), H (prio 3); configASSERT undefined, as in a release build.

  1. L takes the mutex. pxMutexHolder = L, L->uxMutexesHeld = 1.
  2. H takes it and blocks. xTaskPriorityInherit(L) sets L->uxPriority = 3; L->uxBasePriority stays 1.
  3. B (prio 2) calls the raw xSemaphoreGive(): a bug. prvCopyDataToQueue() runs xTaskPriorityDisinherit(L): L->uxMutexesHeld drops to 0 and L's priority is correctly restored to 1. Then xQueueGenericSend() sets pxMutexHolder = B and B->uxMutexesHeld = 1. H is pulled off the wait queue and preempts B once the give returns.
  4. H resumes inside xQueueSemaphoreTake() and sets pxMutexHolder = H.

End state: H holds the mutex, L's priority is right, and L still believes it holds the mutex. Its lock_acquire() returned and nothing released it. When L later calls lock_release(), the kernel disinherits H (a no-op, H has no inherited priority) and hands ownership back to L. Now L and H are both inside the critical section. The real failure is silent ownership transfer, not a stuck priority.

Detection: with configASSERT defined, xTaskPriorityDisinherit()'s own configASSERT( pxTCB == pxCurrentTCB ) fires at step 3. If B had gone through the wrapper instead, the wrapper's owner check fires. In a release build with raw API calls, the residual symptom is two tasks in the critical section: catch it with a canary counter incremented on entry and asserted == 1.

Artefact 3: failure modes, detection, cost.

failuremechanismdetectioncost
non-owner giveholder silently transfers; two tasks enter the critical sectionkernel assert at disinherit, or wrapper owner checkmutual exclusion lost, silently
give from ISRxQueueGiveFromISR never runs the disinherit or updates pxMutexHolderwrapper's xPortIsInsideInterrupt() assertholder left stale; waiters block to timeout
owner deleted holdingFreeRTOS has no owner-death cleanupwatchdog polls xSemaphoreGetMutexHolder() against eTaskGetState()permanent deadlock for every waiter
recursive mismatchuxRecursiveCallCount off by oneassert the count is 0 before deleteone extra give releases early; one short never releases
hold across blocking I/Oholder is blocked, so inheritance can't helptimestamp take/give, histogram p99 holdevery waiter inherits the full I/O latency

The inversion test, with numbers. L (prio 1), M (prio 2), H (prio 3). L holds the mutex for 50 ms of CPU; M becomes ready and runs 30 ms. Without inheritance H waits ~80 ms; with it, L runs at prio 3, M can't preempt, and H waits ~50 ms. Run it with inheritance on and off and assert the delta: that is the validation, not the design review.

When a mutex is the wrong tool. Shared with an ISR: use a critical section or a semaphore, since mutexes can't be given from an ISR. Single-producer handoff: a task notification is cheaper. FreeRTOS's task-notification documentation reports a 45% faster unblock than a binary semaphore, with no queue object allocated. Known, bounded contention: a priority ceiling (Zephyr CONFIG_PRIORITY_CEILING, POSIX PTHREAD_PRIO_PROTECT) caps inversion at one critical section instead of a chain. And if the hold spans a flash erase or a UART write, restructure: no locking discipline fixes a lock held across blocking I/O.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and validate RTOS behavior for deadlock.

Answer

Assumptions. Preemptive fixed-priority RTOS (FreeRTOS 10.x, configUSE_MUTEXES=1), mutexes with priority inheritance, ISRs never block. "Deadlock" means two or more tasks each holding a mutex the other needs: a circular wait no scheduler policy can break.

Core answer. Priority inheritance is not deadlock prevention; it only bounds how long a high-priority task waits on a lower-priority holder. Deadlock is designed out, not scheduled out: impose a global lock order so the wait-for graph stays acyclic, never call code that can take a lock while holding one, and make every acquisition bounded so a mistake degrades to a timeout instead of a hang. Then validate with a harness that forces the AB/BA interleaving and a runtime check that fires on timeout.

Mechanism. Deadlock needs all four Coffman conditions: mutual exclusion, hold-and-wait, no preemption, circular wait. Mutexes supply the first three by definition. Lock ordering removes the fourth, if every task takes A before B, no cycle can form.

Trace: H (prio 5) takes A then B; L (prio 2) takes B then A. H takes A. L takes B. H blocks on B (held by L). L blocks on A (held by H). Circular wait. Priority inheritance raises L to prio 5, but L is still blocked on A, so both hang. Give each take a 50 ms timeout: H's xSemaphoreTake(B, pdMS_TO_TICKS(50)) returns pdFALSE after 50 ms, xSemaphoreGetMutexHolder(B) names L, and you log and unwind. The hang becomes a diagnosable event.

C
/* FreeRTOS 10.5, configUSE_MUTEXES=1 */
SemaphoreHandle_t A = xSemaphoreCreateMutex();
SemaphoreHandle_t B = xSemaphoreCreateMutex();

/* Both tasks use the same order: A then B. */
bool take_pair(TickType_t t) {
    if (xSemaphoreTake(A, t) != pdTRUE) return false;
    if (xSemaphoreTake(B, t) != pdTRUE) {
        xSemaphoreGive(A);          /* release on the error path */
        return false;
    }
    return true;
}

The xSemaphoreGive(A) on the failure path is the point: an error path that returns while holding A is the leak that turns a timeout into a permanent deadlock.

approachmechanismcostwhen wrong
lock orderingacyclic wait-for graphdiscipline, reviewdynamic lock sets you cannot order
priority ceiling (POSIX PTHREAD_PRIO_PROTECT)task runs at ceiling while holding; blocks lower-priority acquirerspriority inflation, static ceilingsceilings unknown at design time
try-lock + backoffnon-blocking acquire, release all, retrylivelock risk, wasted CPUhard real-time deadlines
single lock / message passingno nested lockscoarse contentionhigh-throughput paths

Validation. (1) A test that starts H and L in the AB/BA order and asserts the timeout fires within 50 ms. (2) A lock-order checker (static, or a runtime wrapper recording acquisition order per task) that flags any inversion. (3) A watchdog task that pings mutex holders.

Failure modes and detection.

  • AB/BA inversion: lock-order checker at build time, or the 50 ms timeout at runtime.
  • Recursive callback: a task re-takes a non-recursive mutex it already holds, self-deadlocking. FreeRTOS non-recursive mutexes do not detect this; use xSemaphoreCreateRecursiveMutex, or assert xSemaphoreGetMutexHolder(m) != xTaskGetCurrentTaskHandle().
  • Error-path leak: return while holding. Caught by the give-on-failure pattern and a held-mutex assert at task exit.
  • Cancellation: vTaskDelete on a task holding a mutex does not release it; the mutex is orphaned. Detect with a watchdog on holder liveness.
  • Owner fault: holder crashes or is starved. Watchdog timeout, then reset the mutex.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate RTOS behavior for semaphores.

Answer

What I'd say first. A semaphore in an RTOS is a counter with a blocking wait, not a lock. So design means choosing four things and one rule: the maximum count, the initial count, what happens when a give would exceed the maximum, and which side, task or ISR, is allowed to give and take. Validate means proving the count never drifts and that saturation is detected rather than silent. If you need ownership, priority inheritance or recursion, you want a mutex, not a semaphore.

Mechanism. A counting semaphore holds an integer in 0..max. Give increments it if it is below max; if it is already at max the give fails and the count is unchanged. Take decrements it if it is above zero, otherwise the caller blocks until a give or the timeout expires. That is why counting semaphores count events and binary semaphores coalesce them: a binary semaphore is a counting semaphore with max = 1, so a second give while the count is 1 is discarded and two events wake the consumer once.

FreeRTOS: xSemaphoreCreateCounting(uxMaxCount, uxInitialCount) (needs configUSE_COUNTING_SEMAPHORES = 1), xSemaphoreGiveFromISR(sem, &woken) in the ISR, xSemaphoreTake(sem, ticks) in the task. xSemaphoreCreateBinary() starts empty: you must give it once before the first take. Zephyr: k_sem_init(&sem, initial, limit), k_sem_give() (ISR-safe), k_sem_take(&sem, K_FOREVER) (not ISR-safe).

C
/* FreeRTOS V10.5.x, configUSE_COUNTING_SEMAPHORES = 1 */
#define RX_DEPTH 8
static SemaphoreHandle_t rx_pending;
static volatile uint32_t rx_overrun;

void comms_init(void) {
    rx_pending = xSemaphoreCreateCounting(RX_DEPTH, 0); /* max 8, initially 0 */
    configASSERT(rx_pending != NULL);
}

void DMA_IRQHandler(void) {
    BaseType_t woken = pdFALSE;
    clear_dma_flag();
    if (xSemaphoreGiveFromISR(rx_pending, &woken) != pdTRUE)
        rx_overrun++;              /* count already 8: frame dropped */
    portYIELD_FROM_ISR(woken);
}

void rx_task(void *arg) {
    for (;;) {
        if (xSemaphoreTake(rx_pending, pdMS_TO_TICKS(50)) == pdTRUE)
            process_frame();
        else
            rx_idle_timeouts++;
    }
}

Trace. Max 8, initial 0. The ISR fires 11 times before rx_task runs. Gives 1–8 succeed, count = 8. Gives 9, 10, 11 return pdFALSE, count stays 8, rx_overrun = 3. The task then takes 8 times, count = 0, and processes 8 frames. Three frames are gone, and the semaphore never told anyone except through the return value. That is the whole design question in one trace: the count is a hint, the payload lives in a ring buffer, and the semaphore does not protect it.

Trade-offs.

NeedUseDeciding property
counted events, N-deepcounting semaphoreaccumulates to max, then drops
one-shot signalbinary semaphorecoalesces; 2nd give lost
mutual exclusion, priority inheritancemutexownership, recursion, no ISR give
one producer → one consumer, cheapestdirect-to-task notificationFreeRTOS docs put unblocking ~45% faster than a semaphore
payload + countqueue / stream buffersemaphore carries no data

Failure modes and how you catch them.

  • Double give (ISR fires twice for one frame): count drifts up, consumer processes phantom frames. Catch: assert uxSemaphoreGetCount() <= RX_DEPTH in debug, and compare gives against a hardware frame counter.
  • Saturation ignored: gives return pdFALSE and vanish. Catch: check the return value, count drops, alarm on non-zero.
  • Binary semaphore where counting was needed: N events wake the consumer once. Catch: compare ISR event count to consumer wakeups.
  • Give from ISR without portYIELD_FROM_ISR: the woken task waits for the next tick. Up to one tick period (1 ms at 1000 Hz). Catch: toggle a GPIO in the ISR and in the task, measure on a scope.
  • Take from an ISR: not permitted; it can block and corrupt scheduler state. Catch: configASSERT on xPortIsInsideInterrupt() in the take path.
  • Count does not protect payload: the count says 8 pending but the ring buffer was overwritten. Catch: check head/tail indices against the count.

Validation. (1) Unit test the invariant: give max+1 times, assert count == max and the last give returned pdFALSE. (2) Reproduce the trace above on a host build or with a logic analyzer. (3) Stress: ISR at 1 kHz, consumer lower priority, run 10^6 events, assert given − dropped == processed. (4) Measure worst-case ISR-to-task latency with a GPIO toggle: on a 168 MHz Cortex-M4 a PendSV context switch is on the order of a few microseconds, but measure yours rather than assuming. (5) Watchdog the consumer so a stuck task shows up as a timeout counter, not a silent hang.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and validate RTOS behavior for message queues.

Answer

Core answer (first 90 seconds)

Assume FreeRTOS 11 on Cortex-M, a 1 kHz producer ISR, one consumer task, fixed-size struct payloads. Size the queue from the worst-case burst, not the average rate, and make the overflow policy explicit per producer class.

Depth = burst length − items the consumer drains during the burst, plus margin. Copy semantics matter: xQueueSend copies uxItemSize bytes inside a critical section, so item size is an interrupt-latency budget, not just memory. Keep items ≤ 16 bytes, or send an index into a preallocated pool.

Overflow: ISR producers use xQueueSendFromISR, which cannot block. On full it returns errQUEUE_FULL and the message is gone. Task producers choose: block with a timeout (backpressure) or drop. Never portMAX_DELAY from a task whose consumer is lower priority.

Mechanism

  • A FreeRTOS queue is a copy ring buffer. Send copies the item under taskENTER_CRITICAL, which suspends the scheduler and the tick. A 256-byte struct memcpy at ~4 bytes/cycle on a 100 MHz M4 is ~64 cycles ≈ 0.6 µs of added interrupt latency; a 16-byte item is ~0.04 µs. That is why item size is a latency decision.
  • Send unblocks the highest-priority task blocked in xQueueReceive, not the longest-waiting one. A queue is a priority-ordered wakeup, not FIFO across priorities: that is the starvation mechanism.
  • xQueueSendFromISR sets pxHigherPriorityTaskWoken; you must call portYIELD_FROM_ISR, or the woken consumer waits until the next tick.
  • Queues do not implement priority inheritance. If a high-priority consumer needs a lock a low-priority task holds, use xSemaphoreCreateMutex (configUSE_MUTEXES=1), which inherits; a binary semaphore does not.

Trade-offs

OptionWhen it winsCost
Bounded blocking queueTask producers, backpressure acceptableProducer stalls; inversion if consumer is lower priority
xQueueOverwrite (length-1)Latest-value telemetry, ISR producerOlder samples silently lost by design
Unbounded / heap-backedNever in a hard-real-time pathAllocation failure, unbounded latency
Pointer queue + poolItems > 32 bytesLifetime bugs; pool must be sized

Validation

Instrument, don't assume. FreeRTOS has no built-in queue high-water mark: sample uxQueueMessagesWaiting(q) at the consumer's top and track the max. Count errQUEUE_FULL returns per class.

C
/* FreeRTOS 11, Cortex-M. q_adc: depth 8, item = uint16_t. */
static volatile uint32_t adc_drops;

void ADC_IRQHandler(void) {
    BaseType_t woken = pdFALSE;
    uint16_t s = ADC->DR;
    if (xQueueSendFromISR(q_adc, &s, &woken) != pdPASS) {
        adc_drops++;              /* full: counted drop, not silent */
    }
    portYIELD_FROM_ISR(woken);
}

Trace: the IRQ reads a sample, xQueueSendFromISR copies 2 bytes into the ring under a short critical section. With space it returns pdPASS and sets woken = pdTRUE if a consumer was blocked; when full it returns errQUEUE_FULL and we increment adc_drops. portYIELD_FROM_ISR(woken) switches context only when woken is pdTRUE, so the consumer runs immediately instead of at the next tick.

Sizing arithmetic (hypothetical): producer 1 kHz = 1 item/ms; consumer worst case 1.5 ms/item = 0.67 items/ms. A 20 ms stall (flash write) delivers 20 items while the consumer drains ~13 → backlog 7. Depth 8 covers it; a 50 ms stall needs depth 20. Pick the stall you must survive, then add one.

Failure modes and detection

  • Silent full: ISR drops with errQUEUE_FULL and nobody counts it. Detect: per-class drop counter, assert nonzero in test.
  • Producer blocks unexpectedly: task producer on portMAX_DELAY behind a lower-priority consumer stalls indefinitely. Detect: watchdog on producer heartbeat.
  • Large copies in ISR: item size inflates the critical section and jitters the control loop. Detect: GPIO toggle at ISR entry/exit on a scope.
  • Stale pointer payload: pointer to a stack buffer that went out of scope. Detect: copy by value, or MPU/stack canary.
  • Priority starvation: the high-priority consumer always wins; the low-priority one never runs. Detect: configGENERATE_RUN_TIME_STATS per-task run time.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and validate RTOS behavior for thread flags.

Answer

Thread flags are one word of bits per object, not a queue. That single fact decides the design: bits coalesce, so a flag records "this condition is currently true", never "this happened N times". If the consumer must run once per event, flags are the wrong primitive: use a counting semaphore or a queue.

Assumptions I'd state up front: FreeRTOS event groups as the reference, configUSE_16_BIT_TICKS=0, so 24 usable bits (the top 8 of EventBits_t are kernel control). Producers are a mix of tasks and one ISR. One consumer per bit.

Design

Allocate bits by producer, not by event type, so ownership is unambiguous:

bitownermeaningcleared by
0ADC tasksample readyconsumer, clear-on-exit
1ISRfault latchedconsumer, clear-on-exit
2config taskreload doneconsumer, clear-on-exit

One writer per bit means no clear race. The consumer waits with xClearOnExit=pdTRUE so the clear is atomic with the wake: no window where a second producer's set is dropped between the wake and a separate xEventGroupClearBits call.

Mechanism

xEventGroupSetBits ORs the mask into the word and unblocks any waiter whose condition is now satisfied. xEventGroupWaitBits(eg, mask, xClearOnExit, xWaitForAllBits, ticks) blocks until (mask & eg) matches: any bit if xWaitForAllBits is pdFALSE, all bits if pdTRUE. With xClearOnExit=pdTRUE the matched bits are cleared before the call returns, and the returned EventBits_t is the value before the clear. That return value is your only record of what was set; if two producers set bit 0 before the consumer runs, the consumer sees bit 0 once and the return value is 0x01 both times.

Trace

Assumption: producer A runs at higher priority than the consumer.

C
EventBits_t b = xEventGroupWaitBits(eg, BIT0, pdTRUE, pdFALSE, pdMS_TO_TICKS(100));
  • t0: eg = 0x00. Consumer blocks on BIT0.
  • t1: A calls xEventGroupSetBits(eg, BIT0). eg = 0x01. Consumer is made ready but A keeps running.
  • t2: ISR calls xEventGroupSetBitsFromISR(eg, BIT0, &woken). This does not touch eg: it queues a command to the timer daemon task. eg is still 0x01.
  • t3: A blocks. Consumer runs, clears BIT0, returns 0x01. eg = 0x00.
  • t4: Timer daemon runs the queued command, sets BIT0. eg = 0x01. Consumer is not waiting.
  • t5: Consumer loops, calls wait again, returns 0x01 immediately, clears. eg = 0x00.

Two sets, two consumer iterations, but only because the ISR's set landed after the clear. Move t2 to t2.5 (before the consumer runs) and eg is 0x01 at t3: one iteration, one event lost. That window is the whole coalescing risk.

Validation

  • Lost multiplicity: count producer sets against consumer iterations. In the trace, if the ISR's set lands before t3, the counts diverge by one. Fix: queue the event, or keep a producer-side counter the consumer reads.
  • Clear race: two waiters on the same bit with xClearOnExit. One clears, the other blocks until timeout. Detect with a watchdog on the second waiter. Fix: one owner per bit, or xEventGroupSync for rendezvous.
  • Reserved bit: CMSIS-RTOS2 osEventFlags reserves bit 31 (osFlagsError = 0x80000000), leaving 31 usable; FreeRTOS leaves 24. Assert on the set return value.
  • Wrong recipient lifetime: deleting the event group while a task is blocked in xEventGroupWaitBits is undefined. Assert a waiter refcount is zero before vEventGroupDelete.
  • Unsupported ISR op: xEventGroupWaitBits from an ISR. configASSERT(xPortIsInsideInterrupt() == pdFALSE) in the wait path. Also xEventGroupSetBitsFromISR returns pdFAIL if the timer command queue is full (configTIMER_QUEUE_LENGTH), and the bits land late: an ISR that must not lose events needs a queue, not a flag.

Trade-offs

Flags are the right primitive for level conditions with multiple waiters. For single-recipient, high-rate signaling, FreeRTOS task notifications (xTaskNotifyGive / ulTaskNotifyTake) avoid the separate object and are cheaper. For multiplicity, a counting semaphore or a queue. Zephyr's k_event is the same model: 32 bits, k_event_post returns the previous mask, which is how you detect coalescing directly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate RTOS behavior for lost wakeups.

Answer

Core answer. A lost wakeup is a signal that arrives after the waiter has decided to block but before it actually blocks, so the waiter sleeps forever. The fix is not "add a flag": it is to make the signal carry state, so a signal that arrives early is still there when the waiter looks. Two shapes do that: a kernel object that stores the signal (queue, counting semaphore, task notification), or a predicate guarded by a mutex plus a condition variable, where the check and the block are atomic with respect to the signal. Then you validate by widening the race window and asserting the consumer still wakes.

Mechanism, with a trace. FreeRTOS queue of depth 1, xQueueCreate(1, sizeof(Event_t)):

C
/* ISR */
void sensor_isr(void) {
    BaseType_t woken = pdFALSE;
    Event_t e = { .seq = ++seq };
    xQueueSendFromISR(evt_q, &e, &woken);
    portYIELD_FROM_ISR(woken);
}

/* Consumer task */
void consumer(void *arg) {
    Event_t e;
    for (;;)
        if (xQueueReceive(evt_q, &e, portMAX_DELAY) == pdTRUE)
            handle(&e);
}

Trace the early-signal case: the ISR fires before the consumer ever calls xQueueReceive. xQueueSendFromISR copies e into the single slot, the queue count goes 0→1, and woken stays pdFALSE because no task was blocked. The consumer then calls xQueueReceive, finds count 1, copies out, returns pdTRUE immediately. No lost wakeup. If the ISR fires while the consumer is blocked, woken becomes pdTRUE and portYIELD_FROM_ISR unblocks it. Both orders work because the queue holds the state.

Contrast the broken version:

C
volatile bool ready = false;        /* WRONG */
void isr(void) { ready = true; }
void consumer(void) {
    if (!ready)                     /* check */
        vTaskDelay(portMAX_DELAY);  /* block — a signal here is lost */
}

If the ISR sets ready between the check and vTaskDelay, the consumer blocks forever: vTaskDelay carries no state.

Condition-variable variant. POSIX and Zephyr 2.7+ k_condvar pair a predicate with a mutex:

C
pthread_mutex_lock(&m);
while (!ready)
    pthread_cond_wait(&cv, &m);   /* atomically unlocks m and blocks */
pthread_mutex_unlock(&m);

The signaller holds m, sets ready, signals, unlocks. pthread_cond_wait releases the mutex and blocks as one atomic step, so the signal cannot slip between check and block. The while re-checks because of spurious wakeups and because another waiter may have consumed the signal.

Failure modes and how you catch them.

failuresymptomdetection
event before object existsxQueueSend on a NULL handle trips configASSERT, or the event is droppedcreate all IPC objects before the scheduler starts; assert handles non-NULL
signal coalescedtwo events, one slot; consumer handles one and misses the secondproduced vs consumed counter mismatch
stale predicateconsumer wakes and acts on already-consumed datasequence number in the event; consumer checks seq
timeout races signalwait times out as the signal lands; signal consumed or left pendingre-check the predicate after a timeout; count timeouts
reset leaves old statea stale signal wakes the new instancedrain the queue on reset, or use a generation counter

Validation. Widen the window deliberately: halt the consumer right after the predicate check (debugger breakpoint or a test hook), fire the ISR, then resume and assert it still wakes. Stress it: 10^6 signal/wait iterations with the ISR fired from a timer at random phases, asserting consumed == produced. In test builds replace portMAX_DELAY with pdMS_TO_TICKS(100) and assert the timeout path is never taken: a lost wakeup then shows up as a timeout instead of a hang. Trace with Percepio Tracealyzer or Zephyr's tracing: a lost wakeup appears as a task blocked with no matching unblock.

Trade-offs. A queue carries data and coalesces only when full; a binary semaphore is one bit of state with no payload; a task notification is the cheapest single-waiter signal: FreeRTOS documents it as up to 45% faster and lower RAM than a binary semaphore. Use a queue when you must carry data, a condvar when several waiters need broadcast, a notification when one task waits on one signal.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate RTOS behavior for ISR handoff.

Answer

Assumptions

Cortex-M4 at 168 MHz, FreeRTOS 11.x, configTICK_RATE_HZ = 1000, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY = 5. The ISR must return in a few microseconds; the real work takes a mutex and can block, so it cannot run in interrupt context.

Design

Two rules decide it. The ISR does only what cannot be deferred, read the register that clears the interrupt, then hands the event to a task through an ISR-safe, non-blocking primitive. Then it asks the scheduler to reschedule before returning, so the woken task runs on this exception return instead of at the next tick.

On Cortex-M the handoff is: the FromISR call unblocks the task and sets pxHigherPriorityTaskWoken; portYIELD_FROM_ISR pends PendSV; the exception return enters PendSV, which context-switches to the task.

C
/* FreeRTOS 11.x, Cortex-M4. NVIC priority 5 == configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY */
static QueueHandle_t evq;          /* 8 x uint32_t */
static TaskHandle_t  worker;

void EXTI0_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;
    uint32_t   ev    = read_event_reg();      /* clears the source */

    xQueueSendFromISR(evq, &ev, &woken);      /* ISR-safe, never blocks */
    portYIELD_FROM_ISR(woken);                /* PendSV if a higher-prio task woke */
}

void worker_task(void *arg)
{
    uint32_t ev;
    for (;;)
        if (xQueueReceive(evq, &ev, portMAX_DELAY) == pdPASS)
            handle(ev);                       /* mutexes, malloc, blocking: all legal here */
}

Trace: ISR entry → read_event_reg clears the source → xQueueSendFromISR copies ev into the queue and moves worker (higher priority than the interrupted task) to ready, setting woken = pdTRUE → portYIELD_FROM_ISR(pdTRUE) pends PendSV → exception return enters PendSV → switch → worker resumes inside xQueueReceive, which returns pdPASS with ev. If worker was already ready, woken stays pdFALSE, no PendSV, and the ISR returns to the interrupted task.

Trade-offs

handoffcost (168 MHz M4, typical)use when
xQueueSendFromISR~1 µs + queue RAM, copies the itemseveral event types, or you need buffering
vTaskNotifyGiveFromISR~0.3 µs, no extra RAM, one 32-bit valuea single wakeup, latency-critical
Zephyr k_msgq_put / k_sem_givesame shape; scheduler reschedules on ISR exitZephyr targets
Linux request_threaded_irqtop half + a real thread switch, tens of µsyou want full blocking APIs in the bottom half

Notification is the right default for "one event, wake one task"; a queue earns its RAM only when events arrive faster than the task drains them or you need several event types. On PREEMPT_RT, threaded IRQs give the same split with a heavier switch.

Failure modes and how you catch them

  • ISR above the syscall ceiling. An ISR at NVIC priority 3 calling xQueueSendFromISR is not masked by BASEPRI (0x50 here), so it can corrupt kernel state. configASSERT catches it in vPortValidateInterruptPriority; with asserts off you get a hard fault or a task that never wakes. Check the NVIC priority of every ISR that touches the kernel.
  • Blocking call in the ISR. xQueueSend instead of xQueueSendFromISR can suspend the scheduler from interrupt context. Grep every ISR for the FromISR suffix; if the priority is also wrong the assert fires, otherwise the symptom is a corrupted ready list.
  • Dropped wakeup. Forgetting to pass woken to portYIELD_FROM_ISR leaves the task unblocked but unscheduled until the next tick: up to 1 ms at 1000 Hz. Toggle a GPIO at ISR entry and at task entry and scope the delta: a bimodal distribution (fast path plus one tick) is this bug.
  • Discarded event. xQueueSendFromISR returns errQUEUE_FULL when the queue is full; ignoring the return value silently drops the event. Count non-pdPASS returns and alarm on them.
  • Hidden callback. A callback registered from the ISR that itself takes a mutex or blocks. Audit the call graph of anything invoked from interrupt context.

Validation

Static: assert at build time that every ISR calling a kernel API sits at priority ≥ 5. Dynamic: flood the ISR at its maximum rate, measure handoff latency with DWT->CYCCNT or a scope, and watch the drop counter. Trace with SystemView or Tracealyzer to confirm the ISR→task switch happens on the same exception return, not a tick later.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate RTOS behavior for software timers.

Answer

Assume FreeRTOS 10.x, configUSE_TIMERS=1, a single timer service task (the daemon task), and software timers used for periodic housekeeping (sensor polls, watchdog kicks, LED blink) not for hard real-time deadlines. If you need microsecond-accurate periodic events, use a hardware timer and an ISR.

The core design: every software timer callback runs in the timer service task, the same task that processes the timer command queue (xTimerStart, xTimerStop, xTimerReset and their FromISR variants). A callback that blocks stops every other timer and every start/stop command. So keep callbacks to a few register writes or a non-blocking queue send. For anything that can block (I2C, flash, a mutex) signal a worker task with xQueueSend(..., 0) or xTaskNotifyGive and return. Set configTIMER_TASK_PRIORITY explicitly: above the tasks that consume the timer signals, below your hard real-time control task. Size configTIMER_QUEUE_LENGTH for the worst-case burst of start/stop commands.

Trade-off: inline vs defer. Inline is fine when the callback is bounded and non-blocking: setting a flag, toggling a GPIO, sending to a queue with zero block time. Defer when the work can block, when it exceeds roughly 10% of the shortest timer period, or when the sum of all callback times approaches that period. The deciding numbers are worst-case callback duration, the shortest period, and the number of timers. Eight timers at 20 µs each on a 1 ms period is 160 µs of timer-task work per millisecond, 16% of one core, and any overrun delays the other seven.

Failure modes and how to catch them:

  • Callback blocks on a mutex held by a lower-priority task. Symptom: all timers drift together. Detect with a cycle-counter timestamp at callback entry and exit; assert if it exceeds budget. Use xSemaphoreCreateMutex (priority inheritance) and a timeout, never portMAX_DELAY.
  • Self-delete race: calling xTimerDelete from inside the timer's own callback with a non-zero block time deadlocks, because the delete command is queued behind the callback that is waiting for it. Delete from a worker task, or use block time 0 and accept the deferred free.
  • Command queue full: a burst of xTimerStartFromISR calls fills the queue; xTimerStart returns pdFAIL and the timer never starts. Check the return value and count failures; increase configTIMER_QUEUE_LENGTH or coalesce commands.
  • Drift and catch-up: FreeRTOS computes the next periodic expiry from the previous expiry, so a callback that overruns the period makes the next expiry fire immediately. A burst that starves lower-priority tasks. Measure jitter with a scope on a GPIO toggled in the callback.
  • Priority too low: the timer task is preempted by a logging or comms task, so callbacks arrive late. Raise configTIMER_TASK_PRIORITY, but not above the control loop.

Validation table:

Instrument it:

C
void vSensorTimerCallback(TimerHandle_t xTimer) {
    uint32_t t0 = DWT->CYCCNT;          /* DWT enabled */
    uint32_t evt = EVT_SENSOR_POLL;
    if (xQueueSend(work_q, &evt, 0) != pdPASS) {
        g_timer_drop_count++;           /* queue full: count, don't block */
    }
    uint32_t dt = DWT->CYCCNT - t0;
    if (dt > g_max_cb_cycles) g_max_cb_cycles = dt;
}

At 168 MHz, 1 µs is 168 cycles, so a 100 µs budget is 16,800 cycles. Run the burst test: start all timers from an ISR at once and check that none returns pdFAIL and that g_max_cb_cycles stays under budget.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate RTOS behavior for stack budgets.

Answer

Two things decide the number before I quote one: which core, and whether any task touches floating point. On Cortex-M the per-exception frame is 32 bytes without FP and 104 with it. I'll assume Cortex-M4F, FreeRTOS 10.5, arm-none-eabi-gcc 12.2 at -O2, tasks on PSP, handlers on MSP. The method: static analysis sets the budget, instrumentation on an adversarial path confirms it, an MPU guard catches what both miss. Configured capacity is not proof of fit.

Two stacks, not one. Thread mode runs on PSP, so the task stack carries the deepest call chain plus one hardware exception frame: 32 bytes for R0–R3, R12, LR, PC, xPSR, or 104 bytes when FPCA is set, because lazy stacking reserves the 17 FP registers plus alignment padding even though it defers the write. Handlers run on MSP, so nested ISRs stack their frames there. Size MSP for the deepest handler chain plus (n−1) exception frames.

Concrete budget. sensor_task gets 512 words = 2048 bytes. -fstack-usage writes a .su file with per-function frames: sensor_task 40, read_sample 56, iir_filter 72, snprintf (newlib-nano, no float) 168 → 336 bytes. Add the 104-byte FPU frame → 440 static. Then run the adversarial path (max sample rate, all filters on, logging on, interrupt burst) and read uxTaskGetStackHighWaterMark, which returns words, not bytes. It reports 380 words free = 1520 bytes, so 528 used. The 88-byte gap is spi_read, reached through a driver function pointer; -fstack-usage can't resolve that call graph and records only the caller's frame. Budget 528 × 1.3 = 686 → allocate 256 words (1024 bytes). MSP: three nested handlers at 96+64+48 = 208, plus two nested exception frames at 104 = 416 → 512 bytes in the linker script.

methodgives youblind tocost
-fstack-usage + -fcallgraph-infoper-function frames; flags recursion and dynamic (VLA/alloca) framesindirect calls, library internals, which path actually ranbuild flag only
uxTaskGetStackHighWaterMarkexact usage on paths you ranpaths you didn't; 0xa5 written as datascan cost; needs the adversarial workload
MPU guard region (FreeRTOS Cortex-M MPU port)fault at the instant of overflownothing, but needs a core with an MPUone MPU region per task, 8 total

Failure modes and how they surface:

Overflow past the stack base corrupts the neighbouring TCB. The MPU guard faults immediately: MemManage, CFSR.MSTKERR set, MMFAR names the address. configCHECK_FOR_STACK_OVERFLOW=2 only checks the last 20 bytes at each context switch, so it misses an overflow that recovers before the switch.

Watermark false reading. The fill byte is 0xa5; a local holding 0xa5 stops the scan early and under-reports free space: conservative. The dangerous direction is the other one: if the worst-case path never ran, the watermark reports headroom that isn't there. Run the adversarial path in CI, and treat any dynamic frame in the .su as unbounded.

printf. newlib's vfprintf with %f enabled has a frame over 1 KB on this toolchain; newlib-nano integer-only is 168 bytes. -Wstack-usage=512 fails the build when a frame crosses the line. Don't format in a tight-budget task: write to a ring buffer and format in a low-priority one.

Recursion. -fstack-usage reports one frame and the depth is unbounded; -fcallgraph-info flags the cycle, and MISRA C 2012 Rule 17.2 bans it outright.

Undersized MSP. The fault handler itself faults and the core locks up. Fill MSP with a pattern at startup and check it after a soak test.

On a Cortex-M0 there's no MPU and no FPU, so the guard and the 104-byte frame don't apply: static plus watermark is all you have.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How do you measure context switch latency and ISR response time using hardware instrumentation (GPIO and oscilloscope or logic analyzer) versus software trace tools, and what are the trade-offs of each?

Answer

Start with the definition, not the tool. "Context switch latency" means two different things that differ by an order of magnitude: (a) last instruction of the outgoing task to first instruction of the incoming task, or (b) the event that unblocks the incoming task (an ISR giving a semaphore) to the incoming task actually running. Say which one you are quoting. State assumptions too: MCU and clock, kernel version, whether code runs from zero-wait-state memory or flash with prefetch, and whether interrupts are masked across the interval.

Then the split: GPIO toggling gives you the interval, software trace gives you the cause. You need both.

ISR response time, hardware. Wire a timer output-compare pin (stimulus) to an EXTI input, and toggle a third pin as the first statement in the ISR.

Worked example: STM32F407 at 168 MHz, TIM2 CH1 → PA1 (EXTI1), ISR toggles PA2, scope at 1 GS/s with a 500 MHz probe, single-shot on the stimulus edge:

  • Measured PA1 edge → PA2 edge: 0.19 µs = 32 cycles at 168 MHz.
  • Documented floor: Cortex-M4 interrupt latency is 12 cycles from assertion to the first ISR instruction (ARM DDI 0439), zero-wait-state memory.
  • The other ~20 cycles: GPIO input synchronizer (up to 2 HCLK), EXTI edge detect, the compiler's ISR prologue before the C body, the BSRR store, and the pad's output delay.

Both edges carry the same pad delay, so it cancels in the difference: provided both pins are the same type and you use one probe. Note what you cannot measure: the earliest toggle is after the ISR prologue, so this is an upper bound on NVIC latency.

Context switch, hardware. Two equal-priority tasks, round-robin. A clears the pin then yields; B sets it at the top of its loop. The scope shows a square wave: fall-to-rise is one switch, rise-to-fall the other.

C
/* STM32F4 + FreeRTOS. PIN_MEASURE on GPIOB. */
void vTaskA(void *arg) {
    for (;;) {
        GPIOB->BSRR = (1U << (PIN_MEASURE + 16));  /* clear */
        __asm volatile("" ::: "memory");           /* keep the store before the yield */
        taskYIELD();
    }
}
void vTaskB(void *arg) {
    for (;;) {
        GPIOB->BSRR = (1U << PIN_MEASURE);         /* set */
        __asm volatile("" ::: "memory");
        taskYIELD();
    }
}

On one such board the half-period reads 1.05 µs = 176 cycles. That interval holds the rest of A after the store (SVC, exception entry), PendSV (save r4–r11, pick the next task, restore), and B's resume up to the store. The store issues in 1–2 cycles; the pin transition follows the AHB write and cancels between edges.

Failure modes: drop the compiler barrier and the store sinks past taskYIELD(). You measure nothing. Add a third runnable task and you measure queueing delay, not a switch. And one capture is meaningless: run for hours in infinite persistence and read the maximum, because the worst case is rare.

Software trace. Hooks in traceTASK_SWITCHED_IN/OUT (FreeRTOS) or SEGGER_SYSVIEW_RecordEnterISR log task IDs plus DWT->CYCCNT into a RAM ring buffer, streamed over RTT/SWD. You get the whole timeline: who preempted whom, ISR nesting depth, stack high-water marks.

Costs: each event is a call, a CYCCNT load and a ring-buffer write. Tens of cycles on a zero-wait-state part, and you must measure it on your target rather than trust a number. A hook inside a critical section lengthens that section. If the RTT buffer fills, events are dropped, and the dropped one is usually the outlier you were hunting: watch the dropped-event counter. CYCCNT is 32-bit: at 168 MHz it wraps every 2^32/168e6 ≈ 25.6 s, so timestamp arithmetic must handle wrap.

Trade-offs

GPIO + scope / logic analyzerSoftware trace
OutputInterval onlyInterval + cause
ResolutionProbe and sample-rate limited (ns)1 core cycle (5.95 ns at 168 MHz)
PerturbationOne store per edgeTens of cycles per event; can widen critical sections
Worst-case huntInfinite persistence, deep-memory LARing buffer can drop the outlier
Pins1–4 dedicatedSWD/JTAG or UART
FilteringHardBy task ID, queue, error

Together. Trace first to find which switch is slow and why; then bracket that path with GPIO and read the absolute worst case on a scope. Never quote a trace number as latency without stating the hook overhead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How do you use RTOS trace hook macros (such as FreeRTOS traceTASK_SWITCHED_IN) or a hardware cycle counter to profile per-task execution time, measure CPU utilization, and detect deadline misses at runtime?

Answer

Start with the timebase, not the hook. A tick is far too coarse: at 1 kHz you get 1 ms granularity, so a 200 us task reads as either 0 or 1 ms. Use the Cortex-M DWT cycle counter (DWT->CYCCNT) or a free-running timer clocked at 10-100x the tick. Then charge elapsed cycles to the outgoing task inside traceTASK_SWITCHED_IN, and compare per-job completion against the deadline in a supervisor task.

State two assumptions up front: the counter is monotonic across the window you measure, and the hook is short enough not to change the schedule it measures. If either fails, the numbers are fiction.

FreeRTOS 11.x on Cortex-M4:

c /* FreeRTOSConfig.h. traceTASK_SWITCHED_IN() is called from vTaskSwitchContext() with pxCurrentTCB already pointing at the incoming task. */ extern uint32_t g_prev_cycles; extern TaskHandle_t g_prev; extern uint32_t g_task_cycles[ MAX_TASKS ];

#define traceTASK_SWITCHED_IN() do {
uint32_t now = DWT->CYCCNT;
if (g_prev) g_task_cycles[ idx(g_prev) ] += now - g_prev_cycles;
g_prev_cycles = now;
g_prev = pxCurrentTCB;
} while (0)

Enable DWT once at boot: CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;. The hook runs inside the scheduler's critical section, so it must not call any FreeRTOS API and must stay at a handful of instructions.

Utilization is then arithmetic. On a 168 MHz M4 a 1 s window is 168e6 cycles; if the control task accumulates 50.4e6, that is 30% CPU. Sum across tasks plus idle. If idle is not the largest bucket, you are near saturation.

Deadline misses: each periodic job stamps the counter at release and at completion, and misses when complete - release > deadline * core_hz. A low-priority supervisor reads the table every tick and latches the first miss per task, so the next job overwriting the counters does not erase the evidence.

approachresolutioncostblind spot
DWT + traceTASK_SWITCHED_IN1 cycle~10-20 cycles per switchISR time charged to the interrupted task
configGENERATE_RUN_TIME_STATS + vTaskGetRunTimeStats()10-100x tickone timeraggregate only, no per-job deadline
Zephyr CONFIG_THREAD_RUNTIME_STATS + k_thread_runtime_stats_get()timer-dependentbuilt insame ISR attribution
GPIO toggle + logic analyzernsone pin per eventonly a few events fit

Failure modes. 32-bit wrap: at 168 MHz CYCCNT wraps every 2^32/168e6 = 25.6 s, and unsigned delta arithmetic is only correct if you sample more often than that, which a task that never blocks will not. Hook overhead inflates what it measures; verify by toggling a GPIO around the hook and scoping it, and by diffing utilization against a build with the hook compiled out. ISR execution is charged to whatever task was interrupted, so a 50 us ISR at 1 kHz shows up as 5% on a random task; measure ISR time separately or subtract it. The macros are no-ops unless defined before FreeRTOS.h is included, so a release build with a different FreeRTOSConfig.h silently reports zeros. DWT->CYCCNT stops in deep sleep on most parts, so tickless idle under-reports.

When not to: if you only need aggregate utilization, the built-in run-time stats are less code and less risk. Reach for hooks when you need per-job deadline evidence tied to a specific release build.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate RTOS behavior for watchdogs.

Answer

Core answer.

One supervisor task owns the only feed line to a window watchdog. Every critical task publishes a monotonic progress counter, not a boolean, at its own cadence. The supervisor runs at, say, 20 Hz and checks that each counter advanced since the last pass. All advanced: feed. Any stale: don't feed, and let the hardware reset.

Why monotonic matters: a boolean "alive" flag set once at startup stays true after the task deadlocks. A counter that must advance inside a deadline can't be faked by a dead task.

Concrete shape: an STM32 WWDG clocked from PCLK1, 7-bit down counter, window register. Feed is legal only between the window opening and counter underflow. Kick too early and it resets, which catches a supervisor spinning too fast, something a plain IWDG would happily accept. If you need independence from the MCU clock, put an external window watchdog (MAX6369, TPS3813) on a GPIO.

Numbers to make it real: motor task 1 kHz, deadline 5 ms; comms task 100 Hz, deadline 50 ms; supervisor 20 Hz, 50 ms period; WWDG window set so a feed must land 30–50 ms after the previous one.

Alternatives, and when not to use this.

Three levels. First, a simple kick: feed in the main loop or idle hook. Catches total lockup only; one task deadlocked while the loop still runs is never seen. Cheapest, fine for single-loop firmware. Second, task supervision as above: catches per-task starvation, costs a supervisor task, per-task instrumentation, and a correct deadline per task. This is the default for multi-task safety-relevant firmware. Third, an external window watchdog: independent clock and power, survives MCU clock failure, can't be disabled by a firmware bug. Costs a part and a GPIO; use it when a stuck MCU is unacceptable.

When the token scheme isn't worth it: if a reset is worse than degraded operation, a device mid-procedure that must not reboot, don't wire the miss to reset, wire it to a degraded mode and log. And if you can't state a real deadline per task, the tokens are theatre.

Failure modes and how each is detected.

  • Supervisor starved: no feed lands in the window, hardware resets. Detection is the reset itself; confirm with a reset-cause register.
  • Token replay or stale: a task stops but its counter was cached. Detect by requiring the counter to advance and reading it fresh each pass.
  • Long valid operation: a flash erase blocks the task for ~200 ms and causes a false reset. Fix by letting the task declare a long-op window with its own longer deadline.
  • Debug pause: the core is halted under a debugger while the watchdog keeps counting. Freeze the watchdog on debug halt (STM32 DBGMCU freeze bits) or disable it in debug builds.
  • Reset loop: a persistent fault resets forever. Keep a reset counter in no-init RAM or a backup register; after N resets, enter safe mode.
  • Crash record lost: reset wipes RAM. Write last token state and reset cause to no-init RAM or backup registers before the reset.

Validation.

Fault-inject each path and measure. Suspend a task with vTaskSuspend and confirm a reset within one supervisor period plus the window, scoping the reset pin. Kick too early and confirm the window reset. Hold a task dead and count resets, confirming safe mode after N. Halt under the debugger and confirm no reset with freeze enabled. Run the 200 ms flash erase and confirm no false reset. Then sweep temperature and load and measure worst-case feed jitter against the window margin.

That is the design and the validation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate RTOS behavior for overload policy.

Answer

Assumptions. Fixed-priority preemptive RTOS (FreeRTOS, Zephyr, VxWorks), periodic tasks, and "overload" means offered utilization exceeds what the schedule can meet. If the system is EDF, overload behavior differs and I'll flag where.

Core answer. Overload policy is two decisions. Design: choose a priority assignment and a bounded admission rule for when demand exceeds capacity. Validate: inject a burst, prove the critical path still meets deadline, and prove recovery is monotonic. No scheduler makes unbounded demand schedulable: a fixed-priority schedule has a utilization ceiling, and past it the lowest-priority task misses first.

Mechanism. Rate-monotonic (RM) assigns priority by period and is guaranteed schedulable up to the Liu–Layland bound n(2^(1/n)−1): 0.828 for n=2, 0.780 for n=3, 0.757 for n=4, tending to 0.693. That bound is sufficient, not necessary: exceeding it does not prove a miss; response-time analysis (RTA) does. EDF has a 100% bound but is fragile in overload: one deadline miss cascades because the scheduler keeps running the task that already missed. RM degrades predictably: the lowest-priority task absorbs the overload and everything above it stays intact. That predictability is why safety-critical systems stay on RM.

Worked check. Four tasks: τ1 C=1/T=4, τ2 C=2/T=8, τ4 C=3/T=10, τ3 C=3/T=16. Utilization = 0.25+0.25+0.30+0.1875 = 0.9875, under 100% but above the n=4 bound of 0.757. RM priority order is τ1 > τ2 > τ4 > τ3, so τ3 is lowest. RTA for τ3: R = C3 + Σ ceil(R/Ti)·Ci over higher-priority tasks.

iterRτ1τ2τ4
03———
19123
213343
317446
420566
520566

R converges at 20 ms against a 16 ms deadline: τ3 misses by 4 ms. That is the overload, quantified before it ships.

Trade-offs. Admission control (reject τ4 at submit time) beats priority capping when the work is optional and you can tell the caller no. Priority capping, temporarily raising the overloaded task, beats admission control when the work is mandatory but bursty and you can borrow slack from lower-priority tasks. Load shedding beats both when the work is best-effort telemetry. Degradation (run the control loop at half rate) beats shedding when partial service is still useful. Decide by asking: is the work mandatory, and is partial service acceptable?

Failure modes and detection.

  • Safety work shed. Count drops per class; any safety-class drop is a fault, not a metric. Cost: safety function unavailable.
  • Starvation. A low-priority task never runs. Detect with a per-task heartbeat the task kicks; a watchdog on that heartbeat fires. Cost: silent loss of a subsystem.
  • Stale commands execute late. Timestamp each message and drop anything older than a bound (say 50 ms). Cost: an actuator acts on an old setpoint.
  • Log storm. Logging in the overload path adds work and can invert priority on the UART mutex. Detect by log-queue depth and drop count. Cost: the diagnostic worsens the overload.
  • Recovery oscillation. Shed, re-admit, shed again. Count admission transitions per minute. Cost: throughput thrashes instead of recovering.

Validation. Inject a burst on hardware-in-the-loop, hold it past the deadline, then release. Assert the critical path meets deadline throughout, drop counters increment only for non-safety classes, and admission transitions settle to zero within a bounded window. A 100 ms watchdog timeout and a queue depth of 8 are the kind of bounds you set and then prove.

C
// FreeRTOS: bounded admission, non-blocking, drop counted
if (xQueueSendToBack(cmd_q, &cmd, 0) != pdTRUE) {
    drops[cmd.cls]++;
    if (cmd.cls == CLS_SAFETY) enter_safe_state();  // never shed safety
}

That is the policy: a bound, a priority order, an exposed drop, and a recovery test that shows the system returns to steady state.

Curated: · Written: · Reviewed:

Difficulty: Hard