Skip to content
Tech Interview Prep
Technical interview guide

Real-Time Embedded Systems

Why robotics software has hard timing deadlines that general-purpose software doesn't, and how real-time systems guarantee them.

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

Scope: Current FreeRTOS, Zephyr, CMSIS-RTOS2, Arm Cortex-M, Linux real-time, Embedded Rust, SEI CERT C, IEC functional-safety, NIST firmware resiliency, and Renode references 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

Classify timing requirements for an embedded product.

Answer

Core answer. Classification is a property of the contract between an event and its physical consequence, not of the component that handles it. For each event I ask four things: what triggers it, what result it must produce, the deadline by which that result is useful, and what happens physically if it is late. Then:

  • Hard: a missed deadline is itself a failure. The result has no value after the deadline and the miss is a fault. Motor commutation, airbag firing, ABS pressure control.
  • Firm: the result is worthless after the deadline, but a bounded miss rate is acceptable. A dropped frame, a sensor sample re-derived next cycle.
  • Soft: the result still has value late, degraded. UI refresh, telemetry log.

The class decides the analysis and the verification method, which is why it cannot come from component names. Hard tasks need worst-case analysis (WCET, response-time analysis, a utilization bound) with no probabilistic argument. Firm tasks are specified as a deadline-miss ratio and can be measured statistically. Soft tasks are specified as a percentile latency.

EventArrivalDeadlineJitter budgetMiss toleranceClass
Motor current controlperiodic, 100 µs100 µs (same period)±5 µs0Hard
IMU fusionperiodic, 10 ms10 ms±200 µs1e-3Firm
Telemetry logperiodic, 1 s1 s±50 ms1e-2, stale 5 sSoft

Why the class changes the method. Three periodic tasks with C/T = 0.30, 0.30, 0.25 give U = 0.85. Rate-monotonic's utilization bound for n = 3 is 3(2^(1/3) − 1) ≈ 0.78, so RM gives no guarantee at U = 0.85; EDF's bound is 1.0, so EDF is still feasible. A hard classification forces you to pick the scheduler that matches the bound, not the other way round. Firm and soft tasks can be overbooked and their misses counted.

Budgeting. A 10 ms sensor-to-actuator path: sensing 1.0, bus 0.5, scheduling delay 0.5, compute 3.0, actuation 1.0 = 6.0 ms, leaving 4.0 ms margin. Jitter adds along the chain: end-to-end jitter is the sum of per-stage jitter, so a ±200 µs budget across five stages gives each stage roughly ±40 µs.

Failure modes and detection.

  • Priority inversion. A low-priority task holds a shared I2C mutex; the 1 ms motor task blocks, misses its deadline, current is not updated, overcurrent trips. Detect with a per-task deadline-overrun counter; fix with priority inheritance or a priority-ceiling protocol.
  • Overload. Arrival rate exceeds design. Hard tasks must still meet deadlines, so the overload response is to shed firm and soft work first. Detect with queue-depth and utilization monitors.
  • Jitter accumulation. Control-loop phase margin degrades once actuation jitter exceeds budget. Detect by timestamping at each stage and logging the end-to-end distribution.

When not to classify this way. Do not classify by safety integrity level. A hard real-time task can be low ASIL (a display refresh with a hard deadline) and a soft task can be high ASIL. ASIL drives the safety mechanism; the deadline contract drives the timing class. And calling something hard when you cannot defend a zero miss rate forces expensive WCET analysis for no benefit, if 1e-3 misses are tolerable, say so and measure it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Establish a defensible execution-time bound.

Answer

First, I'd clarify what 'defensible' means: the bound must be sound, no underestimation, and tight enough to be useful for scheduling. I'd assume a single-core embedded processor with caches, interrupts, and a real-time OS, and we need a WCET bound for a safety-critical task. The core answer: you can't just measure; you need either a sound static analysis or a measurement-based approach with a sound argument for coverage, often combined. I'd start with a static analysis tool like aiT or Bound-T, then validate with targeted measurements on the worst-case path, and add margin.

Why static analysis? It explores all feasible paths using abstract interpretation and ILP, so it's sound. But it needs a precise processor model (cache, pipeline, branch prediction) which is expensive to build and may be pessimistic. Measurement is cheaper but unsound: you only see the paths you execute. A hybrid approach uses static analysis to identify the worst-case path, then measures that path with hardware performance counters to get a tighter bound, and uses extreme value theory to estimate the tail.

Here's a comparison:

MethodSoundnessTypical pessimismEffortTool examples
Static analysisSound20-50% overestimateHigh (processor model)aiT, Bound-T, OTAWA
MeasurementUnsound2-3x underestimateLow (test runs)RapiTime, in-house
HybridSound with coverage argument10-20% overestimateMediumaiT + RapiTime

Failure modes: Cache warming can make a measured 'max' 3x below worst case if the cache is warm in all runs. Detection: run with cold caches, use cache-flush instructions, or compare with static analysis. Interrupts: if you measure with interrupts disabled, you miss interference. Detection: measure with interrupts enabled and account for ISR execution. Infeasible paths: static analysis may include paths that can't happen, overestimating by 2x. Detection: use infeasible path analysis or manual review. Stale measurements: after a code change, the bound is invalid. Detection: rerun analysis as part of CI.

When is a bound not worth establishing? If the task is not safety-critical and you can tolerate occasional deadline misses, you might use a probabilistic bound. But for DO-178C or ISO 26262, you need a sound bound.

A worked example: a task has a loop with a rare branch. Static analysis says 10ms. Measurement over 10,000 runs gives max 3ms because the branch never taken. That's a 3x under-cover. To fix, you'd force the branch and measure again, or use static analysis to prove the branch is feasible.

The decision criterion: if you can afford the tool and processor model, static analysis gives a defensible bound. If not, you need a measurement-based approach with a sound coverage argument, plus a margin: 20% is common but not a proof.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Use volatile correctly for a memory-mapped peripheral.

Answer

Start with the assumption I'd state out loud: the register is device memory, mapped non-cacheable, and the compiler is a conforming C compiler (C11 or later) free to optimize aggressively. Under those assumptions volatile is the right tool for exactly one job, forcing the access, and the wrong tool for three others.

What volatile buys you. A volatile-qualified lvalue means every access in the abstract machine is a side effect the compiler must perform, and volatile accesses are not reordered relative to each other. A redundant-looking read is not folded away, a write is not deleted, and two volatile accesses keep their source order.

Propertyvolatile gives it?
Every source access emittedyes
Volatile accesses kept in orderyes
Atomic read-modify-writeno
Ordering vs normal memoryno
CPU-level barrierno

Declaring the register. Fixed-width type, documented address:

C
#define UART_SR (*(volatile uint32_t *)0x40001000u)  /* status */
#define UART_DR (*(volatile uint32_t *)0x40001004u)  /* data   */

void uart_putc(char c) {
    while (UART_SR & (1u << 5)) { }   /* spin until TXE */
    UART_DR = (uint32_t)c;
}

uint32_t, not int, so the width matches the hardware. The pointer is volatile, so the pointee is volatile.

Trace. The loop body must re-read UART_SR every iteration. Illustrative shape of the generated code:

loop:
    ldr  r3, [r2]        ; r2 = 0x40001000, reloaded each pass
    tst  r3, #(1<<5)
    bne  loop
    str  r1, [r0]        ; r0 = 0x40001004

Drop the volatile and the compiler is entitled to hoist that ldr above the loop: one read, then either fall through or spin forever on a stale value. That's the classic hang, and you detect it by reading the disassembly: one load, not one per iteration.

Read-modify-write. UART_SR |= MASK is load, or, store: three accesses. If the device or another agent changes the register between load and store, you write back a stale value and lose the update. volatile does not fix this. Fixes: use a write-one-to-clear or set/clear alias register if the peripheral has one; otherwise guard the sequence with a critical section (disable interrupts, or a lock). Detection: read the register back, or watch it on a scope and see the lost bit.

Barriers. volatile orders volatile accesses against each other, not against normal memory. If you fill a DMA buffer and then ring a doorbell register, the doorbell store can be reordered ahead of the buffer writes. You need a release barrier before the doorbell (__DMB() on ARM, wmb() on Linux, asm volatile("" ::: "memory") for the compiler alone) and an acquire barrier after reading a status that implies data is ready. On x86 the CPU ordering is stronger, but the compiler barrier is still required.

When volatile is the wrong tool. Shared software state between threads or an ISR (a flag, a counter) is not a device register. volatile gives no atomicity, so counter++ still races. Use C11 atomics or a critical section. And volatile does nothing for DMA cache coherency; that's cache maintenance, not a qualifier.

Bitfields. Don't assume a C bitfield maps to a specific bit layout or access width; the ABI leaves it implementation-defined, and the compiler may RMW the whole word or split across words. Use explicit masks and shifts unless the ABI is pinned and you've checked the disassembly.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

How do you safely modify bits in a memory-mapped peripheral register that is written by both an ISR and a task?

Answer

The core problem is that a plain read-modify-write on a memory-mapped register is not atomic. Even with volatile, the compiler emits a load, a modify, and a store; an interrupt between the load and the store can cause the ISR's update to be lost when the task writes back its stale copy.

Assume a 32-bit register where the task sets bit 3 and the ISR sets bit 7. If the task reads 0x00000000, the ISR fires and sets bit 7 (register becomes 0x00000080), then the task ORs in bit 3 and writes 0x00000008, clearing bit 7. The ISR's update is lost.

steptaskISRregister
1load r = 0x000x00
2load r = 0x000x00
3set bit 7, store 0x800x80
4set bit 3, store 0x080x08 (bit 7 lost)

volatile only tells the compiler the value can change outside the program's control; it forces a load each time but does not make the load-modify-store atomic.

Remedies, in order of preference:

  1. Hardware set/clear registers: write 1 to set, write 1 to clear (e.g., STM32 GPIO BSRR). No read-modify-write, so no lost update.
  2. Bit-banding: on Cortex-M3/M4, the alias region maps each bit to a word; a single store sets or clears atomically. Not present on all cores (e.g., Cortex-M7 lacks it).
  3. Atomic aliases: some peripherals provide set/clear aliases that are safe from both contexts.
  4. Disable interrupts around the update: a critical section (taskENTER_CRITICAL/irq_lock). Must be short and bounded; measure worst-case interrupt latency impact.
  5. Shadow register with a single writer: one writer owns the register; the ISR posts a request via queue or flag, and the task performs the update. Or use separate registers for ISR-only bits.

In the field, the symptom is a bit that occasionally does not change or a counter that drifts. A readback check after write can log mismatches, but readback is also racy. Better: toggle a spare GPIO around the update and scope it, or use a hardware set/clear register that makes the bug impossible.

Testing: inject an interrupt at the exact point between load and store. On a Cortex-M, set a breakpoint in the ISR and step, or use a test harness that triggers the ISR via software. Run many iterations with random interrupt timing. Use a logic analyzer to observe the register write. In simulation (Renode), script the interleaving.

Prefer hardware set/clear or bit-banding; if not available, use a critical section with measured latency, or a shadow register with a single writer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How does Direct Memory Access (DMA) operate in embedded systems, and how do you handle cache coherency and memory barriers when sharing buffers between DMA and the CPU?

Answer

DMA hardware offloads bulk transfers between peripherals and memory across the system interconnect (such as an AHB/AXI crossbar). The DMA controller acts as an alternate bus master: once programmed with source, destination, transfer length, and burst size, it arbitrates with the CPU for memory bus cycles.

When a CPU features data caching (e.g., Cortex-M7 or Cortex-A), the primary failure mode is cache incoherency: the DMA engine operates directly on physical SRAM or external DRAM, bypassing the CPU L1/L2 caches. If the CPU and DMA access the same physical buffer without explicit synchronization, data corruption occurs in two directions:

  1. CPU Transmit (Memory to Peripheral): The CPU writes data, but changes remain dirty in the write-back D-cache. When DMA reads physical memory, it transmits stale data.
  2. CPU Receive (Peripheral to Memory): DMA writes new incoming data to physical memory. If the CPU reads the buffer while valid cached lines exist, it reads stale cache lines. Worse, if adjacent cache lines are marked dirty, a background cache eviction by the CPU will overwrite fresh DMA data in SRAM.

Handling Cache Coherency and Barriers

There are three distinct architectural strategies:

Strategy 1: Software Maintenance (Clean / Invalidate)
+-------------------+      Clean (Flush)      +-------------+
| CPU Cache (Dirty) | ----------------------> | Physical RAM |
+-------------------+                         +-------------+
                                                     ^
                                  DMA Read (TX) ---- |

Strategy 2: Hardware MPU Non-Cacheable Region
CPU Load/Store -----------------------------> | Non-cacheable RAM |
                                                     ^
                                  DMA R/W ----------- |
  1. Software Cache Maintenance Operations (CMSIS / Architecture Primitives):

    • For TX (CPU -> Device): Write the buffer -> Issue DSB (Data Synchronization Barrier) -> Clean cache lines (SCB_CleanDCache_by_Addr) -> Issue DSB -> Trigger DMA start.
    • For RX (Device -> CPU): Invalidate cache lines (SCB_InvalidateDCache_by_Addr) prior to transfer or immediately after DMA complete IRQ -> Issue DSB -> CPU reads buffer.
    • Critical constraint: Buffer addresses and sizes must align to the CPU cache line boundary (e.g., 32 bytes on Cortex-M7, 64 bytes on Cortex-A). If a DMA buffer shares a cache line with an unrelated CPU variable, an invalidation discards concurrent CPU writes, or an eviction clobbers incoming DMA data.
  2. Non-Cacheable Memory Regions (via MPU): Configure a dedicated SRAM pool (e.g., in the ARM MPU) with memory type Normal, Non-Cacheable, or Device memory. This eliminates software cache operations at the expense of CPU load/store access throughput.

  3. Hardware Coherent Interconnects (Cache Snooping / ACP): High-end cores route DMA transactions through an Accelerator Coherency Port (ACP) or hardware snoop unit that automatically invalidates or updates CPU L1/L2 tags.

Ordering and Memory Barriers

C
/* Example: Safe TX sequence with CMSIS-Core primitives */
uint8_t __attribute__((aligned(32))) tx_buf[128];

void start_dma_tx(void) {
    populate_payload(tx_buf, sizeof(tx_buf));

    // 1. Ensure all memory writes complete before cache clean
    __DSB();
    // 2. Clean dirty cache lines down to physical RAM
    SCB_CleanDCache_by_Addr((uint32_t *)tx_buf, sizeof(tx_buf));
    // 3. Ensure cache clean completes before enabling peripheral
    __DSB();

    DMA1_Stream0->NDTR = sizeof(tx_buf);
    DMA1_Stream0->CR |= DMA_SxCR_EN;
}

__DMB() ensures program memory access order, while __DSB() stalls CPU execution until memory transactions (and cache operations) complete on the bus before peripheral control registers trigger DMA.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Set and validate an interrupt-latency budget.

Answer

First, pin down what you are budgeting. Interrupt latency is the time from the peripheral asserting its request to the first instruction of the handler that actually services it executing, not to the handler being entered, and not to the work being done. State that, and state whether the core is running or waking from sleep, because those are different budgets by orders of magnitude.

Assume a Cortex-M4 at 168 MHz, code in flash with one wait state, no FPU context, and a motor current loop that needs the ADC sample latched within 5 µs of the timer compare match. The budget breaks down like this:

termworst casewhere the number comes from
timer → NVIC propagation~20 ns3 cycles at 168 MHz
exception entry (stack + vector fetch)71 ns12 cycles, ARM Cortex-M3/M4 TRM, zero-wait-state memory
longest interrupt-disabled section1.79 µs300 cycles, e.g. a 10-node list update
one higher-priority handler2.10 µs353 cycles
margin~1 µs
budget5 µs

The 71 ns entry is not where your budget goes. It goes to masking and to higher-priority handlers, and the reason is mechanical. Exception entry on Cortex-M3/M4 is 12 cycles: the core pushes eight registers and fetches the vector. Tail-chaining is 6 cycles, when a second interrupt is already pending as the first returns, the core skips the unstack/restack and goes straight to the next vector. Late arrival is 6 cycles: if a higher-priority interrupt arrives while the core is stacking, it is taken after the current one. Those figures come from ARM's Cortex-M3/M4 technical reference manual and assume zero-wait-state memory; add a wait state per flash access and the vector fetch and prologue stretch.

A critical section converts directly to added latency: every cycle interrupts are masked is a cycle the pending request waits. So the longest interrupt-disabled region in the whole firmware is a term in the budget, not a footnote. DMA matters for the same reason: a DMA burst reading flash while the ISR's vector fetch is in flight stalls the core on the bus, not on an instruction.

To validate, instrument with DWT->CYCCNT: enable it via CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk and DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk, read it at ISR entry and at the latch, and keep a running maximum. Cross-check with a GPIO toggled at entry and exit on a scope. Drive the timer, the DMA-complete, and the comms ISR concurrently at their worst rates, and run it for hours, not seconds.

The trade-off is analytical versus measured. Summing every masking region and every higher-priority handler is provable and conservative; measurement is realistic but only covers what you exercised. Use analysis for the safety case and measurement to catch what analysis missed. Shortening a critical section costs you either a lock or a copy; deferring that work to a lower-priority task adds queue latency for the deferred work. Raising the priority of the critical section's owner lowers interference on it and raises it on everything below.

Concrete failure modes. Priority inversion: a low-priority ISR holds a spinlock the high-priority ISR needs, and the high-priority handler blocks behind it. Detect by measuring latency with the low-priority ISR forced active. Bench-only measurement: one interrupt source never exercises tail-chaining or late arrival, so the field case with two sources at the same priority is unmeasured. Sleep wake: from WFI the wake latency includes oscillator startup and PLL lock, tens to hundreds of microseconds, which dwarfs the 12-cycle entry, if your budget assumes the core is running, a wake path blows it. Flash contention: DMA reading flash while the ISR fetches its vector adds wait states you never see on an idle bench.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Perform fixed-priority response-time analysis.

Answer

What I'd say first

Assume a uniprocessor, preemptive fixed-priority scheduling, periodic or sporadic tasks with known minimum inter-arrival T_i, relative deadline D_i ≤ T_i, worst-case execution time C_i, and no self-suspension. Under those assumptions the critical instant is synchronous release of every task, and the worst-case response time of task i is the least fixed point of:

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

B_i is the longest time a lower-priority task can block i: a non-preemptive section, or a mutex held under priority inheritance. Task i meets its deadline iff R_i ≤ D_i.

Worked trace

Three tasks, all D = T:

taskTCpriority
τ151high
τ2103mid
τ3205low

τ3, B = 0:

R0 = 5
R1 = 5 + ⌈5/5⌉·1 + ⌈5/10⌉·3 = 5 + 1 + 3 = 9
R2 = 5 + ⌈9/5⌉·1 + ⌈9/10⌉·3 = 5 + 2 + 3 = 10
R3 = 5 + ⌈10/5⌉·1 + ⌈10/10⌉·3 = 5 + 2 + 3 = 10   → fixed point

R3 = 10 ≤ 20. τ2: R0=3, R1 = 3 + ⌈3/5⌉·1 = 4, R2 = 3 + ⌈4/5⌉·1 = 4 → R = 4 ≤ 10. τ1: R = 1 ≤ 5. All schedulable.

Convergence and stopping

R is monotone non-decreasing across iterations and bounded above by any fixed point, so the sequence converges to the least fixed point. Two stopping rules: stop when R_{k+1} = R_k, or stop the moment R_{k+1} > D_i. The task is unschedulable and further iteration is wasted. Raise τ3's C to 15: R0 = 15, R1 = 15 + 3 + 6 = 24 > 20, so it fails on the first iteration.

Trade-offs

  • Exact RTA vs utilization bound. Liu–Layland sufficient test: U = Σ C_i/T_i ≤ n(2^{1/n} − 1). For n = 3 that is 0.780. Here U = 0.2 + 0.3 + 0.25 = 0.75, so it passes, but the bound is sufficient only. RTA is exact for this model and is what you use when U is high or deadlines are tight.
  • Priority assignment. Deadline-monotonic (shorter D → higher priority) is optimal when D_i ≤ T_i; rate-monotonic is the special case D_i = T_i. With arbitrary deadlines DM is not optimal and you need Audsley's algorithm.
  • Sufficient vs exact. RTA assumes synchronous release and no jitter. With release jitter J_j the interference term becomes ⌈(R_i + J_j)/T_j⌉·C_j.

Failure modes

  • Ignoring release jitter underestimates R. Detect by logging actual release times against the nominal period; a jittered task can add a whole extra interference term.
  • Underestimated blocking. A mutex without priority inheritance lets a low-priority task block a high one for its full critical section. Detect with a lock-hold-time trace; the cost is a missed deadline that only appears under contention.
  • ISRs and timer ticks run above every task. If they are not in the model, R is short by their execution time. Measure ISR time on target.
  • WCET measured warm-cache is optimistic. Measure cold-cache, worst-path on the target.

Validation: run the analysis, then confirm on target with a trace of actual response times. The analysis is a bound; the trace tells you whether the assumptions hold.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Choose fixed-priority or EDF scheduling.

Answer

Assumptions first. Uniprocessor (or partitioned multicore), preemptive, periodic or sporadic tasks with known worst-case execution times, hard deadlines, one criticality level, a mainstream RTOS. Under those, I pick fixed priority (rate-monotonic when D=T, deadline-monotonic when D<T) and reach for EDF only when the task set's utilisation is too high for fixed-priority analysis and deadlines are implicit.

Why fixed priority.

Analyzability. Response-time analysis gives an exact test: R_i = C_i + Σ_{j∈hp(i)} ⌈R_i/T_j⌉ C_j, solved by fixed-point iteration. The closed-form Liu & Layland bound for RM is U ≤ n(2^{1/n} − 1): 1.0 at n=1, 0.828 at n=2, 0.780 at n=3, → ln 2 ≈ 0.693 as n→∞. RTA is exact and usually admits more than the bound.

Predictable overload. When the CPU saturates, the lowest-priority task starves first. High-criticality tasks keep meeting deadlines. That is the property you want when a watchdog or a control loop must survive a transient.

Tooling. FreeRTOS, Zephyr, VxWorks, QNX Neutrino and RTEMS all ship fixed-priority preemptive schedulers as the default. ARINC 653, the avionics partitioning standard, mandates fixed-priority preemptive scheduling. POSIX gives SCHED_FIFO and SCHED_RR. EDF is the exception: Linux's SCHED_DEADLINE (3.14+) and RTEMS's EDF scheduler plugin are the mainstream examples.

Where EDF wins. For implicit deadlines (D=T), EDF's utilisation bound is 1.0: it can schedule any set that fits. Fixed priority cannot. Concrete case:

taskCTU
T1250.40
T2470.57
total0.97

RM: T1 preempts at 0–2 and 5–7. T2 gets 2–5 (3 units) then 7–8: its fourth unit lands at t=8, past its deadline of 7. Miss. EDF: at t=0 T1's deadline (5) is earlier, so T1 runs 0–2. T2 runs 2–6, done before 7. T1's next job runs 6–8, done before 10. Both meet. EDF schedules a set RM cannot.

Failure modes.

Fixed priority: priority inversion. A high-priority task blocks on a mutex held by a low-priority task, and a medium-priority task preempts the holder. Unbounded. Mars Pathfinder, 1997: vxWorks, the ASI/MET bus mutex, repeated watchdog resets. Fix: priority inheritance (PIP) or priority ceiling (PCP/ICPP); SRP for stack sharing. Detect with lock hold-time instrumentation and latency histograms on the high-priority task.

EDF: domino effect. Under overload, a job that misses its deadline keeps the earliest (now past) deadline, so the scheduler serves it again and the next job misses too. Misses cascade. Detect with deadline-miss counters, but the first miss is already late. Contain with admission control, a deadline-overrun handler, or a CBS server to isolate the offender.

Interrupts and multicore. Fixed priority maps cleanly: interrupts sit above tasks or run as highest-priority tasks. EDF needs interrupts modelled as sporadic tasks with deadlines, or the analysis breaks. On m cores, global EDF has a utilisation bound of (m+1)/2; partitioned fixed-priority is the common industrial choice.

Decision. Default to fixed priority. Switch to EDF when measured utilisation exceeds what RTA admits and deadlines are implicit, and only with overload containment in place.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Prevent and test priority inversion.

Answer

Assumptions: preemptive fixed-priority RTOS, single core unless I say otherwise, mutexes as the shared-resource primitive.

Priority inversion is when a high-priority task H blocks on a lock held by low-priority L, and a medium-priority task M that needs no lock preempts L. L can't run to release, so H waits behind M, and that wait is set by M's runtime, not by the critical section. Two kernel mechanisms fix it.

Priority inheritance: when H blocks on a mutex held by L, the kernel raises L to H's priority until L releases. Priority ceiling: each mutex carries a ceiling equal to the highest priority of any task that can lock it; a task may lock only if its priority exceeds the ceilings of all mutexes currently held by others, and the holder runs at the ceiling.

Trace it. Priorities H=10, M=5, L=1. L acquires the mutex at t=0 with a 200 µs critical section. H becomes ready at t=20 µs and blocks. M becomes ready at t=50 µs.

  • No protocol: M (5) preempts L (1). M runs 5 ms. L resumes, finishes at ~5.25 ms, releases. H acquires at 5.25 ms: blocking ≈ 5.23 ms, driven by M.
  • Inheritance: at t=20 µs L inherits priority 10. M at 5 cannot preempt. L finishes at 200 µs, releases, drops to 1. H acquires at 200 µs: blocking ≈ 180 µs, bounded by the critical section.
  • Ceiling: mutex ceiling is 10, so L runs at 10 the moment it locks. Same bound, plus M never runs during the section.

Trade-offs. Inheritance needs no static knowledge of who locks what, but allows chained blocking: if H takes mutex A then B, each held by a different low task, H can be blocked once per mutex, so worst-case blocking is the sum of those sections. Ceiling bounds blocking to at most one critical section and prevents deadlock, but you must know every locker statically to set the ceiling, and it blocks tasks even when there is no contention. Pick ceiling when you can enumerate lockers and want a hard bound; inheritance when the lock graph is dynamic.

Named APIs. FreeRTOS: xSemaphoreCreateMutex() gives priority inheritance; xSemaphoreCreateBinary() gives none. VxWorks: semMCreate(SEM_Q_PRIORITY | SEM_INVERSION_SAFE) for inheritance, SEM_PRIORITY_CEILING for ceiling. POSIX: pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT) or PTHREAD_PRIO_PROTECT with pthread_mutexattr_setprioceiling. Zephyr's k_mutex has inheritance built in.

Failure modes and detection.

  1. Binary semaphore used as a mutex: no inheritance. Symptom: H's latency spikes scale with medium-priority CPU load, not with the critical section. Detect: a trace shows M running while H is blocked.
  2. Chained blocking under inheritance. Detect: measured blocking exceeds the longest single critical section.
  3. Ceiling set below a real locker: the bound is void; some kernels assert. Detect: static check that ceiling equals the max priority of all lockers.
  4. An ISR taking a mutex: ISRs can't block; mask interrupts or use a critical section instead. Detect: assert on an in-ISR lock attempt.
  5. Multicore: inheritance is per-core. A holder on core 0 preempted by a medium task on core 0 still delays a high task on core 1. Detect: cross-core blocking not bounded by the critical section.

Test. Instrument the high-priority task with a cycle counter (e.g. DWT->CYCCNT on Cortex-M) around the lock acquire, and log the max. Run three load profiles (idle, one medium task spinning, N medium tasks) and assert max blocking stays under the computed bound. FreeRTOS trace hooks, Percepio Tracealyzer, or SEGGER SystemView show the interleaving when the bound is violated.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Split a device-driver interrupt path from task processing.

Answer

Assumptions: Linux 6.x, SMP, one device on a level-triggered line. The question is where to draw the line between hard IRQ context and process context.

Core answer (first 90 seconds)

Split so the hard handler does only what cannot be deferred: read the status register, decide the IRQ is ours, acknowledge/clear the source, capture the datum (or DMA descriptor pointer) plus a timestamp, and wake a deferred context. Everything variable (parsing, allocation, retries, logging, waking userspace) runs in process context where it can sleep. In Linux the idiomatic mechanism is request_threaded_irq(): the primary handler returns IRQ_WAKE_THREAD and the kernel runs thread_fn in a per-IRQ kthread.

Why: the hard handler runs with local interrupts disabled on that CPU. Time spent there is added to the latency of every other interrupt on the box, and it cannot sleep: no mutexes, no GFP_KERNEL allocation, no blocking I/O. Deferring converts a hard real-time constraint into a scheduling one.

Mechanism

The IRQ core calls the primary handler with local IRQs off. Returning IRQ_WAKE_THREAD masks the line (with IRQF_ONESHOT) and wakes the kthread, which runs at SCHED_FIFO priority 50 by default (IRQ_DEFAULT_PRIO). The thread returns IRQ_HANDLED, and the core unmasks. IRQF_ONESHOT is what makes level-triggered devices safe: the source can be cleared in the thread without the line re-firing.

C
/* Linux 6.6 */
static irqreturn_t my_isr(int irq, void *dev_id)
{
    struct my_dev *d = dev_id;
    u32 status = ioread32(d->base + REG_STATUS);

    if (!(status & STATUS_IRQ))
        return IRQ_NONE;              /* shared line, not ours */

    iowrite32(status, d->base + REG_ACK);   /* W1C: clear source */
    d->irq_count++;                          /* per-CPU counter */
    return IRQ_WAKE_THREAD;                  /* defer the rest */
}

static irqreturn_t my_thread(int irq, void *dev_id)
{
    struct my_dev *d = dev_id;
    /* process context: may sleep, may kmalloc(GFP_KERNEL) */
    return IRQ_HANDLED;
}

ret = devm_request_threaded_irq(&pdev->dev, irq, my_isr, my_thread,
                                IRQF_ONESHOT, "my-dev", d);

Trace. (1) Device asserts the line. (2) IRQ core calls my_isr, local IRQs off. (3) ioread32 returns 0x0000_0004 (bit 2 = RX_READY). (4) status & STATUS_IRQ is nonzero → ours. (5) iowrite32(0x4, REG_ACK) clears the W1C bit. (6) Return IRQ_WAKE_THREAD → core masks the line and wakes the kthread. (7) my_thread runs in process context, drains the FIFO, may allocate, may wake a userspace reader. (8) Thread returns IRQ_HANDLED → core unmasks.

Trade-offs

MechanismContextSleeps?Typical added latencyUse when
Hard IRQ onlyhard IRQno~1–2 µsack + capture only
Threaded IRQkthreadyes~10–50 µsmost drivers; needs IRQF_ONESHOT for level
Taskletsoftirqnolowlegacy; being phased out
Workqueuekworkeryeshigher, sharedwork that can tolerate delay
NAPI pollsoftirqnobudgetedhigh-rate network

Latency figures are typical, workload-dependent, not measured here. Prefer preallocated rings over allocating in the ISR: allocation is the thing you deferred for.

Failure modes

  • Lost wakeup. Clear the source, then a new event arrives before the thread runs; if the thread doesn't re-check status, it's dropped. Detect: ISR event count vs thread-processed count diverge.
  • IRQ storm. Device asserts continuously; without masking the box livelocks. Detect: /proc/interrupts rate; mask and re-enable.
  • Ring overflow. Producer outruns consumer; drop and count rather than block.
  • Shared line. Return IRQ_NONE when it isn't yours, or you ack someone else's device.

Test nested interrupts, full queue, device removal, and lost wakeup.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Review a lock-free ISR-to-task ring buffer.

Answer

First I'd pin down the assumptions, because they decide whether "lock-free" is even achievable. If there is exactly one producer, the ISR, and one consumer, the task, this is SPSC, and you can do it with no locks and no CAS. If two ISRs at different priorities can both push, the head update becomes a read-modify-write and you need a critical section or a CAS loop; the lock-free claim is gone. I'll review the SPSC case and flag the MPSC escape hatch at the end.

The design I'd expect to see: monotonic uint32_t counters for head and tail that never wrap back to zero, masked with capacity-1 to index the array. Capacity is a power of two, 8 here. That encoding makes full and empty unambiguous without wasting a slot: empty is head == tail, full is head - tail == capacity. The producer owns head, the consumer owns tail; each only ever writes its own and reads the other.

Ordering is the part that is usually wrong. volatile is not enough: it stops the compiler caching the variable but does nothing about the CPU reordering the data store after the index store, and nothing about atomicity for widths larger than the bus. The producer must store the data, then store head with release semantics; the consumer must load head with acquire, then read the data. On Cortex-M4 that is a DMB before the head store and after the head load, which is what C11 memory_order_release/acquire compile to.

C
// SPSC ring, capacity 8, Cortex-M4, C11 atomics
#define CAP 8u
static uint8_t buf[CAP];
static _Atomic uint32_t head;  // written only by ISR
static _Atomic uint32_t tail;  // written only by task

bool push(uint8_t v) {                       // ISR
    uint32_t h = atomic_load_explicit(&head, memory_order_relaxed);
    uint32_t t = atomic_load_explicit(&tail, memory_order_acquire);
    if (h - t == CAP) return false;          // full
    buf[h & (CAP - 1)] = v;
    atomic_store_explicit(&head, h + 1, memory_order_release);
    return true;
}

bool pop(uint8_t *out) {                     // task
    uint32_t t = atomic_load_explicit(&tail, memory_order_relaxed);
    uint32_t h = atomic_load_explicit(&head, memory_order_acquire);
    if (h == t) return false;                // empty
    *out = buf[t & (CAP - 1)];
    atomic_store_explicit(&tail, t + 1, memory_order_release);
    return true;
}

Trace it. Capacity 8, head = tail = 0. The ISR pushes 0xA0 through 0xA7: after the eighth push head = 8, tail = 0, head - tail = 8, full. The next push returns false. The task pops: t = 0, h = 8, reads buf[0] = 0xA0, tail becomes 1. After eight pops tail = 8 = head, empty. Now the ISR pushes 0xB0: h = 8, t = 8, not full, writes buf[8 & 7] = buf[0] = 0xB0, head = 9. The task pops buf[8 & 7] = buf[0] = 0xB0. The wrap is correct because the mask is applied only at the array index, never to the counters. At the 2^32 boundary the unsigned subtraction still works: h = 0, t = 0xFFFFFFF0 gives 0x10 = 16, correct, as long as capacity stays below 2^31.

Failure modes I'd actually look for, with how you catch them:

failurecausedetection
torn indexuint16_t index on an 8-bit MCU, load is not atomicstatic assert on width; scope on the index bus
stale datahead stored without releaseintermittent wrong byte at -O2; reproduce by deleting the DMB
dropped wakeupISR gives semaphore before task blockstask stalls with a non-empty buffer; push/pop counts diverge
overrunproducer outruns consumerpush returns false; count the drops

The dropped-wakeup one is the classic: the task checks the buffer, finds it empty, and the ISR fires between the check and the block. The fix is to re-check after blocking, or use a counting semaphore given from the ISR.

Trade-off against the RTOS primitive: FreeRTOS xQueueSendFromISR is safe for multiple producers and gives you blocking, but it masks interrupts for a critical section, order of a microsecond, and copies through its own storage. The lock-free SPSC has bounded ISR latency and no masking, but one producer only, and the consumer must poll or be woken. If you have two producers, take the queue.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Size an inter-task queue and define backpressure.

Answer

Size the queue to hold the worst-case burst plus the backlog that accumulates while the consumer is blocked, then pick a backpressure policy that matches the data's value and the producer's context. For a 1 kHz producer sending 16-byte items and a consumer that drains 5 items per 10 ms, a 32-item queue (about 592 bytes in FreeRTOS) is enough if the producer blocks with a timeout when full. In an ISR, you cannot block, so you drop or overwrite.

Assume FreeRTOS 10.4.x on a 32-bit MCU. The producer is an ISR firing every 1 ms (1 kHz). The consumer is a task that wakes every 10 ms, processes up to 5 items, each taking 2 ms. The consumer can be blocked by a higher-priority task for up to 5 ms. Each item is 16 bytes (e.g., eight uint16_t).

Producer rate = 1000 items/s. Consumer rate = 500 items/s. During a 5 ms block, the backlog grows by (1000 - 500) * 0.005 = 2.5 items. A burst of 20 items can arrive. So the queue must hold at least 20 + 2.5 = 22.5 items. Add 25% margin for jitter and recovery: 22.5 * 1.25 = 28.1, round up to 32. Queue memory = 32 * 16 = 512 bytes for items, plus about 80 bytes for the queue control block, total ~592 bytes.

Backpressure is the mechanism that prevents the producer from outrunning the consumer. In an RTOS, it is implemented by making the producer wait when the queue is full (blocking send with timeout) or by discarding work (drop, overwrite, coalesce).

PolicyWhen to useWhen wrong
Blocking send with timeoutLossless, producer can wait, task contextISR context, hard real-time producer that cannot block
Non-blocking drop newestProducer cannot block, occasional loss OKLossless required
Drop oldestFresh data more importantOrder matters, lossless
Overwrite latestOnly latest value matters (sensor)Every event must be processed
CoalesceMultiple events can be mergedEach event distinct
Priority shedSome events more importantAll events equal
C
QueueHandle_t xQueue = xQueueCreate(32, sizeof(uint16_t[8])); // 16 bytes

// Producer task
void vProducerTask(void *pvParameters) {
    uint16_t item[8];
    while (1) {
        // fill item
        if (xQueueSend(xQueue, item, pdMS_TO_TICKS(10)) != pdPASS) {
            vLogDrop(); // timeout: queue full for 10 ms
        }
    }
}

// ISR
void vISR(void) {
    uint16_t item[8];
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    // fill item
    if (xQueueSendFromISR(xQueue, item, &xHigherPriorityTaskWoken) != pdPASS) {
        vLogDropFromISR(); // queue full, drop
    }
    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}

In the task, xQueueSend blocks up to 10 ms if the queue is full. If it times out, it returns pdFAIL and the item is dropped. In the ISR, xQueueSendFromISR does not block; if the queue is full, it returns pdFAIL and the item is dropped. This is backpressure: the task slows down, the ISR drops.

If the queue is too small, the ISR drops events. Detect via a drop counter incremented in vLogDropFromISR. Cost: missed control updates, safety violation. If the queue is too large, latency increases. Worst-case age of an item = queue depth / consumer rate. For 32 items at 500 items/s, age = 64 ms. If the deadline is 10 ms, that's too stale. Detect via timestamps on items or uxQueueMessagesWaiting(). Cost: control loop instability. If you use blocking send in a high-priority task, you can cause priority inversion if the consumer is lower priority. Detect via priority inheritance or timeout. Cost: missed deadlines.

Blocking send is wrong in an ISR because you cannot block. Drop newest is wrong when lossless is required. Overwrite latest is wrong when every event must be processed. Coalesce is wrong when events are distinct. Priority shed is wrong when all events are equal. If the producer is an ISR, you cannot block, so you must drop or use a hardware flow control (e.g., disable the interrupt source).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How do you establish and defend worst-case stack usage for every task in an RTOS design?

Answer

Stack depth is a worst-case bound, not a measurement. For each task I build a budget: static call-graph depth + context frame + worst-case ISR nesting + margin, then verify with canaries and an MPU guard region under stress.

Static analysis: compile with -fstack-usage (GCC/Clang) to get per-function stack usage, then walk the call graph from each task entry to find the maximum path. Recursion and indirect calls through function pointers break the graph, so SEI CERT C MEM05-C and the rule against recursion apply: ban recursion, and for indirect calls either bound the target set or add the largest target's usage. The result is a static upper bound for the task's own code.

Context frame: on Cortex-M, exception entry pushes 8 words (32 bytes) of basic frame. If the task uses the FPU, lazy stacking adds 17 words (68 bytes) plus one word of padding for 8-byte alignment, so 72 bytes. That frame is saved on the task's stack when it is preempted. FreeRTOS xTaskCreate takes stack depth in words on most ports; CMSIS-RTOS2 osThreadNew and Zephyr K_THREAD_STACK_DEFINE take bytes. Get the units right.

Worst-case interrupt nesting: the highest-priority ISR can preempt at the deepest point of the task's call chain. On Cortex-M, tail-chaining and late arrival allow up to N nested exceptions, each adding its own frame. So the budget is task depth + (max nesting depth × per-exception frame). Measure by forcing the deepest call path and firing the worst-case interrupt storm, not by running typical traffic.

Guard patterns: write a canary (e.g., 0xDEADBEEF) at the lowest address of the stack, which grows down. FreeRTOS configCHECK_FOR_STACK_OVERFLOW=2 checks it at context switch; Zephyr CONFIG_HW_STACK_PROTECTION uses the MPU. For stronger protection, configure an MPU region just below the stack limit as no-access; a push past it triggers a MemManage fault immediately. The fault handler should capture the faulting task, PC, and SP, then reset or kill the task.

If a task overflows without protection, it corrupts adjacent memory, another task's stack or TCB, and the failure surfaces later as a HardFault or silent data corruption. With MPU, the fault is immediate and attributable.

Average-case measurement is not evidence: uxTaskGetStackHighWaterMark or a high-water mark from a typical run gives a lower bound. The worst-case path may be an error handler, and the worst-case interrupt may not have fired. Use high-water marks as a sanity check, not as proof.

Re-validation: any change to the call graph, compiler version or flags, RTOS config (FPU, interrupt priorities), or ISR set invalidates the budget. Re-run static analysis, re-measure, and re-check canaries. Keep the budget in version control; CI can fail the build if a function's stack usage exceeds a threshold.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design bounded memory use for long-lived firmware.

Answer

Assumptions. Cortex-M class MCU, no MMU, an RTOS (FreeRTOS or Zephyr), deadlines in the tens of microseconds, device runs unattended for years and takes field updates. With an MMU and a Linux-class SoC most of this is replaced by cgroups and an OOM killer, so say which world you're in before you answer.

The 90-second answer. Bounded memory means every byte is accounted for at link time or in a fixed-size pool, and no allocation path can fail in a way you haven't handled. I'd partition RAM into four regions: static .bss for drivers and RTOS objects, one stack per task plus the ISR stack, DMA buffers pinned to cache-line-aligned non-cacheable memory, and a small number of fixed-block pools for anything whose size varies at runtime. Variable-size allocation in a deadline path is the thing to eliminate. A general-purpose heap gives you a first-fit search and unbounded external fragmentation, so p99 allocation latency is not a number you can put in a timing analysis. Where a subsystem genuinely needs variable sizes, give it an arena reset at a phase boundary (boot, connection setup, one transaction) so the allocator is a pointer bump and fragmentation is structurally impossible. Then prove the bounds: static stack analysis for the worst-case call chain, high-water marks in the field to confirm, and a soak that exercises the rare paths.

Why an arena bounds fragmentation.

C
typedef struct { uint8_t *base; size_t cap, used; } arena_t;

void *arena_alloc(arena_t *a, size_t n, size_t align) {
    size_t off = (a->used + align - 1) & ~(align - 1);
    if (off + n > a->cap) return NULL;
    a->used = off + n;
    return a->base + off;
}
void arena_reset(arena_t *a) { a->used = 0; }

Trace with cap = 4096, used = 0: arena_alloc(&a, 100, 4) → off = (0+3)&~3 = 0, used = 100. arena_alloc(&a, 50, 8) → off = (100+7)&~7 = 104, used = 154. arena_alloc(&a, 4000, 4) → off = (154+3)&~3 = 156, 156+4000 = 4156 > 4096, returns NULL and leaves used at 154. Allocation is O(1) and the only waste is the align-1 pad per call, bounded by the number of live allocations. The cost is real: you cannot free one object, so an arena only works when lifetimes are phase-aligned. A long-lived connection that churns objects needs a fixed-block pool instead, where internal fragmentation is at most block_size - requested and free is O(1) via a free list.

Stacks. Size each task from the worst-case call chain, not from a guess. GCC's -fstack-usage emits per-function frame sizes; walk the deepest chain and sum. Illustrative: 64 B main loop + 128 B protocol parser + 512 B AES-GCM verify + 96 B logging + two nested ISR frames of 32 B ≈ 832 B, plus the Cortex-M hardware frame (32 B) and software-saved registers (32 B) ≈ 900 B, so 1 KiB with headroom. Confirm in the field with uxTaskGetStackHighWaterMark(), which returns the minimum free stack in words since the task started: a value that never drops below ~25% of the allocation means you over-provisioned; one that approaches zero means you got lucky. Guard with configCHECK_FOR_STACK_OVERFLOW = 2, which paints a pattern at the stack end and checks it on every context switch, or on ARMv8-M use the MSPLIM/PSPLIM registers, which fault on underflow instead of corrupting the neighbouring task.

Failure modes and detection. Pool exhaustion returning NULL on a path that assumed success: assert and reset, never continue. DMA buffers sharing a cache line with CPU-written data on Cortex-M7 (32 B lines): align and place in a non-cacheable region. ISR nesting deeper than budgeted: measure with a GPIO toggle and a scope. Update rollback needing two full image slots plus a scratch area: size flash for it before you ship, not after.

When not to. If the workload is genuinely unpredictable and the device has an MMU, a heap with an OOM policy is cheaper than hand-partitioning. For everything else, the arena-plus-pool split is the default.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Diagnose an optimization-sensitive peripheral-ordering bug.

Answer

First 90 seconds. Three questions before I read any code: which core and architecture, what memory attributes the peripheral mapping uses, and does the symptom disappear when I add a print or a delay? If it disappears, I am looking at a store-buffer or compiler-reordering bug, not a logic bug. I will assume ARMv7-A or ARMv8-A, a memory-mapped peripheral, GCC or Clang at -O2, and a DMA engine sharing the buffer.

There are three independent ordering domains and the fix is different in each.

1. Compiler. volatile orders volatile accesses against each other and stops elision, but it does not order a volatile access against a non-volatile one, and it emits no CPU barrier. GCC and Clang will hoist a non-volatile descriptor read above a volatile doorbell write. Fix: every MMIO access is volatile, and where you need a compiler barrier without a CPU barrier, asm volatile("" ::: "memory").

2. CPU and store buffer. The memory attribute decides what you get for free.

AttributeGatheringReorderingEarly write ackUse for
Device-nGnRnEnononocontrol registers, side-effect ordering
Device-nGnREnonoyesdoorbells where order matters but completion does not
Device-GREyesyesyesbulk FIFO where order is irrelevant
Normal (cacheable)———DMA buffers; needs cache maintenance

With Device-nGnRE the store is acknowledged before it reaches the peripheral, so the CPU retires it and issues the next access while the write is still in the store buffer. DMB orders accesses but does not wait for completion; DSB drains the store buffer and guarantees completion; ISB flushes the pipeline after a system-register or cache-maintenance write. On x86 the picture differs: UC MMIO is strongly ordered and needs no fence, but WC memory is weakly ordered and needs sfence.

3. DMA and cache. Normal cacheable memory is invisible to a DMA engine until cleaned.

C
// ARMv7-A, GCC 12 -O2. tx_buf is Normal cacheable; doorbell is Device-nGnRE.
void send(struct dev *d, void *tx_buf, size_t n) {
    memcpy(tx_buf, payload, n);   // lands in L1/L2, may still be dirty
    d->len = n;                   // Device-nGnRE
    d->doorbell = 1;              // DMA engine watches this
}

Trace: the memcpy writes can still be dirty in cache when doorbell is written, and the DMA engine reads physical memory, not the cache, so it sees stale bytes. Two separate faults. Cache coherency: clean_dcache_range(tx_buf, n) before the doorbell. Completion: Device-nGnRE acknowledges the doorbell early, so __DSB() goes between the clean and the doorbell store. On the receive side, invalidate the buffer before starting the DMA and __DSB() after the completion interrupt before reading it.

Trade-offs. A DSB on Cortex-A9 or A53 stalls roughly 50–200 cycles depending on store-buffer depth, so a DMB per poll iteration in a hot FIFO loop is waste: map the region Device-nGnRnE and drop the barrier instead. Some peripherals let you flush a posted write with a read-back of the same register, which is cheaper than a DSB. Barriers are unnecessary for a single access with no ordering requirement, or where the attribute already enforces order. They are insufficient against a compiler that reordered a non-volatile access, and they never fix cache coherency.

Failure modes. The Heisenbug: adding a print or a delay drains the store buffer and hides the fault. Detect it by diffing -O2 against -O0 disassembly, or toggling a GPIO around the sequence and capturing it on a scope. Temperature and voltage: at low core voltage the store buffer drains slower relative to the peripheral, widening the window; sweep both core and peripheral clocks. Cost: intermittent, roughly 1 in 10^5 boots, no crash dump, field returns.

Regression. A target test that runs the sequence with the barrier removed and fails: a loopback with a deliberately slowed peripheral clock, plus a static check that the doorbell store is preceded by a DSB in the disassembly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design a zero-copy DMA receive pipeline.

Answer

Zero-copy RX means the NIC DMAs each frame straight into a buffer the stack later reads: no memcpy between wire and socket. Four moving parts: a shared descriptor ring, a buffer pool with explicit ownership handoff, cache maintenance in the correct direction, and a completion path that orders the device's writes before the CPU reads them.

Concrete target: a 10 GbE NIC on ARM64 with a non-coherent DMA master. 1024-entry descriptor ring, 16-byte descriptors, 2048-byte buffers from a page pool. Ring is 16 KB, pool is 2 MB. The device owns descriptors from head to tail; the CPU owns tail to head. The DD (descriptor-done) bit is the handoff.

C
/* ARM64, non-coherent device, 64-byte cache lines */
#define RING_SZ 1024
#define BUF_SZ  2048
#define DD      0x1

struct rx_desc {
    __le64 buf_dma;
    __le16 len;
    __le16 flags;   /* bit0 = DD */
    __le32 rsvd;
} __aligned(16);

int rx_poll(struct ring *r, int budget)
{
    int done = 0;
    while (done < budget) {
        struct rx_desc *d = &r->desc[r->tail & (RING_SZ - 1)];
        if (!(le16_to_cpu(d->flags) & DD))
            break;                       /* device still owns it */
        dma_rmb();                       /* DD before buffer read */
        dma_sync_single_for_cpu(dev, d->buf_dma, BUF_SZ, DMA_FROM_DEVICE);
        deliver(r->buf[r->tail & (RING_SZ - 1)], le16_to_cpu(d->len));
        dma_sync_single_for_device(dev, d->buf_dma, BUF_SZ, DMA_FROM_DEVICE);
        d->flags = 0;                    /* release to device */
        dma_wmb();
        r->tail++;
        writel(r->tail, r->tail_reg);
        done++;
    }
    return done;
}

Trace it with tail=5, budget=4, DD set on descriptors 5 and 6, clear on 7. Iteration 1: desc[5] has DD, dma_rmb orders the flag read before the buffer read, sync_for_cpu invalidates 32 cache lines of buffer 5 so the CPU sees the device's writes, deliver hands the buffer up, sync_for_device cleans the lines back and returns ownership, flags=0, dma_wmb orders that store before the tail write, tail=6, writel publishes it. Iteration 2 repeats for desc[6], tail=7. Iteration 3 sees DD clear and breaks. Returns 2.

Why direction matters: for RX the device wrote memory behind the CPU's cache, so you must invalidate before reading or you get stale data. For TX the CPU wrote and the device reads, so you clean before handing over. Invalidating a range the CPU has dirtied throws those writes away: that is the bug that makes people think DMA is nondeterministic.

Trade-offs. Coherent vs streaming: dma_alloc_coherent gives Normal Non-Cacheable memory on ARM64. No maintenance, but CPU reads bypass the cache and run several times slower. Streaming (dma_map_single plus sync) keeps CPU access cached and pays maintenance per buffer. Use coherent for small control structures, streaming for frame data. Zero-copy vs copy: below roughly 256 bytes the page-pool refcount, cache maintenance and skb allocation can cost more than a memcpy into a slab, so many drivers copy small frames and zero-copy only large ones. Polling vs interrupts: at 14.88 Mpps (64-byte frames on 10 GbE) the per-packet budget is 67 ns, far below interrupt latency, so NAPI takes the first interrupt then polls with a budget of 64 packets.

Arithmetic, illustrative: invalidating a 2048-byte buffer touches 32 cache lines; at a few nanoseconds per dc ivac that is 60-130 ns, over the 67 ns budget at minimum frame size. At 1500-byte frames the rate drops to about 822 kpps, 1.2 us per packet, and maintenance is under 10%.

Failure modes. Ring overrun: device drops, rx_missed_errors climbs in ethtool -S. Missing invalidate: stale frames, checksum failures. Catch it by pre-filling buffers with 0xAA and asserting none survives. Premature repost: clearing DD before the device finished writing lets it overwrite a live buffer; put a canary at the buffer tail and check it under load. Short or error descriptors: recycle the buffer, never deliver. Late interrupt after a poll: the DD bit is the only source of truth; re-check the ring, never trust the IRQ.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design a watchdog and recovery architecture.

Answer

Assumptions: single-core MCU running an RTOS, three tasks whose progress matters, one output that must be de-energised on reset. On Linux the same shape maps onto systemd's WatchdogSec=, the hung_task/softlockup detectors and /dev/watchdog; the reasoning below is the MCU version.

Core answer. A supervisor task owns the hardware watchdog and feeds it only when every required task has checked in inside its own deadline. The watchdog runs on an independent oscillator and is windowed, so a feed that arrives too early is also a reset. Reset cause and a breadcrumb survive into backup RAM, and a consecutive-reset counter drops the device into safe mode after three loops.

C
/* FreeRTOS 10.x, Cortex-M. One heartbeat slot per required task. */
typedef struct { volatile uint32_t last; uint32_t deadline_ms; } hb_t;
static hb_t hb[3] = { {0,200}, {0,200}, {0,500} };

static inline uint32_t now_ms(void) { return xTaskGetTickCount(); } /* monotonic */

void task_a(void *p) {
    for (;;) { do_work(); hb[0].last = now_ms(); vTaskDelay(pdMS_TO_TICKS(20)); }
}

void supervisor(void *p) {
    for (;;) {
        uint32_t t = now_ms();
        bool ok = true;
        for (int i = 0; i < 3; i++)
            if ((uint32_t)(t - hb[i].last) > hb[i].deadline_ms) ok = false;
        if (ok) wdt_feed();
        vTaskDelay(pdMS_TO_TICKS(50));
    }
}

Trace: task_a stamps every 20 ms. The supervisor runs every 50 ms, computes t - hb[i].last and compares against the deadline. If task_a hangs, hb[0].last stops advancing; 200 ms later the comparison fails, wdt_feed() is skipped, and the watchdog expires. The subtraction is unsigned, so it stays correct across the 32-bit tick wrap.

Timeout derivation: worst healthy gap between feeds = longest legitimate blocking operation (a 400 ms flash sector erase) + supervisor period (50 ms) + scheduling jitter (50 ms) = 500 ms. Margin 2× → 1 s. On an STM32F4 the IWDG is clocked by the LSI, nominally 32 kHz but specified loosely (tens of percent over temperature, not ppm) so a 1 s nominal timeout can land well outside that. Budget the margin for the oscillator, not just the software.

Why monotonic: a wall-clock timestamp can jump backwards on an NTP step or forwards on a manual set, which either expires a healthy system or hides a hung one. A free-running tick counter only advances.

Why windowed: a plain watchdog only catches "too slow". A task stuck in a tight loop that still stamps its heartbeat looks healthy; a windowed watchdog rejects a feed that arrives before the lower bound, so a runaway loop feeding every 5 ms trips it.

schemecatchesmissesuse when
timer ISR feeds WDTtotal CPU lockup, clock lossany task hang while the ISR still runssingle-loop firmware, no RTOS
windowed WDT fed by the main looptoo slow and too fasta task that hangs while the loop keeps runningone control loop
supervisor + per-task deadlinesone task hanging, starvationthe supervisor itself hangingRTOS with several required tasks
external WDT IC (MAX6369, TPS3813)MCU clock failure, dead MCUnothing inside the MCUsafety-relevant outputs, output gating

If there is one control loop and no RTOS, the windowed WDT fed from the loop is the right call: the supervisor adds a task that can itself hang and needs its own protection. If the MCU clock can fail, no internal watchdog helps; you need the external IC.

Failure modes: the supervisor starved by a higher-priority task fires the watchdog correctly but looks like a false positive. The breadcrumb naming the last task to check in tells them apart. A watchdog clocked from the CPU clock is disabled by the very clock fault it should catch. Feeding from an ISR masks every task hang. A driver that blocks with interrupts disabled starves the supervisor, so the reset is real but the breadcrumb points at the driver, not the watchdog.

Recovery: read the reset cause before anything clears it. On STM32F4 that is RCC_CSR, with IWDGRSTF distinguishing a watchdog reset from PORRSTF/PINRSTF. Write a breadcrumb (last task to check in, current state) to backup SRAM, which survives reset. Keep a consecutive-reset counter in the same VBAT-backed region; after three watchdog resets without a clean-shutdown marker, boot into safe mode instead of the application. Fault-inject deadlock (two tasks taking mutexes in opposite order), starvation (a high-priority task spinning), an ISR storm (timer at maximum rate) and hung I/O (driver blocking with IRQ off), and confirm each produces a reset inside the expected window with the right breadcrumb.

What changes the decision: if the outputs are not safety-relevant and a reboot is an acceptable recovery, drop the supervisor and the breadcrumb and use a windowed WDT alone. If they are, the external watchdog IC that also gates the output enable is the part that actually makes the system safe.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design deterministic boot and brownout recovery.

Answer

What a strong candidate says first

Assume a 3.3 V MCU with an internal brown-out reset, external gate drivers on the actuators, and a config region in flash. Three layers make boot deterministic: hardware holds outputs safe before code runs, software brings subsystems up in a fixed order behind one "control enabled" gate, and a bounded recovery path catches whatever fails.

Outputs are safe by default: gate drivers carry pull-downs, and MCU pins reset to input, so nothing drives until software explicitly does. I latch the reset cause, then validate clock, RAM, retained state, image, peripherals, sensors, interlocks and actuator feedback in that order. Control stays inhibited until every stage passes and the last command is fresh. Three consecutive boots that never reach healthy drop to a recovery image.

Why the order matters

Each stage depends on the one before it. You cannot CRC the image before the clock is stable, and you cannot trust a sensor reading before the ADC reference is up. Validating out of order means acting on garbage.

Reset cause is read first because the flag register can be cleared by later init. On STM32 that is RCC->CSR; on ESP32 it is esp_reset_reason().

C
uint32_t csr = RCC->CSR;
reset_cause_t cause =
    (csr & RCC_CSR_BORRSTF)  ? CAUSE_BROWNOUT :
    (csr & RCC_CSR_IWDGRSTF) ? CAUSE_WATCHDOG :
    (csr & RCC_CSR_PORRSTF)  ? CAUSE_POWERON  :
    (csr & RCC_CSR_SFTRSTF)  ? CAUSE_SOFTWARE : CAUSE_UNKNOWN;
__HAL_RCC_CLEAR_RESET_FLAGS();

uint32_t boots = nv_read_u32(SLOT_BOOT_COUNT);
if (cause != CAUSE_SOFTWARE) boots++;      // software reset is intentional
nv_write_u32(SLOT_BOOT_COUNT, boots);
if (boots > 3) enter_recovery_mode();

boots is cleared to zero only when the system reaches healthy, so the counter measures unattended boots, not total boots.

Brownout

Set the BOR threshold above the flash minimum write voltage: on a 3.3 V rail, typically 2.5–2.7 V. BOR holds the core in reset below that, but it does not finish an in-flight flash write. Work out the hold-up window: a 10 µF decoupling cap at 50 mA load gives t = C·ΔV/I = 10 µF × 0.6 V / 50 mA = 120 µs. A flash page write takes about 1 ms, so you cannot complete it. That is why config writes must be atomic: write slot B, CRC it, then flip a pointer, and on boot pick the highest-sequence slot with a valid CRC.

Trade-offs

  • Internal BOR vs external supervisor (TPS3808, MAX809): the supervisor has a tighter threshold and a clean reset pulse but costs a part and a pin. Use it when other chips share the rail and need the same protection.
  • A/B slots vs journaling: A/B costs 2× flash and is trivial to reason about; journaling spreads wear but needs compaction. For config written rarely, A/B wins.
  • Boot counter in flash vs RTC backup register: the backup register survives reset but not power loss; flash survives both but wears. Use the register for soft resets, flash for power cycles.
  • Inhibit-until-ready vs fail-operational: safety-critical systems inhibit; availability-critical ones run degraded. The hazard analysis decides.

Failure modes and detection

FailureDetected byCost
Torn flash write during brownoutCRC mismatch at stage 4config lost, one slow boot
Corrupt image boot loopboot counter > 3recovery image, degraded
Stuck sensorplausibility range at stage 7control inhibited, alarm
Stale command replayed after brownoutsequence + timestamp at stage 10command rejected
BOR set too lowCRC mismatch on next bootraise threshold

Test by ramping and dipping the rail, resetting mid-write and mid-update, corrupting retention, and cycling power rapidly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design long-uptime timeout handling.

Answer

Assume a system that stays up for months, an embedded controller or a kernel, and that timeouts are durations ("retry in 200 ms"), not calendar dates. The core answer: drive timeouts from a monotonic counter, store each deadline as an absolute tick value, and compare with wrap-safe signed subtraction, keeping every interval below half the counter's range.

Why monotonic and not wall-clock: CLOCK_MONOTONIC (or a free-running hardware counter) never steps backward, so an NTP correction or a manual settimeofday cannot make a pending timeout fire early or hang. Wall-clock is only for calendar deadlines (certificate expiry, "fire at 09:00") where surviving a clock step is the point.

Why wrap-safe subtraction works. With an unsigned 32-bit tick, compare like this:

C
// 32-bit unsigned tick, 1 kHz (1 ms per tick)
static inline bool expired(uint32_t now, uint32_t deadline) {
    return (int32_t)(now - deadline) >= 0;
}

The subtraction is modulo 2^32, and casting to int32_t reinterprets the low 32 bits as two's complement. That sign is only meaningful when the true gap is under 2^31 ticks: half the range. Past that the sign flips and the comparison lies, so the ambiguity bound is 2^31 ticks and every interval must sit below it.

Trace it. deadline = 0xFFFFFF00, now = 0x00000100 (the counter wrapped between them). now - deadline = 0x00000200 = 512; as int32_t that is +512, so expired is true: correct, 512 ms elapsed. Reverse them: now = 0xFFFFFF00, deadline = 0x00000100 gives 0xFFFFFE00 = -512, not expired. Correct.

Pick the counter so the bound covers your longest timeout:

countertickrollovermax safe interval (2^31)
32-bit1 ms49.7 days24.8 days
32-bit1 µs71.6 min35.8 min
32-bit jiffies, HZ=10001 ms49.7 days24.8 days
64-bit1 ns584 years292 years

Trade-offs and when to pick which. 32-bit vs 64-bit: a 64-bit counter at 1 ns never wraps in practice, but on a 32-bit MCU reading it is not atomic, so you pay a retry loop; a 32-bit counter reads atomically but wraps in 49.7 days at 1 ms. Decide by longest interval versus atomicity. Tickless vs periodic: a periodic tick gives a trivial incrementing counter but wakes the CPU every tick; tickless saves power but needs a free-running counter that keeps counting in low-power modes. Decide by power budget. Monotonic vs wall-clock: decide by whether the deadline must survive a clock step.

Failure modes, with how you catch them:

  • Rollover: a timeout fires ~49.7 days early or never. Detect by logging the delta between scheduled and actual fire time and asserting it stays under a threshold.
  • Multiword tearing: on a 32-bit MCU, reading a 64-bit counter as hi, lo, hi can return a value that never existed. Read hi=0x00000000, the counter crosses 2^32 (hi→1, lo→0), read lo=0x00000000; the naive combine gives 0x00000000 when the real value is 0x100000000, off by 2^32, so a timeout fires ~4.29e9 ticks early. Detect by re-reading hi and retrying if it changed.
  • Delayed wake: the timer fires late under load or after sleep. Symptom is a burst of already-expired timers; process all of them, never skip.
  • Tickless idle: the counter does not advance during sleep, so the timeout never fires. Detect by comparing counter delta against wall-clock delta across the sleep.
  • Frequency change: DVFS scales the counter, stretching or compressing timeouts. Detect by calibrating the counter against a known reference.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Integrate low-power modes into a real-time design.

Answer

Core answer. Pick the sleep depth from the tightest deadline and the wake-latency budget, not from the lowest current number in the datasheet. A mode is only usable if wake_latency + ISR + work < deadline. Then make the sleep decision atomic against interrupts, and keep the time base monotonic across the sleep so deadlines don't drift.

Three depths, and when each wins.

ModeStopsRetainsWake latency (example)Current (example)
Tickless idle (WFI)core clockeverything~1 µs~2 mA
Stop (STM32L4 STOP2)core + most clocksSRAM, RTC/LPTIM~5 µs~1.5 µA
Standbyeverything but backup domainbackup regs onlytens of µs + re-init~0.5 µA

Figures are illustrative for an STM32L4-class part with LSE running; read your own datasheet, the ordering is what matters.

Choose tickless idle when the next deadline is under a millisecond or a peripheral must keep running (UART, ADC). Choose Stop when the next deadline is milliseconds to seconds and SRAM must survive. Choose Standby only when you can afford to re-init peripherals and lose RAM: typically a device that wakes on a button or an RTC alarm every few minutes. Duty cycling (radio on a fixed schedule) is a fourth option when the wake time is set by an external protocol, not by your code.

FreeRTOS does tickless idle with configUSE_TICKLESS_IDLE: the port reprograms a low-power timer to the next deadline and corrects the tick count on wake.

Why break-even exists. Entering and leaving a low-power mode costs charge: oscillator restart, regulator settling, re-init. Sleeping saves (I_run − I_sleep) × t, so there is a minimum sleep duration below which sleeping costs more than it saves:

wake transition cost ≈ 20 µA·s   (example, Stop2 entry+exit)
savings rate        = 12 mA − 1.5 µA ≈ 12 mA
break-even          = 20 µA·s / 12 mA ≈ 1.7 ms

Sleeping 200 µs to service a 1 kHz tick is a net loss; batching to 5 ms is a win. That is why tickless idle must reprogram the tick to the next deadline, not to a fixed period.

The race, and the fix. The classic lost wakeup: an interrupt fires after you check "no work pending" but before the CPU actually stops. On Cortex-M, WFI wakes on a pending interrupt even when PRIMASK masks it, so the check and the sleep can be made atomic:

C
__disable_irq();
if (!work_pending()) {
    __WFI();          /* wakes even with PRIMASK set; ISR runs after enable */
}
__enable_irq();

WFE with the latched event register solves the same problem differently: an SEV that arrives before WFE is not lost.

Failure modes and how you see them.

  • Lost wakeup: sleep-entered counter climbs, wake counter doesn't. Detect with a watchdog and a counter pair; the device resets instead of hanging.
  • Clock failure: LSE won't start, the RTC alarm never fires, the device sleeps forever. Enable the clock-security interrupt, fall back to LSI, and log the flag.
  • Actuator unsafe: in Standby, GPIOs go to a defined state; a floating gate-driver input can turn a MOSFET on. Detect by measuring quiescent current: a stuck output shows mA where you expect µA.
  • Time wrap: a 1 kHz 32-bit tick wraps in 49.7 days; an RTC alarm set across the wrap fires early or late. Keep one monotonic source and convert, don't reset the tick on wake.

Test: interrupt just before entry, two wake sources at once, a sleep longer than the tick wrap, and clock failure.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design a secure A/B firmware update flow.

Answer

Assumptions. Embedded Linux or RTOS device, two equal-size flash slots (say 4 MB each on a 16 MB part), a bootloader that can select a slot, and a TPM 2.0 or secure element for key storage. If there's only one slot, the design changes: I'll cover that below.

The flow. A release engineer signs a manifest with an offline root key and the image with a release key; the device trusts the root via a hash burned into eFuse or a read-only partition. The manifest binds hardware ID, product ID, version, and dependencies ("requires bootloader >= 1.4"). The device streams the image into the inactive slot, verifying signature, hash, and size as it goes: never writing past the slot boundary. On success it writes one record into a small metadata partition: active = B, trial = 1, retries = 3. The bootloader reads that record, decrements retries, and jumps to B. The new image runs health checks (radio init, filesystem mount, watchdog kick) and calls the confirm API within 30 seconds. If it doesn't, the bootloader reverts to A on the next reset.

Why it works. Slot selection is atomic because it's a single sector write to a dedicated metadata partition: the bootloader reads one struct before jumping, so there's no window where both slots look valid. The retry counter must be monotonic because an attacker who can serve an old signed image (a rollback attack) would otherwise downgrade the device to a known-vulnerable version; storing it in TPM 2.0 NV (TPM2_NV_Increment) or eFuse makes it tamper-evident. Rollback reverts by flipping the active-slot byte back to A: the old image was never erased.

Alternatives.

  • Single slot + recovery image: half the flash, but the recovery image can't be updated without risking the device, and a bad recovery image bricks it. Pick this only when flash is the binding constraint.
  • Overwrite-only: faster, but no rollback. The old image is gone. MCUboot's swap-using-scratch keeps a scratch area so both images survive; that's the default for a reason.
  • Streaming vs full download: streaming needs a resumable protocol (HTTP range or chunked) but only a small RAM buffer; full download needs 2x image size in RAM or a staging partition.

The manifest format can follow IETF SUIT (RFC 9019) or TUF; both give signed metadata with roles and key rotation.

Failure modes.

FailureDetectionCost
Power loss mid-writeTrailer magic mismatch on bootRevert to old slot, one boot cycle
Corrupted imageSignature verify failsRefuse to boot, revert
Storage fullDownload returns ENOSPCOld slot untouched, retry later
Rollback attackMonotonic counter mismatchReject image, log to secure log
Health check false positiveWatchdog reset before confirmRetry counter decrements, revert after 3
C
// Called by the new image after health checks pass.
// MCUboot: marks the image confirmed so the next boot doesn't revert.
boot_set_confirmed();

Testing. Power-cut at every transition (relay or reboot -f in a loop), corrupt the trailer magic, fill the slot to the last byte, and serve an old signed image to confirm the counter rejects it. Run each 1000 times.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Separate embedded control and protective functions.

Answer

What a strong candidate says first

The question is whether a single fault in the control path can also take out protection. If it can, the two functions are not separated, whatever the code layout says. So I start from the hazard, not the architecture: what is the dangerous condition, what is the safe state, and how fast must I reach it. That fixes the required integrity and the response budget: for example, "open the heater contactor within 100 ms of a validated over-temperature reading," with a SIL 2 target under IEC 61508 or ASIL D under ISO 26262.

Then I separate along the failure modes that couple the two functions, not along source files. Two functions in one MCU share a clock, a power rail, an ADC reference, a flash image and a debug port. Separation means the protective function gets its own instance of each, or I can show the shared one cannot fail in a way that disables both.

Why separation works: common cause dominates

Redundancy only pays when the channels fail independently. IEC 61508-6 Annex D scores separation (physical distance, separate supplies, separate clocks, diverse design) and lands the common-cause beta factor between 1% and 10%. Beta is the fraction of failures that hit both channels at once, and it usually sets the floor.

Arithmetic. One channel, dangerous undetected failure rate λ_DU = 100 FIT (1×10⁻⁷/h), proof-test interval T = 1 year (8760 h):

PFD_avg(1oo1) = λ_DU·T/2 = 1e-7 × 8760 / 2 = 4.4×10⁻⁴: SIL 3 on paper.

Duplicate it 1oo2, per IEC 61508-6:

PFD_avg(1oo2) = (λ_DU·T)²/3 + β·λ_DU·T/2 = (8.76×10⁻⁴)²/3 + 0.05 × 4.4×10⁻⁴ = 2.6×10⁻⁷ + 2.2×10⁻⁵ ≈ 2.2×10⁻⁵.

The second channel bought a factor of 20, not the ~1700 the independent term alone implies. At β = 5%, the common-cause term is 99% of the total. That is the whole argument for separation: you are buying down beta, not adding channels.

Allocation options

OptionIntegrity it can reachCostRight call whenWrong call when
Same MCU, MPU-partitioned tasksSIL 1 at best~0Hazard is low and one fault cannot reach the safe stateAny SIL 2+ claim
Same MCU, lockstep core (Cortex-R5 lockstep, TI TMS570, Infineon AURIX)SIL 2 / ASIL D with external monitoring+10-30% siliconCPU and clock faults are the dominant riskPower, ADC or I/O faults dominate: lockstep does not cover them
Separate safety MCU, own clock, supply and ADCSIL 2-3+BOM, second toolchain, second qualificationControl MCU runs an RTOS and comms stack you cannot argueThe hazard is already covered by hardware
External interlock: safety relay, contactor, thermal fuse, pressure reliefHighest; independent of softwareRelay plus wiringSafe state must hold with power removed, or software cannot be trustedYou need proportional control, not a trip

When separation is not worth it: if the hazard analysis shows a single fault cannot produce the dangerous condition, a second channel adds cost and no risk reduction.

Failure modes and how you catch them

Shared resourceHow it defeats both functionsDetection
Clock / PLLDrift makes both channels miss the response deadlineIndependent oscillator; window watchdog with a too-early and too-late window
Power railBrownout resets control and safety togetherSeparate regulator, or a supply monitor that forces the relay open
ADC referenceBoth channels read the same wrong value and agreeSeparate reference, or cross-check against a different sensor type
Debug / update pathJTAG halt or a flash update stops the safety taskLock debug in production, CRC the safety image, signed updates only
Watchdog fed by the monitored taskA hung task keeps kicking and hides the hangKick from a different task on a different clock source

Operational cost: each of these adds a proof test you have to run and record. The 1-year proof-test interval is what the PFD arithmetic above assumes; skip it and the numbers are fiction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Build observability that does not invalidate timing evidence.

Answer

Assumptions first. This is a service with a p99 budget in the tens of microseconds: a trading path, a packet forwarder, a control loop. If your budget is milliseconds, a 200 ns probe is noise and none of this is worth building. I'll assume Linux on x86-64, and that you need to explain a slow request after the fact without having caused it.

The answer. Capture is a fixed-size binary record written into a per-CPU lock-free ring; formatting and shipping happen later on a low-priority thread. Timestamps come from a monotonic clock. Drops are counted and exported.

Record, 32 bytes so two fit a cache line:

C
struct ev {
    uint64_t tsc;   // monotonic ns
    uint32_t id;    // event type
    uint16_t core;  // producer
    uint16_t len;   // payload bytes
    uint64_t a, b;  // two args
};

Fast path:

C
void emit(uint32_t id, uint64_t a, uint64_t b) {
    uint64_t w = r->w;                 // only this thread writes w
    struct ev *e = &r->buf[w & r->mask];
    e->tsc = now_ns();                 // clock_gettime(CLOCK_MONOTONIC), vDSO
    e->id = id; e->core = r->core; e->len = 0; e->a = a; e->b = b;
    __atomic_store_n(&r->w, w + 1, __ATOMIC_RELEASE);
}

Why this preserves timing evidence. The producer never takes a lock, so it can't be blocked by a lower-priority thread holding one: that's the priority inversion a mutex-based logger hands you. It never allocates, so no malloc jitter. It writes to memory it already owns, so no cache-line ping-pong between cores. The only shared operation is the release store of the write index, which the drain thread reads with an acquire load; a few nanoseconds, and no contention because there is one producer per ring.

Cost: clock_gettime(CLOCK_MONOTONIC) through the vDSO is roughly 20-30 ns on typical x86-64, the stores a few ns more. Call it 30-40 ns per event. Formatting the same event with snprintf into a text line is 1-2 µs, 30-50× more, which is why formatting is deferred. If you need lower, rdtsc is ~20-30 cycles, but only if the CPU reports constant_tsc and nonstop_tsc; otherwise the counter drifts with frequency and your deltas are fiction.

Alternatives and when to pick them. A single global lock-free MPMC queue gives a total order across threads, at the cost of cache-line contention on the head and tail: worth it when cross-thread ordering matters more than per-event cost. Sampling (1 in N) cuts cost proportionally but misses the rare event you are usually chasing; a bounded ring keeps complete recent history instead. perf_event_open and LTTng-UST give you this machinery already: perf's ring defaults to one data page plus one control page, raised with -m; LTTng-UST's fast path is a few tens of ns when the ring has room. Reach for eBPF/bpftrace when the events are kernel-side.

Failure modes. Ring full: choose drop-oldest (keeps the pre-fault window, which is what you want for a crash) or overwrite-newest, and export the lost count. Perf exposes it as lost events. First write to a fresh page faults for 1-2 µs, so pre-touch and mlock the ring. Wall-clock timestamps step under NTP; use CLOCK_MONOTONIC (or _RAW to dodge slew) for deltas. TSC across sockets can be skewed: verify sync before comparing timestamps from different cores. Redact at format time, not capture time, or you have put a variable-cost branch back on the hot path.

Proving it. A/B the probe: run with capture on and off and compare p99. If the delta sits inside your noise floor, you are done.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design a hardware-in-the-loop test that exercises real-time deadlines on the target board: what must run on real silicon, how do you inject faults and load, and how do you capture deadline misses without perturbing the system under test?

Answer

Core (first 90 seconds). Before picking a rig I pin down the acceptance criterion: which deadlines, measured where, and what counts as a pass. "Control loop responds within 5 ms at p99.9, zero misses over 10^6 iterations, at 85 °C and 3.0 V" is testable; "the loop is fast enough" is not. Then I split the system: anything whose timing depends on silicon runs on the target board, everything else runs on the host.

What must run on real silicon: instruction timing with flash wait states and cache, interrupt latency, the RTOS port's context-switch cost, bus-matrix arbitration between CPU and DMA, PLL lock and clock-tree behaviour, oscillator drift, and power-state transitions. Renode and QEMU model instruction cost with an idealised cost model: fine for functional logic and for injecting software faults deterministically, not fine for producing deadline evidence. The plant model, the fault schedule and the orchestration run on the host and talk to the target over the real bus (CAN, SPI, Ethernet), so the target's actual driver and ISR path is in the loop.

Timestamping without perturbing. The measurement must cost less than the thing it measures. A UART log at 115200 baud costs ~87 µs per byte; a 40-byte line is 3.5 ms, larger than a 1 ms deadline: the instrumentation causes the miss you were trying to detect. Instead: toggle a GPIO at job entry and exit and capture it on a scope or logic analyser (~2 cycles, 12 ns at 168 MHz), and read DWT->CYCCNT in the deadline ISR. On Cortex-M4 (DUI0553) DWT provides a 32-bit cycle counter; enable it with CoreDebug->DEMCR |= TRCENA and DWT->CTRL |= 1. It wraps every 2^32 cycles: 25.6 s at 168 MHz, so unsigned subtraction is correct for any interval under that.

c static volatile uint32_t worst_cycles, miss_count; void deadline_isr(void) { uint32_t elapsed = DWT->CYCCNT - job_start; /* wrap-safe / if (elapsed > worst_cycles) worst_cycles = elapsed; if (elapsed > BUDGET_CYCLES) { miss_count++; GPIOA->BSRR = (1u << MISS_PIN); / scope-visible */ } }

Store misses in a preallocated ring the host drains after the run, never a blocking write inside the deadline path.

Fault and load injection. Bus contention: a memory-to-memory DMA burst at full rate, or a second master on the shared bus. Interrupt storms: a timer firing at a priority above and below the task under test, plus the adversarial case where the interrupt lands just before the deadline. Sensor dropout: the plant stops sending, sends stale or out-of-range values, or the SPI read returns all-0xFF. Clock stretch: hold SCL low on I2C from the slave; on the MCU, switch to the internal RC or change the PLL to simulate oscillator failure. Add flash-wait-state and cache-off runs.

Repeatability. Fixed seed for the fault schedule, reset-then-sync-pulse start, same binary and board revision. Real hardware is never perfectly repeatable, so gate statistically: N iterations, zero misses, p99.9 under budget, record the max. Run at temperature and voltage corners.

Limits. HIL cannot reproduce analogue behaviour, RF, EMC, long-term drift or rare errata, and it cannot prove the absence of a race that needs a specific interleaving. Pure logic, protocol conformance and driver register sequences stay in unit tests with a mocked register file; analogue, RF, EMC and thermal behaviour stay on the bench. HIL is slow per run, so it gates releases, not every commit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How do you decide between a bare-metal superloop with interrupts and a full RTOS for a given product?

Answer

Start by counting independent activities and their deadlines, not by preference. A superloop with interrupts is the right default when you have a handful of periodic jobs that fit in one pass, no blocking calls, and no third-party stack that assumes a scheduler. An RTOS earns its footprint when at least one of these is true: more than about three activities with different periods that cannot be serviced cooperatively; a blocking operation (flash erase, radio TX, SD write) that would stall the loop past a deadline; a hard requirement that a high-rate control task preempt a lower-priority job; or a TCP/IP, USB, BLE or filesystem stack you are integrating rather than writing. Certification is a fourth signal: a pre-qualified kernel such as Zephyr or FreeRTOS with a safety pack moves evidence from your code to the vendor's.

The costs are concrete. On a Cortex-M4 at 100 MHz, a PendSV context switch is roughly 1–2 µs including register save/restore; with FPU lazy stacking it can be higher. FreeRTOS kernel is about 6–10 KB flash and each task needs its own stack: 512 B is a floor, 1–2 KB is realistic with printf or floating point. Zephyr's minimal build is larger, tens of KB. You also inherit priority inversion (use mutexes with priority inheritance, not binary semaphores), stack overflow risk (measure high-water and enable MPU stack guard), and a certification burden if the kernel is not already qualified.

The timing budget decides it. In a superloop, worst-case response is the sum of every ISR and every polled routine in the pass. If that sum exceeds the shortest deadline, or if any routine can block, you need preemption. Example: a 1 kHz control loop has a 1 ms period. ADC read 20 µs, filter 30 µs, PID 10 µs, PWM update 5 µs, housekeeping 200 µs, comms poll 300 µs: 565 µs, fits. But if comms_poll() triggers a 5 ms flash erase, the loop misses. Under an RTOS, the control task at priority 5 preempts the comms task at priority 2, and the erase runs in a low-priority task; the control deadline holds.

A superloop that is structured well migrates cleanly: keep ISRs short, push events into ring buffers, and write each activity as a non-blocking state machine with a tick check. Then each state machine becomes a task, the ring buffer becomes a FreeRTOS queue or Zephyr k_msgq, and the tick becomes the kernel tick. Using CMSIS-RTOS2 as the abstraction lets you swap FreeRTOS for Zephyr without rewriting application logic.

Failure modes to name: superloop. A polled routine that blocks, detected by a deadline-miss counter and a GPIO toggled at loop start; RTOS. Priority inversion, detected by a mutex timeout and a task that misses its deadline only when a low-priority task holds the lock; stack overflow, detected by high-water mark and MPU fault. The update strategy interacts: a single-image superloop is simpler to A/B update; an RTOS with multiple tasks needs a coordinated safe state before flashing, and the bootloader must not depend on the kernel.

Curated: · Written: · Reviewed:

Difficulty: Hard