Skip to content
Tech Interview Prep
Technical interview guide

Interrupts & Interrupt Service Routines

How hardware interrupts preempt normal execution, and the discipline required to write an ISR that doesn't corrupt shared state or blow the interrupt budget.

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

Scope: CMSIS-Core 6.2 interrupt APIs; current FreeRTOS Cortex-M port guidance; current GCC interrupt attributes and Arm ABI 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-2

Design and validate interrupt handling for vector table.

Answer

Assumptions first. Cortex-M4 (STM32F4-class), GCC arm-none-eabi, a bootloader at 0x08000000 handing off to an application linked at 0x08020000, and a 128-entry table (16 core exceptions + 112 device IRQs). On Cortex-M0 there is no VTOR, so the relocation story below changes: I'll flag that.

The design. The vector table is 128 words = 512 bytes, and it lives in its own linker section at the start of the image so the boot ROM and bootloader can find it. Two rules decide whether it works:

  1. Alignment. VTOR (at 0xE000ED08) holds the base in bits [31:7]; bits [6:0] read as zero. So the table must be aligned to a power of two at least as large as itself: 512 bytes here. If it isn't, the VTOR write silently rounds the base down and the core fetches handlers from the wrong addresses.
  2. Relocation. The application's table is at 0x08020000, not 0x00000000, so the app must point VTOR at its own table before enabling interrupts.
C
extern uint32_t __isr_vector[];          // .isr_vector, 512-byte aligned
SCB->VTOR = (uint32_t)__isr_vector;      // bits [6:0] ignored
__DSB();
__enable_irq();
LD
.isr_vector : ALIGN(512) { KEEP(*(.isr_vector)) } > FLASH

Entry 0 is the initial MSP, entry 1 the reset vector, entries 2–15 the core exceptions (NMI, HardFault, SVCall, PendSV, SysTick…), and device IRQ n sits at index 16+n. That order is fixed by the silicon; a table generated from the vendor SVD or CMSIS startup_*.s keeps it honest.

Validation. Static checks come from the build, runtime checks from the boot path:

checkhowfail signal
table baseread VTOR, compare to &__isr_vectorVTOR still 0x08000000 → interrupts vector through the bootloader
alignmentaddr % 512 == 0base truncated, wrong handler fetched
entrieseach entry bit0 == 1 and inside app flash0xFFFFFFFF (erased) or 0x00000000
weak defaultsnm/map: symbol != Default_Handlerhandler silently aliased to the infinite loop
signaturehandler is void f(void)HardFault on exception return

Failure modes and how you catch them. A retained weak default is the nastiest: the vendor startup file aliases every vector to Default_Handler, an infinite loop, so a forgotten handler spins until the watchdog resets. You find it in the map file, not at runtime. An erased entry reads 0xFFFFFFFF; bit 0 is set so it looks like a valid Thumb address, but the fetch lands in unmapped flash and faults. A wrong offset after an OTA update means the new image's table isn't where VTOR points; CRC the table region and re-check VTOR at boot. An incompatible signature (extra parameter, non-void return, or a C++ member function) is fine on Cortex-M (the core stacks context, so a plain void f(void) is correct) but corrupts registers on cores that need __irq or __attribute__((interrupt)).

Trade-offs. A flash table is the default: simple, read-only, no copy step. A RAM table lets you re-vector at runtime (RTOS dynamic handlers, debugger breakpoints) but costs RAM and needs the copy done before interrupts enable. VTOR relocation is clean on M3/M4; on Cortex-M0 you instead remap the app region to 0x00000000, which works only if the bootloader no longer needs interrupts after the jump. Finally, keeping the weak attribute lets a missing handler link silently; dropping it turns that into a link error: good for production, but it breaks vendor startup files, so the middle ground is to keep weak and add the map-file check to CI.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Design and validate interrupt handling for interrupt path.

Answer

Assumptions, stated up front. This is about a device interrupt path, peripheral assertion through to handler entry, not the CPU's internal exception model. I'll assume Linux 6.6 on ARM64 with a GICv3, one level-triggered SPI from a UART, and a hardirq handler. Swap any of those and the gates change, not the method.

The answer. Design the path as an ordered chain of gates, each with exactly one register or field that can stop delivery, and validate by injecting a fault at each gate and asserting the observable. A path that merely works tells you nothing; the deliverable is a path where a single register read names the gate that failed.

The chain, in order:

  1. Peripheral source: the event sets the status bit (UART RIS), and the device mask (IMSC) must be clear for that bit to drive the line.
  2. Distributor enable: GICD_ISENABLER<n> bit for the SPI.
  3. Trigger config: GICD_ICFGR<n> must match the device: level for a level-driven line.
  4. Priority and routing: GICD_IPRIORITYR, GICD_IROUTER (affinity).
  5. Group: GICD_IGROUPR; Group 1 reaches Linux, Group 0 goes to EL3.
  6. CPU interface: ICC_PMR_EL1 above the interrupt's priority, ICC_IGRPEN1_EL1 = 1, PSTATE.I clear.
  7. Entry and dispatch: vector → el1_irq → gic_handle_irq reads ICC_IAR1_EL1, maps hwirq → irq_desc → the handler registered by request_irq.

A healthy delivery, traced:

UART0: RIS bit4=1, IMSC bit4=0        -> line asserted
GICD_ISENABLER0 bit33=1
GICD_ICFGR1[2]=0b00 (level)
GICD_IGROUPR1 bit1=1 (Group 1)
ICC_PMR_EL1=0xF0, ICC_IGRPEN1_EL1=1, PSTATE.I=0
CPU: el1_irq -> gic_handle_irq -> ICC_IAR1_EL1 reads 33
irq_desc[33] -> uart0_handler -> clears RIS -> ICC_EOIR1_EL1=33

Trade-offs. A hardirq handler is right when the work is a few register writes; move anything that sleeps or takes a mutex to a threaded handler with IRQF_ONESHOT, at the cost of a scheduler round-trip. Level-triggered is safer for shared lines because a missed clear re-asserts; edge-triggered is cheaper but a lost edge is lost forever. MSI/MSI-X removes the shared-line problem entirely and gives per-vector affinity: use it when the device offers it, and keep the legacy line only for older parts. Pinning affinity with GICD_IROUTER gives predictable latency; leaving it to irqbalance gives throughput. Don't pin a high-rate interrupt to a CPU that also runs your latency-critical thread.

Failure modes and how each is detected.

GateFaultObservable
SourceIMSC bit left set/proc/interrupts count flat while RIS reads 1
PendingStale edge pending bitSpurious count rises; irq N: nobody cared in dmesg
VectorICFGR edge on a level lineCount climbs toward 100 kHz, RCU stall follows
MaskPMR below the priority, or PSTATE.I setCount frozen; no irq:irq_handler_entry in ftrace
GroupIGROUPR = Group 0IAR1 never returns the ID; secure firmware sees it instead
RoutingIROUTER to an offline CPUCount frozen on that CPU only

Validation. Inject each fault deliberately: set the source mask, write GICD_ISPENDR to fake a stale pending bit, mis-set ICFGR, raise PMR, and confirm the observable above. Then do the arithmetic on the worst case: a 100 kHz storm with a 2 µs handler on a 1.5 GHz core burns 20% of one core; if the level line is never cleared it is 100%, and the box stops responding. That number, not the passing test, is what you take to review.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and validate interrupt handling for handler ABI.

Answer

Assumptions. x86-64, GCC 13, ring-0 handler, non-nested interrupts. On Cortex-M the answer inverts: the hardware stacks R0–R3, R12, LR, PC and xPSR, the handler is a plain AAPCS function, and it returns with bx lr holding EXC_RETURN. No attribute is needed there, and __attribute__((interrupt)) is the wrong tool.

Core answer. Don't hand-write the handler ABI. Make the compiler emit it, then verify the emitted code.

The IDT gate points at a stub. Two designs are credible.

  1. Compiler-generated. Mark the C handler __attribute__((interrupt)). GCC emits the GPR save/restore and returns with iretq instead of ret. The signature is void h(struct interrupt_frame *f), where the frame is {ip, cs, flags, sp, ss}. Vectors that push an error code (8, 10–14, 17, 21, 29, 30) need the second parameter unsigned long err; using the one-argument form on those vectors misreads the frame by 8 bytes. Compile that translation unit with -mgeneral-regs-only: the attribute saves general-purpose registers only, so without the flag the compiler may use XMM/YMM and silently corrupt the interrupted thread's FP state.

  2. Hand-written stub. A .S file that pushes the GPRs, aligns RSP, calls a normal C function, restores, and iretqs. Needed when you switch to an IST stack or handle nesting, but every register you forget to push is silent corruption.

__attribute__((naked)) is not a third option on x86-64: GCC permits only basic asm in a naked function there, so you write the whole stub anyway. A .S file is clearer.

Validation. Disassemble the release build, because that is what the IDT points at.

  • objdump -d vmlinux | grep -A40 '<handler>:': the handler must end in iretq, never ret.
  • Confirm the prologue pushes every GPR the body clobbers.
  • objdump -d vmlinux | grep -E '\b(xmm|ymm|zmm)[0-9]' scoped to the handler: any hit means FP state is used and not saved.
  • Check the frame offset against the vector's error-code behaviour.

Trade-offs.

designcontrolrisk
__attribute__((interrupt))lowtrusts the compiler's frame model; awkward to switch stacks
hand-written .Sfulla missed register save is silent corruption
naked—no C body allowed on x86-64

Failure modes and detection.

  • Missing or wrong attribute. The handler ends in ret, popping the return address off the interrupt frame and returning to garbage. Detect in objdump.
  • FP/SIMD clobber. The interrupted thread's XMM state is corrupted. Detect by grepping the handler disassembly for vector registers, or by building with -mgeneral-regs-only and confirming it still compiles.
  • Stack misalignment. The CPU pushes 3 qwords on a same-privilege interrupt and 5 on a privilege change, and the interrupted code's RSP is not guaranteed 16-aligned, so a hand-written stub must align RSP before call or the callee's first aligned SSE spill faults. Detect via the #GP on that instruction.
  • Frame layout. The sp/ss fields of interrupt_frame exist only on a privilege change; code that reads them on a ring-0 interrupt reads the wrong slot.
  • LTO. The attribute is a function property and survives, but verify the final linked disassembly: the wrapper, not the source, is what runs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design and validate interrupt handling for source acknowledgement.

Answer

Core answer (first 90 seconds)

Assume a level-triggered interrupt on a shared vector: the common case on ARM SoCs (GIC plus a PL011-class peripheral). The rule is: acknowledge at the source, not at the controller. Read the peripheral's masked status, handle the condition that set it, clear only the bits you handled, then verify the status reads back zero before you signal end-of-interrupt. If you clear the controller's pending bit while the peripheral still drives the line, the controller re-pends the same vector immediately and you re-enter the ISR: an interrupt storm that starves the thread you interrupted.

Why it behaves that way

A level-triggered line is a wire held high while the condition is true. The GIC latches it into GICD_ISPENDR and delivers a vector via GICC_IAR. Writing GICC_EOIR drops the active priority, but the GIC samples the line again: still high, so it re-pends. EOI must therefore come after the source deasserts. Edge-triggered is the opposite: the controller latched a transition, so clearing the source after EOI is safe, but you can lose a second edge that arrives while the vector is active unless the peripheral keeps its own pending latch.

Trade-offs

W1C (write-one-to-clear) status: writing 1 clears that bit, writing 0 leaves it. Cheap, but a read-modify-write reg |= bit; write(reg) clears every bit that was set, including ones you did not handle: evidence loss. R2C (read-to-clear): the read itself clears the flag, so a diagnostic read inside the ISR destroys the event before you act on it. Prefer W1C with explicit single-bit writes; use R2C only when the read is the acknowledgement and you never read for logging.

Masking versus clearing: masking the source in the controller stops re-entry but hides the condition, and you must still clear it before unmasking or you take one more interrupt. Loop-until-drained (re-read status until zero) handles shared vectors; a single pass leaves a second source asserted and re-enters.

Failure modes and how to detect them

  • W1C mishandled (RMW clears unhandled bits): count interrupts per source; a source that never fires while its status bit is set in a dump shows the loss.
  • R2C evidence lost: log the raw status before any read that clears, or keep a shadow counter of expected versus handled events.
  • Shared vector source missed: watchdog the ISR, if the same vector re-enters within microseconds, a source is still asserted.
  • Device still active (FIFO not drained): read status after the clear; if it re-sets, the cause is still true.
  • Clear races a new event: re-read status after the clear write; a bit set that you did not handle means an event arrived during the window.

Worked trace: PL011 UART, RX (bit 4, 0x10) and RX-timeout (bit 6, 0x40) share the vector.

C
uint32_t s = readl(UART_MIS);          // e.g. 0x50
if (s & RX) { drain_fifo();    writel(RX, UART_ICR); }
if (s & RT) { flush_partial(); writel(RT, UART_ICR); }
if (readl(UART_MIS) != 0) goto again;  // re-check before EOI
writel(id, GICC_EOIR);

Trace: read 0x50 → drain, clear RX → flush, clear RT → re-read 0x00 → EOI. Had you written s (0x50) in one shot after handling only RX, you would clear RT without flushing the partial frame: silent data loss that only shows up as a truncated read under load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate interrupt handling for edge and level semantics.

Answer

Ask first what the signal is. A transient pulse (a button, a one-shot from a sensor) needs edge detection so a pulse that arrives while the CPU is in a critical section is not lost. A condition that persists until serviced (a FIFO half-full flag, a fault line) is better level-sensitive, because the line stays asserted until you clear the cause. On Cortex-M the NVIC itself has no edge/level setting: its inputs are level-sensitive, the pending bit is set while the line is asserted, and it is set again if the line is still asserted when the handler returns. Edge detection lives in the peripheral: STM32's EXTI edge detectors, or a timer capture input. So the design is: pick the peripheral line whose semantics match the event, then make the ISR clear the cause, not just the pending bit.

Mechanism. Edge: the peripheral holds a flip-flop per line. A transition sets the pending bit (EXTI->PR on STM32). The bit stays set until software writes 1 to it; the NVIC sees the line asserted and takes the interrupt. On STM32 the edge detector sets PR regardless of the IMR mask, so masking a line latches the edge rather than losing it. Level: no latch. The line mirrors the source, and the NVIC re-enters immediately after return if the line is still high.

Trade-offs. Edge gives no storm and no re-entry, but a pulse shorter than the sampling clock is lost, and you must clear PR or the line stays asserted. Level cannot lose an event while the source is asserted, but it storms if the ISR cannot clear the source. Alternatives: DMA with a level-triggered FIFO flag for bulk data; a timer-based debounce for mechanical inputs; an external SR latch to widen a narrow pulse.

Failure modes, with detection:

  • Pulse narrower than the sampling clock. EXTI samples in the APB clock domain; on an STM32F407 with APB2 at 84 MHz the period is ~11.9 ns, so a 5 ns glitch is not guaranteed captured. Detect with a pulse generator and a scope; fix with a hardware latch or a faster clock.
  • Polarity wrong. RTSR vs FTSR swapped fires on the opposite edge. Detect by comparing the scope edge to the interrupt count.
  • Bounce. A mechanical switch produces many edges. Count interrupts in a 10 ms window: expect one, see dozens. Fix with an RC filter or timer debounce.
  • Level cleared before the cause. Clearing the NVIC pending bit while RXNE is still set re-enters immediately. Detect by handler entry count.
  • Read-modify-write clear. EXTI->PR |= mask reads, ORs, writes back; an edge on another line between the read and the write is cleared and lost. Always use EXTI->PR = mask.
AspectEdge (EXTI)Level (USART RXNE)
DetectionPeripheral edge detectorNone; line mirrors source
Pending bitSet by transition, write-1-to-clearSet while source asserted
Clear actionWrite 1 to EXTI->PRClear the source (read DR)
Missed eventPulse < sampling clockNone while asserted
Re-entryOnly on a new edgeImmediate if source not cleared
Typical useButton, one-shotFIFO, fault line, UART RX
C
/* STM32F407, PA0 -> EXTI0, rising edge. */
RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN;
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI0;  /* PA0 */
EXTI->IMR  |= EXTI_IMR_MR0;                   /* unmask line 0 */
EXTI->RTSR |= EXTI_RTSR_TR0;                  /* rising edge */
NVIC_EnableIRQ(EXTI0_IRQn);

void EXTI0_IRQHandler(void) {
    EXTI->PR = EXTI_PR_PR0;   /* write 1 to clear, before handling */
    /* handle event */
}

Trace: a rising edge on PA0 sets PR bit 0, the line asserts, the NVIC pending bit sets, the handler runs and its first instruction clears PR. A second rising edge during the handler body sets PR bit 0 again, so the NVIC pending bit sets again and the handler re-enters on return. Two edges, two handler entries. Clearing first keeps the line free for the whole body, so any edge during handling re-arms the next entry; the only way to lose an edge is the read-modify-write clear above.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design and validate interrupt handling for pending and active state.

Answer

What a strong candidate says first

On Cortex-M the NVIC holds two independent bits per IRQ: pending (readable in ISPR) and active (IABR). Pending means a request is latched and waiting to be taken; active means the exception has been entered and not yet returned from. An IRQ can be both at once, and IABR can show several bits set simultaneously when a higher-priority handler preempts a lower one.

Hardware owns the NVIC bits: it clears pending on exception entry, sets active on entry, clears active on return. The handler's job is therefore not to manage those bits but to deassert the peripheral's interrupt line and re-check it after clearing, so a request that lands mid-handler is not dropped.

Design rule: clear the peripheral source, re-read it, loop while it is still asserted, and never write the NVIC pending bit from inside the handler unless you deliberately want re-entry.

Mechanism

Registers: ISER/ICER enable, ISPR/ICPR set/clear pending, IABR read active, IPR priority. ICPR clears pending and has no effect on active. ISPR sets pending even while the IRQ is disabled; the request is taken when you enable it. Masking with PRIMASK/BASEPRI does not clear pending: a request that arrives while masked is latched and taken on unmask, which is why masking is safe but clearing pending while masked is not.

Tail-chaining: on return with pending set, the core skips unstack/restack and vectors straight into the next handler. The Cortex-M4 TRM lists exception entry at 12 cycles, tail-chaining at 6, late arrival at 6, and return at 10, so a request that arrives during a handler costs 6 cycles rather than a full 22. Late arrival: a higher-priority IRQ that asserts during stacking is serviced first without re-stacking.

Worked trace

C
/* Cortex-M4, CMSIS 5, arm-none-eabi-gcc 12, -O2 */
void TIM2_IRQHandler(void)
{
    do {
        TIM2->SR = 0;                  /* rc_w0: clears UIF and the rest */
        isr_count++;
        /* ... consume the event ... */
    } while (TIM2->SR & TIM_SR_UIF);   /* re-check: did a new event land? */
}

IRQn = 5, one-shot peripheral event, default priority.

#Eventpending (ISPR5)active (IABR5)Note
0idle00
1event A asserts line10NVIC latches pending
2exception entry01HW clears pending, sets active
3handler clears SR01line deasserts
4event B asserts line11pending set while active
5handler re-checks, loops, clears SR01B consumed; pending bit still latched
6handler returns10tail-chain
7exception entry01one spurious activation
8SR reads 0, loop exits01
9return00

The re-check loop costs one extra activation when a second event lands mid-handler. That is the price of not losing it.

Two ways to break it, same starting state:

VariantSteppendingactiveResult
handler calls NVIC_ClearPendingIRQ(5) after clearing SR501event B's pending bit destroyed; B never serviced
handler calls NVIC_SetPendingIRQ(5)311tail-chains forever; never returns to main

Failure modes and detection

  • Lost event from clearing pending late. Compare a peripheral event counter against isr_count; a gap is the signature.
  • Self-repend storm. CPU never leaves the handler. Detect with a watchdog or by sampling PC; confirm with the DWT cycle counter.
  • Reading IABR to decide which IRQ to service. IABR shows active, not pending: an IRQ that is active is already being serviced. Catch it in review.
  • Debugger halt. Halting the core leaves pending bits latched that fire on resume, and can mask others. Use SWO/ITM or DWT instead of halt.
  • Livelock in the re-check loop. If the peripheral can assert faster than the handler drains, the loop never exits. Bound the loop and defer the rest to a lower-priority context (PendSV): the legitimate use of a software-set pending bit: PENDSVSET runs at the lowest priority.

Validation

Drive the peripheral at its maximum rate and assert isr_count equals the peripheral's event count. Break in the handler and read ISPR/IABR to confirm the expected bits. Trace entry/return and tail-chains over SWO/ITM with timestamps. Put a scope on the IRQ line to confirm it deasserts before the handler returns.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and validate interrupt handling for priority encoding.

Answer

Core answer

Assume a Cortex-M MCU using the NVIC and CMSIS headers, with __NVIC_PRIO_BITS supplied by the vendor: 2 on Cortex-M0/M0+, 3 on many M4 parts (nRF52), 4 on STM32F4. Lower numeric value means higher priority. "Design" is two decisions: the preemption scheme and the priority assignment. "Validate" is proving the register bytes on the actual silicon match the intent.

Design

First, split the implemented bits into group (preemption) bits and subpriority bits with NVIC_SetPriorityGrouping. Group bits decide preemption; subpriority bits only order two pending interrupts that share a group priority: they never preempt. On a 4-bit device the reset value PRIGROUP=0 gives 4 group bits and 0 sub bits, so all 16 levels preempt each other. If you want a class of ISRs that run to completion without preempting each other, split, e.g., 2 group + 2 sub bits.

Second, assign levels. Reserve the highest (lowest numbers) for faults and the RTOS kernel. FreeRTOS requires PendSV and SysTick at the lowest priority, and any ISR calling a ...FromISR API must run at a priority numerically at or below configMAX_SYSCALL_INTERRUPT_PRIORITY. Then order the application: hard real-time (motor control, safety) above comms above background.

Trade-off

All-bits-preemption (PRIGROUP=0) gives the finest granularity and the lowest latency for the top task, but every ISR can preempt every other, so shared state must be audited everywhere. Grouped priorities (2+2) let a class of ISRs run without preempting each other, which simplifies locking, at the cost of a high-subpriority interrupt waiting behind a lower one in the same group. Choose all-preempt when latency dominates and ISRs are short and independent; choose grouping when many ISRs share data and you can absorb the extra latency.

Validation

  1. Read back. NVIC_SetPriority(IRQ, 5) on a 4-bit device writes 5 << 4 = 0x50; NVIC_GetPriority shifts back and must return 5. Assert it.

  2. Unimplemented bits. On a 3-bit device the implemented bits are [7:5]. A raw write of 0x1F (0b0001_1111) has implemented bits 000, so it reads back 0x00: the highest priority, not the low priority intended. Never write IPR raw; go through CMSIS.

  3. Double shift. Passing a pre-shifted value to NVIC_SetPriority shifts again: 0x50 << 4 = 0x500, truncated to 8 bits = 0x00 → highest priority. A "low priority" ISR becomes the top one. Keep one convention: CMSIS logical values everywhere.

  4. Reset default. Every IPR byte resets to 0x00 = highest priority, so any interrupt enabled before its priority is set runs at the top level.

logical4-bit reg3-bit reg
00x000x00
50x50—
70x700xE0
150xF0—

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design and validate interrupt handling for preemption grouping.

Answer

Assumptions: ARM Cortex-M4 (STM32F4-class), CMSIS, 4 implemented priority bits, FreeRTOS. The question is about the NVIC priority grouping, not about writing ISRs.

Core answer (first 90 seconds). Grouping is one global split of the 8-bit priority field into preemption bits and subpriority bits, held in SCB->AIRCR.PRIGROUP. It is not per-interrupt. Set it once, before any interrupt is enabled, and choose the split from the number of distinct preemption levels you need, not from the number of ISRs. Two exceptions with the same preemption priority never preempt each other; subpriority only breaks ties between exceptions that are pending at the same instant in the same group. Validate by reading PRIGROUP back after every init stage and by scoping two same-group ISRs to prove neither preempts.

Mechanism. The priority field is left-aligned in the 8-bit IPR byte; on a 4-bit part the low nibble reads as zero. PRIGROUP (AIRCR bits 10:8) sets the binary point. CMSIS exposes it as five groups:

CMSIS groupAIRCR.PRIGROUPpreempt bitssub bitspreempt levelssub levels
Group 0704116
Group 161328
Group 252244
Group 343182
Group 4340161

Choosing the split. Count the preemption levels you need, then take the smallest group that gives them. A motor-control loop that must preempt comms needs 2–3 levels; Group 2 (4 preempt levels, 4 sub levels) is the common default. If you need 16 preemption levels you give up subpriority entirely (Group 4): that is the trade, not a free choice.

Worked trace. Group 2, NVIC_GetPriorityGrouping() returns 5:

C
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);   /* PRIGROUP = 5 */
NVIC_SetPriority(EXTI0_IRQn,  NVIC_EncodePriority(5, 1, 0));
NVIC_SetPriority(TIM2_IRQn,   NVIC_EncodePriority(5, 1, 3));
NVIC_SetPriority(USART1_IRQn, NVIC_EncodePriority(5, 0, 0));

EncodePriority(5,1,0): preempt bits = 7−5 = 2, sub bits = 2. (1 & 0b11) << 2 | 0 = 4; SetPriority shifts left by 8−4 = 4, so IPR = 0x40. EncodePriority(5,1,3) = (1<<2)|3 = 7 → IPR = 0x70. EncodePriority(5,0,0) → IPR = 0x00. So EXTI0 and TIM2 share preemption level 1 and cannot preempt each other; if both are pending, EXTI0 (sub 0) runs first. USART1 (preempt 0) preempts both.

Failure modes and detection.

  • Library changes grouping. Vendor HAL or an RTOS calls NVIC_SetPriorityGrouping after your init. Detect: read SCB->AIRCR after every init stage and assert PRIGROUP == 5; fail loudly at boot.
  • Assumed reset value. PRIGROUP resets to 0, which on a 4-bit part is effectively 4 preempt / 0 sub: right by accident here, wrong on an 8-bit part. Detect: read it, never assume.
  • Subpriority mistaken for urgency. Two ISRs, same preempt, different sub. Detect: toggle a GPIO in each and scope. The higher-sub ISR waits, it does not preempt. Symptom is a "high-priority" sensor ISR delayed by a lower-sub one.
  • Unsupported core. Cortex-M0/M0+ fix PRIGROUP and often implement only 2 priority bits. Detect: write PRIGROUP, read back; unchanged means grouping is not configurable.
  • Third-party init overwrites. An RTOS or middleware reconfigures grouping after kernel start. Detect: assert in a post-init hook.

One more hazard: AIRCR bits 31:16 must carry 0x05FA (VECTKEY) or the write is ignored, and AIRCR also holds SYSRESETREQ (bit 2). A malformed write can reset the core. Changing PRIGROUP while interrupts are enabled reinterprets every priority already programmed, so a value set as preempt=1/sub=0 is re-read under the new split.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and validate interrupt handling for nesting.

Answer

I'd start by clarifying the hard real-time deadlines and which interrupts are safety-critical. Assuming a Cortex-M4 with NVIC, 4 priority bits (16 levels), and an FPU, here's how I'd design and validate nesting.

Design: Use two priority levels. Level 0 (highest) for faults and the most urgent control loop. Level 1 for communication and housekeeping. Allow nesting only for level 0: a level 0 interrupt can preempt level 1, but level 1 interrupts cannot preempt each other because they share the same priority. This bounds nesting depth to 2. For critical sections, use BASEPRI to mask level 1, leaving level 0 active. For example, __set_BASEPRI(0x10) masks level 1 on a 4-bit implementation. This keeps the most urgent interrupt responsive without disabling all interrupts.

Mechanism: The NVIC preempts based on priority. When an interrupt occurs, the processor pushes 8 registers (xPSR, PC, LR, R12, R3-R0), 32 bytes, onto the current stack. If a higher-priority interrupt arrives, it preempts after the first ISR starts (or during stacking via late arrival). Each nesting level adds at least 32 bytes plus the ISR's own stack frame. If an ISR uses the FPU, lazy stacking adds 17 words (68 bytes) on the first FPU instruction. So worst-case stack = base + sum of max stack of each nested ISR + FPU overhead.

Validation:

  1. Stack depth: paint the stack with 0xAA, run a test that triggers all interrupts at maximum rate, then find the lowest written address. Compare to allocated stack.
  2. Latency: toggle a GPIO at ISR entry and exit, measure with a logic analyzer. Measure worst-case latency for each priority level under maximum load.
  3. Priority inversion: have a low-priority ISR take a mutex, then trigger a high-priority interrupt that needs the same mutex. Measure the delay.
  4. Same-priority: trigger two same-priority interrupts back-to-back, measure the second's latency.
  5. Unbounded source: increase interrupt rate until a counter shows missed interrupts.
  6. FPU: measure latency with and without FPU usage in the ISR.

Failure modes: Priority inversion shows up as a high-priority latency spike in test 3. Same-priority blocking shows up in test 4. A reentrant driver bug appears as corrupted data under stress; detect with code review and a stress test that preempts the driver. Stack overflow is caught by stack painting. An unbounded high-rate source is caught by test 5.

Trade-offs: No nesting is simplest but hurts urgent latency. Full nesting gives best latency but increases stack and shared-state complexity. Limited nesting balances. Don't nest if all interrupts have similar deadlines or if shared state is too complex to reason about.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate interrupt handling for global masking.

Answer

Assume a Cortex-M4 at 168 MHz running FreeRTOS 10.5.1, with a UART RX FIFO and a watchdog. The design: use global masking only for short, bounded critical sections; save and restore PRIMASK; prefer BASEPRI when a high-priority IRQ must keep running. Validate with the DWT cycle counter, a scope, and stress tests.

PRIMASK=1 blocks all exceptions except NMI and HardFault. Pending IRQs latch in the NVIC pending registers and fire when PRIMASK returns to 0. A mask window therefore adds its full duration to every masked IRQ's latency. At 168 MHz, 200 cycles is 1.19 µs. If the UART RX FIFO drains in 8 µs, a 10 µs mask can overrun it.

C
// Cortex-M4, CMSIS 5.9.0
uint32_t saved = __get_PRIMASK();
__disable_irq();
shared_counter++;
__set_PRIMASK(saved);

Trace: saved=0, PRIMASK=1, increment, PRIMASK=0. If called from an ISR with PRIMASK=1, saved=1 and it stays 1. Nested: outer saves 0, disables; inner saves 1, disables, restores 1; outer restores 0. That preserves the outer critical section.

primitivemaskscostusefailure
PRIMASKall except NMI/HardFaultsimple, full latencycritical section under a few µsearly return leaves masked
BASEPRIpriorities >= thresholdleaves high-priority IRQsprotect shared data, keep motor/watchdog runningwrong threshold masks too much
local_irq_save/restorelocal CPU IRQssaves flagsLinux short sectionslong section causes latency
spin_lock_irqsavelocal IRQs + locklock + IRQ disableSMP shared datalock contention plus IRQ latency

Validation:

  1. Measure the mask window: toggle a GPIO before __disable_irq() and after __set_PRIMASK(saved); scope it. Assert max < 5 µs.
  2. Measure IRQ latency: a timer ISR toggles a GPIO; measure from mask release to ISR entry. Or read DWT->CYCCNT at mask release and at ISR entry. On 168 MHz, 200 cycles is 1.19 µs.
  3. Stress: run UART at max rate and check the overrun flag; run the watchdog and check reset count.
  4. Fault injection: force an early return and a nested call; verify PRIMASK==0 after the function.
  5. Static analysis: every __disable_irq() has a matching __set_PRIMASK(saved) on all paths.

Failure modes and detection:

  • Early return leaves masked: system hangs, watchdog resets. Detect by a test asserting PRIMASK==0 after the function.
  • Nested caller state lost: inner uses __enable_irq() instead of restore; outer critical section breaks. Detect by a nested test with a counter.
  • Watchdog delayed: mask exceeds watchdog timeout; reset. Detect by measuring max mask window against watchdog period.
  • FIFO overrun: mask exceeds FIFO drain time; overrun flag sets. Detect by reading the UART overrun flag.
  • NMI/fault: NMI is not maskable; a fault while masked may escalate to HardFault. Detect by having the fault handler log PRIMASK.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and validate interrupt handling for BASEPRI ceiling.

Answer

Clarify first: which core, how many priority bits are implemented, and which RTOS. I'll assume Cortex-M4 with 4 implemented priority bits and FreeRTOS; the design changes on M0.

BASEPRI is a threshold register. A non-zero value masks every exception whose priority value is numerically greater than or equal to it; zero disables masking. On Cortex-M a lower numeric value means higher urgency, so the ceiling is the highest numeric priority, the least urgent level, at which an ISR may still call RTOS APIs. FreeRTOS names it configMAX_SYSCALL_INTERRUPT_PRIORITY. ISRs numerically above the ceiling must not call RTOS APIs and must be short.

With 4 priority bits, a priority p is stored as p << 4:

  • Safety-stop ISR, priority 1 → 0x10. Above the ceiling, never masked.
  • UART/ADC ISRs that call xQueueSendFromISR, priority 5 → 0x50. At the ceiling.
  • SysTick and PendSV, priority 15 → 0xF0.
C
/* Cortex-M4, 4 implemented priority bits. Lower value = higher urgency. */
#define PRIO_BITS   4
#define PRIO(p)     ((uint32_t)(p) << (8 - PRIO_BITS))

#define PRIO_SAFETY  PRIO(1)    /* 0x10 - never masked */
#define PRIO_RTOS    PRIO(5)    /* 0x50 - ceiling */
#define PRIO_KERNEL  PRIO(15)   /* 0xF0 - SysTick/PendSV */

#define configMAX_SYSCALL_INTERRUPT_PRIORITY  PRIO_RTOS

static inline void critical_enter(void) {
    __set_BASEPRI(configMAX_SYSCALL_INTERRUPT_PRIORITY);  /* 0x50 */
    __DSB(); __ISB();
}
static inline void critical_exit(void) {
    __set_BASEPRI(0);   /* 0 = masking disabled */
}

Validation has three parts. First, confirm the implemented priority bits at runtime: write 0xFF to NVIC->IP[0] and read it back. A 4-bit part returns 0xF0; count the leading ones to get 4, and assert it equals PRIO_BITS. A 3-bit part returns 0xE0, and the ceiling 0x50 would be wrong.

Second, prove the masking boundary. With BASEPRI = 0x50, pend the safety IRQ (0x10) and the UART IRQ (0x50). 0x10 < 0x50, so the safety ISR runs immediately; 0x50 >= 0x50, so the UART ISR stays pending. After critical_exit writes 0, the UART ISR runs. If the safety ISR does not run, the ceiling is numerically too low.

Third, static-assert the ceiling is non-zero, because BASEPRI = 0 disables masking entirely.

Trade-offs: PRIMASK masks every configurable-priority interrupt, everything except NMI and HardFault, so the worst-case latency for a safety ISR equals the longest critical section. BASEPRI masks only priorities at or below the ceiling, so ISRs above it keep running; the price is that it needs M3+ and a correctly shifted value. An RTOS mutex only serialises tasks and cannot protect data shared with an ISR. Decide by deadline: if any ISR's deadline is shorter than the longest kernel critical section, put it above the ceiling and use BASEPRI; otherwise PRIMASK is simpler. On M0/M0+ there is no BASEPRI: the FreeRTOS port falls back to PRIMASK, so every critical section masks all interrupts; keep them to a few instructions.

Failure modes and how to catch them: unsupported core (M0/M0+ have no BASEPRI, detect at compile time via __ARM_ARCH_6M__; inverted priority) ceiling set numerically too low masks urgent ISRs, caught by the masking test above, symptom is safety-ISR latency spikes; threshold zero. Caught by the static assert; direct BASEPRI writes outside the port break RTOS nesting, caught by asserting BASEPRI equals the expected value after enter and grepping for __set_BASEPRI; restoration order. Clearing BASEPRI on every exit instead of only when the nesting counter reaches zero unmasks early, caught by asserting uxCriticalNesting == 0 and BASEPRI == 0 after exit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and validate interrupt handling for RTOS syscall ceiling.

Answer

Assumptions first. This is port-specific, so I'll pin it: ARM Cortex-M, FreeRTOS, 4 implemented priority bits (STM32-class), CMSIS, configASSERT enabled in dev builds. On Cortex-M, priority 0 is the most urgent, and FreeRTOS masks interrupts by writing configMAX_SYSCALL_INTERRUPT_PRIORITY into BASEPRI. BASEPRI masks every interrupt whose priority number is greater than or equal to that value. That one fact is the whole design: the ceiling splits the priority space, and interrupts numerically below it are never masked by the kernel, so they must never call a FreeRTOS API.

Design. I set configMAX_SYSCALL_INTERRUPT_PRIORITY to 5 and configKERNEL_INTERRUPT_PRIORITY to 15, and lay out three bands:

  • 0–4: hard-real-time ISRs that touch no kernel state. Motor commutation, fault latches. Short, no FromISR calls.
  • 5–14: RTOS-aware ISRs (UART, Ethernet, timers) all free to call the FromISR APIs.
  • 15: PendSV and SysTick, the kernel's own.

The API-selection rule is mechanical: an ISR whose configured priority number is >= 5 may call xQueueSendFromISR and friends; one below 5 may not, and if it needs to signal a task it must pend a lower-priority ISR or set a flag a task polls.

Trade-off. The ceiling value is a latency knob, not a constant to copy. Lowering it (to 3) lets more ISRs be RTOS-aware but widens every kernel critical section, because BASEPRI then masks more interrupts for longer: that adds directly to worst-case interrupt latency. Raising it (to 7) shrinks masked latency but pushes more ISRs above the ceiling, where they can't signal tasks directly. I pick the ceiling from the highest-priority ISR that genuinely needs to wake a task: that ISR's number becomes the ceiling, and everything above it must be kernel-free. The alternative to a low ceiling is deferred processing, a high-priority ISR does minimal work and pends a lower-priority RTOS-aware ISR, which costs an extra context switch but keeps the masked window small.

Validation. The port ships a check: vPortValidateInterruptPriority, called by every FromISR API when configASSERT is on. It reads the running interrupt's raw priority from the NVIC and asserts it is numerically >= configMAX_SYSCALL_INTERRUPT_PRIORITY. That catches the two most common misses:

missmechanismdetection
priority 0 defaultNVIC IPR resets to 0, the most urgent; an unconfigured ISR runs above the ceiling and BASEPRI can never mask itthe assert fires on the first FromISR call; in release, read back NVIC->IP[n] at init
shifted vs unshiftedIPR stores priority in the top bits (4 bits → shift left 4); writing an unshifted 5 lands as effective priority 0configMAX_SYSCALL_INTERRUPT_PRIORITY is defined shifted (5 << 4 = 0x50), so the assert compares like with like
ordinary API from ISRvTaskDelay etc. touch the ready list with no maskingconfigASSERT's portCHECK_IF_IN_ISR traps it
kernel config driftsomeone edits the ceiling in FreeRTOSConfig.h and ISR priorities no longer matchstatic assert tying the ceiling to a project constant, plus a CI grep
library resets prioritya vendor HAL init re-writes NVIC->IP after your initre-assert priorities after every peripheral init and read back

One more: NVIC_SetPriorityGrouping must be NVIC_PRIORITYGROUP_4 (all bits preemption, no subpriority) or BASEPRI masking and the assert's numeric comparison disagree.

C
NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
NVIC_SetPriority(UART_IRQn,  5);   /* unshifted; CMSIS writes 0x50 to IPR */
NVIC_SetPriority(MOTOR_IRQn, 2);   /* above ceiling: no FreeRTOS calls */

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and validate interrupt handling for ISR-safe APIs.

Answer

Assumptions: FreeRTOS v10.x on ARM Cortex-M4, configASSERT enabled, configMAX_SYSCALL_INTERRUPT_PRIORITY set, configTICK_RATE_HZ = 1000.

Core answer

An ISR does the minimum hardware work, then hands off to a task through an ISR-safe primitive. Three rules decide whether the design is correct:

  1. Every FreeRTOS call reachable from an ISR vector comes from the ...FromISR family.
  2. The ISR runs at a priority numerically at or below configMAX_SYSCALL_INTERRUPT_PRIORITY. Anything above it must not call any FreeRTOS API.
  3. The wake flag is initialised to pdFALSE before the first ...FromISR call and carried to exactly one portYIELD_FROM_ISR() at the end.

Validation is a call-graph audit from each vector to its leaves, plus configASSERT in a debug build, plus a measured interrupt latency.

Mechanism: why the switch is deferred

The ISR never switches context. xQueueSendFromISR() copies the item, moves the blocked receiver's TCB from the queue's waiting list to the ready list, and sets *pxHigherPriorityTaskWoken = pdTRUE. The switch itself is deferred: portYIELD_FROM_ISR() sets the PendSV pending bit in the NVIC. PendSV is configured to the lowest interrupt priority, so it runs after every other ISR has returned, at the tail of the exception return. That is why the flag must reach the end of the ISR: a yield issued before the last ...FromISR call loses the wakeup.

C
/* FreeRTOS v10.x, Cortex-M4, configASSERT enabled */
static QueueHandle_t xRxQueue;

void UART0_IRQHandler( void )
{
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;   /* must start pdFALSE */
    uint8_t ucByte = UART0->DR;

    xQueueSendFromISR( xRxQueue, &ucByte, &xHigherPriorityTaskWoken );
    /* further FromISR calls may also set the flag */

    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );  /* one yield, last */
}

Trace. Byte arrives → UART0_IRQHandler runs at priority 5 → xQueueSendFromISR queues the byte, moves vRxTask (priority 3) to the ready list, sets the flag pdTRUE → portYIELD_FROM_ISR(pdTRUE) writes ICSR.PENDSVSET → ISR returns → NVIC takes PendSV → PendSV saves the interrupted context and restores vRxTask → vRxTask runs. Had the flag been left pdFALSE, the byte is still queued but vRxTask waits for the next tick: up to 1 ms of added latency at a 1000 Hz tick.

Failure modes and how each is caught

FailureMechanismDetection
Hidden mutexA helper takes a mutex; an ISR has no TCB to suspend, so the take trips configASSERT() or corrupts the ready listCall-graph audit for xSemaphoreTake / vTaskSuspendAll reachable from the vector; configASSERT in the take path
Blocking timeoutxQueueSend(..., 10) instead of xQueueSendFromISRThe ...FromISR variants take no timeout argument, so the wrong call is visible at review; grep ISR bodies for non-FromISR names
Logging lockprintf reaches newlib _write, which takes a lockHang or assert on the first log from an ISR; route logs through a queue instead
Wrong yield macrotaskYIELD() from an ISR, or portYIELD_FROM_ISR() before the last ...FromISR callSymptom is a missed wakeup costing one tick; review the flag's lifetime
Callback invokes a task APIA driver callback calls vTaskDelay or xQueueSendportASSERT_IF_INTERRUPT_PRIORITY_INVALID() at the top of the FromISR queue functions, plus an audit of every registered callback

An ISR above configMAX_SYSCALL_INTERRUPT_PRIORITY is caught by vPortValidateInterruptPriority() under configASSERT.

Trade-offs

Keeping the work in the ISR gives the lowest latency but blocks every lower-priority interrupt and forbids blocking APIs. Queueing to a task is safe and costs one copy plus a context switch. vTaskNotifyGiveFromISR() writes a single counter in the TCB, no queue object to allocate, but supports one receiver and no buffering, so use it when exactly one task consumes and events may coalesce. Decide on the ISR's own duration: a few microseconds with no blocking call stays in the ISR; anything longer defers.

Validating it

Enable configASSERT and run the ISR paths. Audit the call graph from every vector. Measure latency with a GPIO toggle or the DWT cycle counter. Then flood the ISR above the task's drain rate and confirm the queue saturates and errQUEUE_FULL is handled rather than silently dropped.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Design and validate interrupt handling for deferred work.

Answer

I'll assume a Linux kernel on a multi-core SoC, with a high-rate interrupt source like a 1 Gbps network interface generating up to 1.48 million packets per second. The goal is to minimize time in hard IRQ context while ensuring no data loss and bounded latency for other interrupts.

My core recommendation is a threaded IRQ handler with a bounded per-CPU workqueue, or for very high rates, NAPI-style polling. The top half acknowledges the interrupt and schedules the bottom half; the bottom half does the heavy processing. For validation, we measure interrupt latency, queue depths, and drop rates under load.

Why this works: the top half runs with interrupts disabled, so it must be fast. It reads the status register, acknowledges the interrupt, and either copies data to a buffer or records a pointer. Then it schedules the bottom half. The bottom half runs in process context (threaded IRQ) or softirq context. Threaded IRQ can sleep, so it can handle complex processing. Softirq is faster but can't sleep. Deferral reduces blocking because the top half only disables interrupts briefly, allowing higher-priority interrupts to be serviced.

Now the trade-offs. Softirq gives the lowest latency but runs in interrupt context, can't sleep, and can starve user processes if not bounded. Tasklet is built on softirq, serialized per tasklet, good for small deferred work. Workqueue runs in process context, can sleep, but has higher latency due to scheduling; a bounded workqueue limits concurrency. Threaded IRQ also runs in process context, can sleep, and can be prioritized, but has context switch overhead. The IRQF_ONESHOT flag keeps the interrupt line disabled until the threaded handler completes, preventing reentrancy. Choose based on: can the work sleep? If yes, use threaded IRQ or workqueue. If latency is critical and work is short, use softirq or tasklet. If the interrupt rate is very high, use NAPI polling to batch processing.

Failure modes to watch for. Queue overflow silent: the producer outpaces the consumer, and new items are dropped without notification. Detect by monitoring queue depth and drop counters. Mitigate with a bounded queue and backpressure: disable the interrupt source when the queue is near full. Source reenabled too early: if you reenable the interrupt before the bottom half has consumed the data, the device may overwrite the buffer or generate another interrupt, causing lost data or an interrupt storm. Detect via missed interrupts or data corruption. Mitigate with IRQF_ONESHOT or reenable only after processing. Borrowed buffer overwritten: DMA writes to a buffer while software reads it. Detect via checksum errors. Mitigate with ownership handoff or separate buffers. Consumer starvation: the bottom half is delayed by other work. Detect via latency spikes. Mitigate with a dedicated high-priority workqueue or an RT thread. Ordering lost: concurrent bottom halves on different CPUs process out of order. Detect via sequence numbers. Mitigate with per-CPU queues or serialization.

To validate, use ftrace to trace irq_handler_entry/exit, softirq, and workqueue events. Use perf to measure interrupt latency and CPU cycles. Stress test by injecting a high interrupt rate and measuring queue depth, drop rate, and system responsiveness. For example, with a 1 Gbps NIC and 64-byte packets (including overhead), the packet rate is 1.48 Mpps. A 1024-entry ring fills in 0.69 ms. If the bottom half takes 10 µs per packet, it processes 100k packets per second, so it falls behind. With NAPI polling 64 packets per interrupt, the interrupt rate drops to 23k per second, reducing hard IRQ overhead. The softirq then processes the batch, which is more efficient than per-packet interrupts. This is a real technique used in Linux networking.

Here's a quick comparison table:

MechanismContextCan sleep?LatencyUse case
SoftirqInterruptNoLowestNetworking, high rate
TaskletInterruptNoLowSmall deferred work
WorkqueueProcessYesHigherBlocking work
Threaded IRQProcessYesHigherComplex, sleepable

And a code snippet for threaded IRQ:

C
request_threaded_irq(irq, top_half, bottom_half, IRQF_ONESHOT, "my_device", dev);

This registers a threaded handler where top_half runs in hard IRQ context and bottom_half runs in a kernel thread. IRQF_ONESHOT keeps the line disabled until bottom_half completes.

That's the design and validation approach.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Design and validate interrupt handling for shared atomics.

Answer

Core answer (first 90 seconds). Assume one ISR writes a shared value, the main loop and possibly lower-priority ISRs read it, and the target is a 32-bit MCU (Cortex-M) unless stated otherwise. The design rule: use a lock-free atomic when the type is lock-free on the target, a bounded critical section when it is not, and a seqlock only when you must publish a multi-word snapshot from a single writer. Validate by proving lock-freedom at compile time, then measuring worst-case interrupt latency and lost-update count under load.

Why. On Cortex-M, an aligned 32-bit load or store is single-copy atomic in hardware, so _Atomic uint32_t with memory_order_relaxed compiles to a single LDR/STR: no interrupt masking, zero added latency. On an 8-bit AVR, a 32-bit atomic is not lock-free; GCC emits __atomic_fetch_add_4, which calls __disable_interrupt()/__enable_interrupt() around the read-modify-write. That is correct but adds the libcall plus the masked window to every update.

For a multi-word snapshot (a timestamp and a value that must agree), a seqlock lets the ISR write without blocking readers:

C
// C11, single writer (ISR), multiple readers. Checked with gcc 13 -O2, Cortex-M4.
static _Atomic uint32_t seq;
static uint32_t data_a, data_b;

void isr_write(uint32_t a, uint32_t b) {
    uint32_t s = atomic_load_explicit(&seq, memory_order_relaxed);
    atomic_store_explicit(&seq, s + 1, memory_order_relaxed); // odd: writing
    atomic_thread_fence(memory_order_release);
    data_a = a; data_b = b;
    atomic_thread_fence(memory_order_release);
    atomic_store_explicit(&seq, s + 2, memory_order_relaxed); // even: done
}

bool read_snapshot(uint32_t *a, uint32_t *b) {
    for (;;) {
        uint32_t s0 = atomic_load_explicit(&seq, memory_order_acquire);
        if (s0 & 1) continue;          // writer mid-update
        *a = data_a; *b = data_b;
        atomic_thread_fence(memory_order_acquire);
        uint32_t s1 = atomic_load_explicit(&seq, memory_order_relaxed);
        if (s0 == s1) return true;
    }
}

The fences stop the compiler and CPU from hoisting data_a/data_b across the sequence reads. On Cortex-M the fence emits __DMB; on x86 acquire/release are free but the compiler barrier still matters.

Trade-offs.

mechanismadded ISR latencyreader costwhen not to use
lock-free atomicnone (single LDR/STR)one loadmulti-word invariant
critical section (__disable_irq/BASEPRI)masked window equal to the RMW bodyone masked windowlong body, or a high-priority ISR must still run: use BASEPRI, not PRIMASK
seqlocktwo stores + two fencesretry loopmore than one writer, or writer rate near reader rate

FreeRTOS taskENTER_CRITICAL() on Cortex-M writes BASEPRI with configMAX_SYSCALL_INTERRUPT_PRIORITY, so interrupts above that priority still fire. __disable_irq() sets PRIMASK and masks everything: only for short, bounded sections.

Failure modes and detection.

  • Torn counter: a 32-bit read split into two 16-bit loads on AVR. Detect with a stress test: ISR increments at 10 kHz, reader checks monotonicity over 10^7 reads; any decrease is a torn read.
  • Check-then-act: if (flag) { use(data); } where the ISR clears flag between the test and the use. Detect by widening the window with a deliberate delay in a test build; the reader then sees stale data.
  • Compiler reordering: volatile alone does not order non-volatile companion data. Detect by inspecting the generated assembly (arm-none-eabi-objdump -d) for the load order, or by running the same code on a host build under ThreadSanitizer.
  • Stale companion data: a seqlock reader that drops the second sequence check. Detect by instrumenting retry count; a correct reader retries when s0 != s1.
  • Multi-core visibility: on a dual-core Cortex-M7 or A53, a store on core 0 is not visible to core 1 without a DMB/DSB and a cache-coherent path. Detect with a ping-pong test: core 0 writes, core 1 polls, measure propagation delay; if it never arrives, the barrier or cache maintenance is missing.

Validation procedure. 1) Compile-time: _Static_assert(ATOMIC_INT_LOCK_FREE == 2, ...) for the counter type, or __atomic_always_lock_free(sizeof(x), 0). 2) Disassembly check: no __atomic_* libcall on the hot path. 3) Latency: toggle a GPIO at ISR entry and exit, measure with a scope; the critical section must not exceed the deadline of the highest-priority interrupt you still need. 4) Stress: 10 kHz ISR, 10^7 reads, zero lost updates and zero torn reads. 5) Seqlock: retry count stays below a bound you set from the writer rate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do shared interrupts work, and how does an ISR determine whether its associated device asserted the interrupt?

Answer

What a strong candidate says first

A shared interrupt line is a scarce resource multiplexed across several devices: legacy PCI INTA#–INTD#, a wired-OR SoC line, or an external NVIC EXTI line. The line is level-triggered and wired-OR (active-low open-drain on PCI), so any asserting device holds it active until every asserting device has been serviced and cleared. The vector identifies the line, not the device.

So the ISR cannot be told who fired: it must ask its own hardware. The pattern is always the same three steps: read the device's interrupt status register, AND it with the interrupt enable register, and if the result is zero return IRQ_NONE without touching a single register; otherwise service the cause, clear the device's latch, and return IRQ_HANDLED.

Two consequences worth saying out loud: the dispatcher runs every handler on the chain (Linux's handle_irq_event_percpu() walks the whole irq_desc.action list and does not short-circuit on the first IRQ_HANDLED), and the line only releases after the last asserting device clears.

Mechanism

Registration is per-handler: request_irq(irq, fn, IRQF_SHARED, name, dev_id). For shared IRQs dev_id must be non-NULL and unique: it is the cookie passed back to the handler and the key free_irq() uses to remove the right action. IRQF_SHARED handlers that are threaded must also set IRQF_ONESHOT, otherwise the level line is re-enabled before the thread finishes and re-fires immediately.

C
/* Linux 6.x irqreturn_t semantics; ISR/IER/ICR at +0x00/+0x04/+0x08 */
static irqreturn_t mydev_isr(int irq, void *dev_id)
{
    struct mydev *d = dev_id;
    u32 status  = readl(d->base + 0x00);   /* ISR */
    u32 enabled = readl(d->base + 0x04);   /* IER */
    u32 active  = status & enabled;

    if (!active)
        return IRQ_NONE;                   /* not mine: touch nothing */

    if (active & BIT(0))                   /* RX FIFO non-empty */
        schedule_work(&d->rx_work);

    writel(active, d->base + 0x08);        /* ICR: write-1-to-clear */
    return IRQ_HANDLED;
}

Trace. Devices A and B share IRQ 17; only B asserts. The controller raises 17. The kernel calls A's handler: ISR = 0, active = 0, returns IRQ_NONE, no MMIO writes. It then calls B's handler: ISR = 0x1, IER = 0x1, active = 0x1, schedules work, writes 0x1 to ICR, B de-asserts, the line releases. retval is IRQ_HANDLED, so note_interrupt() does not count it as spurious. If both assert, both handlers return IRQ_HANDLED and the line releases only after the second clear.

Legacy INTx (shared)MSI / MSI-X
Signallinglevel, active-low, open-drain, wired-ORmemory write to a per-vector address
SharingN devices per linenone; one handler per vector
Source IDISR reads its own statusvector number is the device
Vectorslimited by controller linesMSI up to 32, MSI-X up to 2048 per function
Dispatchevery handler in the chain runsexactly one handler

Failure modes

  • Spurious storm. If every handler returns IRQ_NONE on a level line, the line stays asserted and the CPU re-enters immediately. Linux's note_interrupt() counts consecutive unhandled interrupts and disables the line at roughly 100,000 (SPURIOUS_IRQ_LIMIT in kernel/irq/spurious.c; noirqdebug turns the check off). Detect it in dmesg and /proc/interrupts.
  • Wrong IRQ_NONE. A driver that forgets to mask against IER returns IRQ_NONE while its device is asserting, so nothing ever clears the line: same storm, different cause.
  • Clear race. If the device re-asserts the same bit between the ISR read and the ICR write, write-1-to-clear drops that event. Mitigate by re-reading ISR after the clear and looping, or by having the work function drain the FIFO.
  • Clearing someone else's bits. Write only active, never 0xFFFFFFFF; a multi-function controller's other function loses its pending interrupt.
  • Edge-triggered sharing. Unsafe. A device asserting while another handler runs is missed entirely; only level lines can be shared.

MSI/MSI-X removes the problem rather than solving it: each device writes to its own vector address, so no status interrogation and no chain walk. The cost of sharing is that walk: each handler in the chain performs an MMIO read across PCIe (order of hundreds of nanoseconds to ~1 µs each), so a line with eight devices can add several microseconds of non-deterministic latency before the right handler runs.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

How does an ISR detect and recover from a spurious interrupt, one that fires with no corresponding source assertion, and how do you tell that apart from a shared line where another device owns the assertion?

Answer

On Cortex-M there is no EOI register. The NVIC clears the pending bit when the exception is taken, so a vector that fires with nothing asserted will not re-pend by itself: the only thing that can drive re-entry is the peripheral still holding its flag or line. That reframes the whole problem: recovery is a peripheral-side action, not a controller-side one.

The handler's first act is to read the peripheral's raw status register, not the interrupt-enable-filtered view, and test the specific bit it owns:

c /* Cortex-M, CMSIS 6. UART1_IRQn is the vector index. / volatile uint32_t g_spurious[64]; / retained RAM, survives warm reset */

void UART1_IRQHandler(void) { uint32_t sr = UART1->SR; /* raw, not masked / if ((sr & UART_SR_RXNE) == 0u) { g_spurious[UART1_IRQn]++; if (g_spurious[UART1_IRQn] > 1000u) / storm guard / NVIC_DisableIRQ(UART1_IRQn); return; / nothing to acknowledge / } rx_byte = UART1->DR; / read clears RXNE on this part / UART1->SR = UART_SR_ERR; / W1C: write 1 to the bits you clear */ }

Writing 0 to a write-1-to-clear register is a no-op. That single mistake is the most common cause of the re-entry loop people call a spurious interrupt: the flag never clears, the level-triggered line stays asserted, and the vector fires again the instant you return.

situationraw status showscorrect actionthe bug it prevents
spuriousno owned bit setcount it, returnclearing a bit that was never set; on W1C that is a no-op and the line stays asserted
shared line, peer owns ityour bit clear, peer's bit setreturn without touching the shared statusclearing the shared register drops the peer's interrupt
unhandled vectorhandler is Default_Handlerreplace with a counting stubDefault_Handler is an infinite loop, so the part hangs

That middle row is the distinction the question is really after. On a shared line a real device did assert; you must not acknowledge on its behalf. A spurious interrupt has no owner at all, so there is nothing to acknowledge and the correct action is to count and leave.

Root causes worth naming: a gated peripheral clock, so the status register reads zero while the line is still asserted; an edge/level configuration mismatch; DMA or another core clearing the flag between assertion and handler entry; a leftover NVIC_SetPendingIRQ in the code; a pending bit set before NVIC_EnableIRQ (fix: NVIC_DisableIRQ, then NVIC_ClearPendingIRQ, then enable); and an EMC glitch on a long edge-triggered trace.

In the field you diagnose it with a retained counter array indexed by IRQn, a raw-status snapshot and timestamp captured on the first few occurrences, and rate-limited logging exposed over the debug CLI. The storm guard masks the IRQ past a threshold and sets a device-failed flag so a supervisor resets the peripheral rather than the board.

The failure modes of the guard itself matter. Masking after 1000 hits kills a device that is legitimately running at 1 kHz. A counter in ordinary RAM is zeroed by the reset you are trying to diagnose: put it in a no-init section. Logging from the spurious path can re-enter the same UART. And a peer on a shared line that never clears its own flag makes your handler look spurious forever.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate interrupt handling for ring handoff.

Answer

Core answer (first 90 seconds). Treat the ring as a single-producer/single-consumer queue where the producer is the interrupt handler and the consumer is a thread. Three decisions carry the design. The ISR never blocks: if the ring is full it drops the newest item and bumps a counter, because an interrupt handler cannot wait on a consumer. Indices are monotonic unsigned counters, never masked, so full and empty are distinguishable. The producer publishes its index with a release store and the consumer reads it with an acquire load; that pairing is what makes the slot data visible before the index that advertises it. Padding, per-CPU rings and index width all follow from those three.

C
#define RING_CAP 1024u                 /* power of two */
#define RING_MASK (RING_CAP - 1u)

struct ring {
    _Atomic uint32_t head __attribute__((aligned(64)));  /* producer writes */
    _Atomic uint32_t tail __attribute__((aligned(64)));  /* consumer writes */
    _Atomic uint32_t dropped;
    void *slot[RING_CAP];
};

/* interrupt context: no locks, no allocation, bounded time */
bool ring_push(struct ring *r, void *item)
{
    uint32_t h = atomic_load_explicit(&r->head, memory_order_relaxed);
    uint32_t t = atomic_load_explicit(&r->tail, memory_order_acquire);
    if (h - t >= RING_CAP) {                 /* full: drop newest */
        atomic_fetch_add_explicit(&r->dropped, 1, memory_order_relaxed);
        return false;
    }
    r->slot[h & RING_MASK] = item;           /* data first */
    atomic_store_explicit(&r->head, h + 1, memory_order_release); /* then index */
    return true;
}

/* consumer thread */
bool ring_pop(struct ring *r, void **out)
{
    uint32_t t = atomic_load_explicit(&r->tail, memory_order_relaxed);
    uint32_t h = atomic_load_explicit(&r->head, memory_order_acquire);
    if (h == t) return false;                /* empty */
    *out = r->slot[t & RING_MASK];
    atomic_store_explicit(&r->tail, t + 1, memory_order_release);
    return true;
}

On x86-64 the release store is a plain mov and the acquire load a plain mov (stores are not reordered with stores, loads not with loads). On arm64 they compile to stlr/ldar. Name the barrier you rely on; "volatile" is not one.

Worked trace, RING_CAP = 4, mask 3, head = tail = 0:

stephth-taction
push A000slot[0]=A, head=1
push B101slot[1]=B, head=2
push C202slot[2]=C, head=3
push D303slot[3]=D, head=4
push E404full, dropped=1, return false
pop404out=A, tail=1
push E413slot[4&3=0]=E, head=5
pop514out=B, tail=2

The push of E overwrites slot 0 only after A was consumed; the difference h - t is what makes that safe.

Trade-offs. Drop-newest (above) preserves ordering and keeps the ISR branch-free; drop-oldest needs the producer to advance tail, which races the consumer and is only worth it when the newest sample matters more than the oldest. A per-CPU ring avoids reentrancy entirely when the same IRQ can fire on several cores; masking the line is cheaper but adds interrupt latency. Index width: uint32_t is correct indefinitely because h - t is computed mod 2^32 and in-flight ≤ 1024, so the difference is exact after any number of wraps, but a uint64_t index is torn on a 32-bit MCU (two words), so pick the width the platform can load atomically.

Failure modes and how they show up.

failurecausedetection
head published earlyplain store instead of releaseconsumer sees a stale slot; fill slots with a known pattern and assert
full/empty ambiguitycomparing masked indicesring reports empty when full; unit test at exactly N
wrap bug> vs >= on the capacity checkoff-by-one drop at every wrap; test with head near 2^32
torn index64-bit index on 32-bit archsporadic garbage slot; run under a 32-bit build
cache incoherencehead and tail on one linethroughput collapses under load; check with perf c2c
overwritten unread entrywriting without the space checkconsumer reads a slot it already drained; assert monotonic sequence numbers

Validation. Prove the ordering with a stress test that writes a per-slot sequence number and asserts the consumer never sees a value ahead of the index. Prove the width by starting head at 0xFFFFFF00 and pushing past the wrap. Retain dropped as a counter exported to debugfs and alert on any increment. Stress rollover at the real interrupt rate: at 100k IRQ/s a 1024-slot ring wraps its mask every 10 ms, so a one-minute soak covers ~6000 wraps.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate interrupt handling for DMA completion.

Answer

First 90 seconds. Three things decide this design, so I'd pin them down before drawing anything: is the DMA engine cache-coherent with the CPU, is completion a dedicated MSI-X vector or a shared legacy line, and does the consumer run in hardirq or process context. On x86-64 the first is yes: PCIe devices snoop the caches, so there is no manual cache maintenance and the whole problem collapses to ordering. On most ARM64 SoCs it is no, and the design has to own cache ownership explicitly. I'll assume the non-coherent ARM64 case because it is the harder one, and flag where x86 differs.

Mechanism. The device writes the payload into a buffer, writes a completion status into a descriptor, then raises the interrupt. The ISR's job is small: read the status register, confirm the interrupt is ours, clear the source, and hand the rest to a bottom half. Clearing before returning is not optional: a level-triggered line that is still asserted re-enters immediately and you get an interrupt storm.

C
static irqreturn_t dma_done(int irq, void *dev_id)
{
    struct dma_chan *ch = dev_id;
    u32 status = readl(ch->regs + DMA_STATUS);

    if (!(status & DMA_STATUS_DONE))
        return IRQ_NONE;              /* shared line: not ours */

    writel(status, ch->regs + DMA_STATUS);  /* W1C: clear before re-enable */
    return IRQ_WAKE_THREAD;
}

static irqreturn_t dma_done_thread(int irq, void *dev_id)
{
    struct dma_chan *ch = dev_id;
    dma_rmb();                        /* status visible before payload */
    dma_unmap_single(ch->dev, ch->dma_addr, ch->len, DMA_FROM_DEVICE);
    complete(&ch->done);
    return IRQ_HANDLED;
}

Trace. Device writes 1500 bytes to the buffer, sets descriptor status = DONE, raises MSI-X vector 3. GICv3 delivers it; the CPU reads ICC_IAR1_EL1 to get the ID, vectors to dma_done. Handler reads DMA_STATUS, sees DONE, writes 1 back to clear (write-1-to-clear), returns IRQ_WAKE_THREAD. The kernel wakes the thread; dma_unmap_single on non-coherent ARM64 invalidates the buffer's cache lines (64 bytes each, rounded out to the mapping) so the CPU sees device data, not stale lines. ICC_EOIR1_EL1 is written on handler return. On x86-64 the unmap is a no-op for cache purposes.

Trade-offs.

choicecostwhen to pick it
dma_alloc_coherentmemory often uncached on ARM; slower CPU readssmall control structures, low rate
streaming map + syncyou must clean/invalidate at the right boundarybulk payloads, cache stays useful
hardirq + taskletcannot sleep; ~µs latencyhigh-rate, no locking needed
threaded IRQscheduling adds tens of µsconsumer takes mutexes or sleeps
MSI-Xper-vector, no shared-line checkany modern PCIe device
legacy INTxshared, needs IRQ_NONE pathold hardware only

Failure modes and detection. Invalidate instead of clean on a TX buffer discards CPU writes: detect with a checksum mismatch on the first transmit. A buffer that is not cache-line aligned shares a 64-byte line with a neighbour, so invalidate drops the neighbour's bytes: detect by corrupting an adjacent field. Reading descriptor status before the device's write is visible gives a spurious "no completion" that arrives late: fix with dma_rmb(), detect with sporadic timeouts. Reusing a descriptor before the device consumed it makes the device write into the wrong buffer: detect with a pattern check. Unmapping or freeing while DMA is still in flight is a use-after-free, often surfacing as an IOMMU fault.

Validation. Inject faults: delay the status write, drop the interrupt, raise it twice. Run a known pattern through the buffer and verify checksums. Watch /proc/interrupts for counts that climb without completions, and use the irqsoff tracer to bound latency. On x86-64, confirm the same test passes with cache maintenance compiled out: that proves the ordering, not the maintenance, was load-bearing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate interrupt handling for tick interrupt.

Answer

Core answer (first 90 seconds). Assume a Cortex-M MCU where SysTick drives the RTOS scheduler at 1 kHz, and the tick only has to be accurate enough for timeouts, not for wall-clock time. The design rule: the tick ISR does O(1) work and returns. It increments the tick count, expires the delayed-task list, and pends PendSV if a switch is due. Everything else (logging, sensor reads, protocol work) is deferred to a task. Validate two things: the handler's worst-case cycle count against the tick period, and the tick count against a free-running hardware counter over hours.

Why defer. At 1 kHz on a 168 MHz core the period is 168,000 cycles. A handler that costs 1,680 cycles is 1% of the CPU; one that costs 16,800 is 10% and delays every other interrupt by up to 100 µs. A printf to a UART that blocks on a full FIFO can cost milliseconds, so it must never run in the tick. FreeRTOS's Cortex-M port sets SysTick to configKERNEL_INTERRUPT_PRIORITY, the lowest priority, so the tick never preempts a real ISR, and any ISR that calls a ...FromISR() API must sit at or below configMAX_SYSCALL_INTERRUPT_PRIORITY (numerically greater, since a lower number is a higher priority on Cortex-M).

C
/* FreeRTOSConfig.h — 1 kHz tick on a 168 MHz Cortex-M4 */
#define configTICK_RATE_HZ   1000
#define configUSE_TICKLESS_IDLE 1
#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2   /* ticks */

/* SysTick reload = core_clk/tick_hz - 1 = 168000000/1000 - 1 = 167999.
   The reload register is 24-bit (max 16777215): 1 kHz and 100 Hz fit,
   1 Hz does not — you would need a prescaler or a different timer. */

void SysTick_Handler(void) {
    uint32_t t0 = DWT->CYCCNT;
    BaseType_t switch_required = xTaskIncrementTick();
    portYIELD_FROM_ISR(switch_required);
    g_tick_cycles = DWT->CYCCNT - t0;   /* budget: <1680 cycles = 1% of 1 ms */
}

Periodic vs tickless. A periodic tick is simple and predictable but wakes the core every 1 ms even when idle. Tickless idle (configUSE_TICKLESS_IDLE) reprograms a low-power timer to the next expiry and calls vTaskStepTick() on wake, so an idle system sleeps for tens of milliseconds. Use tickless when idle power dominates and your timer can wake accurately; stay periodic when you need a fixed, jitter-free time base or the low-power timer's accuracy is worse than the tick you are replacing.

Failure modes and how to catch them.

failuresymptomdetection
handler overruns the periodtimeouts slip, other IRQs delayedg_tick_cycles above budget; scope a GPIO toggle in the ISR
...FromISR() from too-high priorityrandom hard faults, corrupted kernel stateconfigASSERT in vPortValidateInterruptPriority
missed tickstick count falls behind real timecompare xTaskGetTickCount() to a free-running counter (DWT or a spare timer)
counter wrapsub-tick math jumps at 0→reloadtest across the boundary; 32-bit jiffies at 1 kHz wrap every 49.7 days
low-power wake racea tick is lost on wakesleep N ms, assert the tick advanced by N

Drift. A 20 ppm crystal drifts 20e-6 × 86400 = 1.73 s/day; a 1% RC oscillator drifts 864 s/day. Neither is a clock, if you need wall time, discipline the tick against an RTC or NTP and treat the tick as a monotonic interval source only.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate interrupt handling for latency budget.

Answer

Assume a hard real-time budget: 50 µs from the interrupt request line asserting to the first instruction of the handler, with a worst credible burst of 8 interrupts in 10 µs. I take the budget as assertion-to-first-instruction; if your budget includes the ISR, subtract the ISR duration. The design: assign NVIC preemption priorities so the tightest deadline gets the highest priority, keep every ISR under 5 µs, and use BASEPRI to mask only the priorities below the one you are protecting. Validate by measuring assertion-to-entry, not ISR duration.

Latency has four parts: hardware response (finish current instruction, arbitrate), vector fetch, context save (stacking r0-r3, r12, LR, PC, xPSR), and ISR entry. ARM documents 12 cycles for Cortex-M3/M4 with zero-wait-state memory. That is a floor. Flash wait states, bus contention from DMA, and cache misses on Cortex-M7 add to it. Tail-chaining reduces back-to-back latency to 6 cycles, but only if no higher-priority interrupt preempts.

Two credible alternatives for critical sections: (a) disable all interrupts with PRIMASK. Simple, but the longest critical section adds to every interrupt's latency; (b) use BASEPRI to mask only up to a level. Lower-priority interrupts still run, but you must prove the masked section is shorter than the budget minus the worst-case entry. Choose (b) when you have more than one deadline class; choose (a) only when the critical section is a few cycles and you have a single deadline.

Failure modes and detection:

  • Debug probe distortion: SWO/ITM trace adds cycles. Measure with the probe detached, or account for the added cycles.
  • Average reported: a mean hides the tail. Capture max over 10^6 events.
  • Caches warm only: on Cortex-M7, first access after reset misses. Run the test after a cold cache.
  • Flash wait changes: latency depends on clock and wait states. Test at the production clock.
  • Long critical section: a 20 µs masked section blows a 50 µs budget. Measure the section with a GPIO toggle.
  • Priority storm: many same-priority interrupts tail-chain but jitter. Count tail-chains in DWT.

Artefact 1: measurement code.

C
// Cortex-M4, CMSIS. Measure assertion-to-entry with two GPIOs.
void EXTI0_IRQHandler(void) {
    GPIOA->BSRR = (1u << 5);   // debug pin high at entry
    // clear pending...
    GPIOA->BSRR = (1u << 21);  // debug pin low
}

// Test harness:
// 1. Configure PA0 as EXTI0 rising edge.
// 2. Configure PA1 as output, loopback to PA0.
// 3. Toggle PA1; scope channel 1 on PA1, channel 2 on PA5.
// 4. Measure time from PA1 rising to PA5 rising.

Artefact 2: latency table (hypothetical figures for a 168 MHz Cortex-M4 with 1 flash wait state).

ScenarioLatency (cycles)Notes
Zero-wait-state, no contention12ARM documented
+1 flash wait state15hypothetical
+DMA bus contention23hypothetical
+tail-chain (back-to-back)6ARM documented

At 168 MHz, 23 cycles is 137 ns. That leaves 49.86 µs of the 50 µs budget for the ISR and any masked section. If your ISR is 5 µs, you have 44.86 µs of slack. That is the number to defend in review.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate interrupt handling for WCET.

Answer

Assumptions first. Cortex-M7 at 400 MHz (2.5 ns/cycle), TCM-resident code, a 1 kHz control loop with a hard 1 ms deadline, plus UART and ADC interrupts. "WCET of interrupt handling" means the worst-case response time of the lowest-priority handler, not just the handler body: it includes interrupt latency, the handler's own worst path, and interference from every higher-priority ISR.

Core answer. Design so every handler has a statically bounded path, then validate with response-time analysis over per-handler costs that are measured and statically bounded. Two rules do most of the work: no loop whose trip count depends on external state, and no blocking call in ISR context.

Why bounding loops bounds WCET. A drain-until-empty loop has a trip count set by the producer. If the producer's rate meets or exceeds the consumer's, the loop never exits and the handler has no finite WCET: the interrupt starves everything below it. Capping the trip count makes the handler's cost a constant you can feed into the analysis; leftover data is handled by re-entering the handler, which is cheap on Cortex-M because tail-chaining skips the full register save/restore.

C
#define RX_DRAIN_MAX 16
volatile uint32_t rx_overruns;

void UART0_IRQHandler(void) {
    uint32_t start = DWT->CYCCNT;              // enable: DEMCR.TRCENA, DWT_CTRL.CYCCNTENA
    for (int i = 0; i < RX_DRAIN_MAX; i++) {
        if (!(UART0->S1 & UART_S1_RDRF)) break;
        ring_put(UART0->D);                    // non-blocking, bounded
    }
    if (UART0->S1 & UART_S1_RDRF) rx_overruns++;   // leftover: flag, don't spin
    uint32_t c = DWT->CYCCNT - start;
    if (c > isr_wcet_cycles) isr_wcet_cycles = c;
}

Trace: the loop runs at most 16 times; each pass reads S1, then breaks or reads D. Worst path is 16 iterations at roughly 20 cycles each, plus ~40 cycles prologue/epilogue ≈ 360 cycles ≈ 0.9 µs at 400 MHz. RDRF is level-triggered, so a leftover byte re-fires the interrupt immediately: no data loss, just a second ~1 µs handler entry.

Turning per-handler costs into a WCET bound. Classic response-time analysis: R_i = C_i + B_i + Σ_{j∈hp(i)} ⌈R_i/T_j⌉·C_j. With control ISR C=2.0 µs, T=1000 µs, D=1000 µs, and higher-priority ADC (C=1.5 µs, T=100 µs) and comms (C=1.0 µs, T=50 µs):

R0 = 2.0; R1 = 2.0 + 1·1.5 + 1·1.0 = 4.5; R2 = 2.0 + ⌈4.5/100⌉·1.5 + ⌈4.5/50⌉·1.0 = 4.5. Converges at 4.5 µs against a 1000 µs deadline.

Where the C_i come from, and the trade-off. Measurement alone never proves WCET: DWT cycle counting or ETM trace (Lauterbach TRACE32, Segger J-Trace) gives the observed max over N runs, which is a lower bound. Static analysis (AbsInt aiT) gives a safe upper bound but needs loop bounds and no indirect calls. Hybrid tools (Rapita RapiTime) combine both. Choose per handler: if the path is data-dependent and you cannot annotate bounds, defer the work to a task and keep the ISR fixed-cost.

designISR WCETadded latencypick when
work in ISRgrows with worklowest< ~2 µs, no locks/logging
ISR signals RTOS taskfixed, small+ scheduler latency (5–20 µs)work needs locks, malloc, logging
DMA + completion ISRfixed, smallDMA transfer timebulk transfer

Failure modes to check in review. Drain-until-empty loops and polling a status bit that never clears (hardware fault) both remove the bound: detect with a cycle-count assertion in the handler plus a watchdog. printf in an ISR blocks on a full TX FIFO and is non-reentrant: detect by auditing ISR call graphs for non-reentrant library calls. Flash erase blocks the controller for milliseconds: never in ISR context. Two ISRs sharing a peripheral register without masking cause priority inversion: audit shared resources. A fault handler that touches the faulting resource recurses: keep it to a fixed register dump.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate interrupt handling for interrupt storm.

Answer

Assumptions first. Linux 6.x on ARM64 with a GIC (or x86 with APIC); the storm is on a level-triggered line or a device that keeps raising edges. I'll assume the source is not a safety-critical signal, because that changes the answer.

Core answer (first 90 seconds). An interrupt storm is a source asserting its IRQ faster than the handler can clear it, so the CPU spends its budget in interrupt context and threads starve. You handle it in three moves: measure the per-source rate, bound the handler so it can't monopolize the CPU, then mask or throttle the offending source while keeping evidence and degrading to a defined state. You validate by reproducing the storm and checking the system survives with the source isolated.

Why storms happen. Two mechanisms. Level-triggered: the line stays asserted until the device's status register is cleared. If the handler returns without clearing it (wrong register, firmware bug, or a condition that re-asserts instantly) the controller re-enters immediately. Edge-triggered: a device that keeps generating edges, e.g. a NIC whose ring is full and whose coalescing is off, floods you with edges. The first is a bug; the second is a load problem.

Bounding the handler. Move work out of hardirq context with a threaded IRQ: the hardirq acks the device and returns IRQ_WAKE_THREAD; the real work runs in a schedulable thread. That caps hardirq time at the ack and lets the watchdog and other threads run.

C
static atomic_t irq_count;

static irqreturn_t storm_hardirq(int irq, void *dev)
{
    struct my_dev *d = dev;
    writel(IRQ_ACK, d->base + IRQ_STATUS); /* deassert a level line */
    return IRQ_WAKE_THREAD;
}

static irqreturn_t storm_thread(int irq, void *dev)
{
    struct my_dev *d = dev;
    if (atomic_inc_return(&irq_count) > STORM_THRESHOLD) {
        disable_irq_nosync(irq);   /* nosync: disable_irq would deadlock here */
        dev_warn(d->dev, "IRQ %d storm: %d in window, masked\n",
                 irq, atomic_read(&irq_count));
        schedule_delayed_work(&d->rearm, REARM_DELAY);
        return IRQ_HANDLED;
    }
    /* real work */
    return IRQ_HANDLED;
}

Rate counting and masking. Count interrupts per source per window; above threshold, disable_irq_nosync the line and log. On MSI-X each vector is per-device, so masking one vector doesn't touch neighbours. On legacy shared INTx, masking the line disables every device on it: that's the failure mode to avoid.

Trade-offs. Masking loses events; rate-limiting (coalescing) keeps them but adds latency. Deciding criterion: can the source drop events? A NIC can (retransmit); a safety heartbeat cannot: throttle and alert instead of masking. A threaded IRQ adds scheduling latency, tens of microseconds, fine for most workloads, not for a hard real-time deadline.

Failure modes and detection.

  • Shared line masked, healthy device dies → per-device error counters; prefer MSI-X.
  • Safety event masked → watchdog on the expected heartbeat; never mask, rate-limit and alert.
  • printk in hardirq floods and can deadlock → use printk_deferred or ratelimit, or log from the thread.
  • Watchdog loop: the storm starves the watchdog, the system resets repeatedly → boot counter plus the NMI hard-lockup detector.
  • Evidence lost at boot: /proc/interrupts resets → persist counters to pstore/ramoops.

Arithmetic. A hardirq costs ~2 µs. At 100k IRQ/s that's 200 ms/s, 20% of one core. At 1M IRQ/s it's 2 s/s: two cores fully consumed, which is the storm.

Validation. Inject the storm (a test module raising the IRQ in a loop, or a fault-injection device), confirm the rate counter trips, the source is masked, healthy devices keep working, and the evidence survives reboot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate interrupt handling for fault handlers.

Answer

Assumptions. Cortex-M3/M4/M7 (arm-none-eabi-gcc 12, -mcpu=cortex-m4), bare-metal or RTOS, no debugger attached in the field. Goal: a crash record that survives the reset and says which instruction faulted and why.

Core answer. On reset, MemManage, BusFault and UsageFault are disabled, so every fault escalates to HardFault and you lose the specific status. First design decision: enable them in SHCSR (bits 16-18) and give them a priority higher than any thread or task so they can preempt and don't re-escalate. HardFault stays as the catch-all.

Second: the handler must not touch the normal runtime. The stacked frame sits on a possibly-corrupt stack, and calling printf or malloc can fault again and lock the core. So the handler is naked assembly that picks the right stack pointer, then a C function that only writes registers into a fixed .noinit record.

Which stack? On exception entry the CPU pushes an 8-word frame (R0-R3, R12, LR, PC, xPSR) onto the stack in use. EXC_RETURN in LR tells you which: bit 2 set means the frame is on PSP, clear means MSP. Bit 4 set means an extended frame (S0-S15, FPSCR) was also pushed: the first 8 words are unchanged, so PC is still frame[6].

C
typedef struct { uint32_t r0,r1,r2,r3,r12,lr,pc,xpsr; } hw_frame_t;

__attribute__((section(".noinit"))) static volatile crash_record_t g_crash;

void HardFault_Handler(void) __attribute__((naked));
void HardFault_Handler(void) {
    __asm volatile(
        "tst lr, #4        \n"   // EXC_RETURN[2]: 1 => frame on PSP
        "ite eq            \n"
        "mrseq r0, msp     \n"
        "mrsne r0, psp     \n"
        "mov  r1, lr       \n"
        "b    hardfault_c  \n");
}

void hardfault_c(uint32_t *f, uint32_t exc_ret) {
    g_crash.magic   = 0xC0FFEE01;
    g_crash.cfsr    = *(volatile uint32_t *)0xE000ED28; // MMFSR|BFSR|UFSR
    g_crash.hfsr    = *(volatile uint32_t *)0xE000ED2C;
    g_crash.bfar    = *(volatile uint32_t *)0xE000ED38;
    g_crash.mmfar   = *(volatile uint32_t *)0xE000ED34;
    g_crash.exc_ret = exc_ret;
    g_crash.pc      = f[6];
    g_crash.lr      = f[5];
    g_crash.xpsr    = f[7];
    g_crash.crc     = crc32(&g_crash, offsetof(crash_record_t, crc));
    NVIC_SystemReset();
}

Boot code checks magic + CRC, copies the record to flash, then clears it.

Trace. *(volatile uint32_t *)0x80000000 = 1; with BusFault enabled:

  • STR executes at PC=0x08000A2C; the bus returns an error.
  • Exception entry pushes the 8-word frame on MSP (thread used MSP), LR = 0xFFFFFFF9.
  • BusFault_Handler runs. CFSR = 0x00008200 → BFSR PRECISERR (bit 1) + BFARVALID (bit 7); BFAR = 0x80000000. PC in the frame = 0x08000A2C.
  • If the store was buffered and no DSB followed, you instead get IMPRECISERR (0x00000400) and PC points past the store: the faulting instruction is unknown.

Validation. Inject each fault and assert the record:

Injected faultTriggerExpected CFSRExpected PC
Undefined instructionexecute 0xDE00UFSR UNDEFINSTR 0x00010000address of 0xDE00
Divide by zeroCCR.DIV_0_TRP=1, 1/0UFSR DIVBYZERO 0x02000000the SDIV
Unaligned accessCCR.UNALIGN_TRP=1, load at buf+1UFSR UNALIGNED 0x01000000the LDR
Precise bus faultstore to unmapped addr + DSBBFSR PRECISERR 0x00000200the STR
Stack overflowrecurse past MSPBFSR STKERR 0x00001000the push

Trade-offs. Precise vs imprecise bus faults: a DSB after every store makes faults precise but costs throughput; accept imprecise on bulk paths and keep a small PC trace buffer instead. Retained RAM vs flash: RAM survives reset but not power loss, flash survives both but writing it from a fault handler risks the flash controller and takes milliseconds. Write RAM, copy at boot. Enabling configurable faults gives precise status but adds handlers and priority config; get the priorities wrong and they escalate anyway.

Failure modes. Fault in the logger (printf/malloc in the handler) → second fault → LOCKUP; detect via watchdog reset with no record. Invalid stack dereference → STKERR/UNSTKERR in CFSR, escalates to HardFault; check SP is inside known RAM before dereferencing. Nested fault lockup → HFSR.FORCED set, no record; detect via boot counter. Stale record → magic + CRC + boot counter, clear after read. Privacy leak → scrub pointers/keys before persisting. Boot overwrites evidence → place .noinit outside the bootloader's write range and verify CRC at boot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

When would you choose polling over interrupt-driven I/O on a Cortex-M, and what does each cost?

Answer

Fix two numbers before choosing: the event rate and the worst-case latency budget. Polling is the right default when the event rate is high enough that per-interrupt overhead is a meaningful fraction of the work per event, or when the rate is so low that the wake-up cost dominates. Interrupts win when events are sparse and the CPU must sleep between them.

On Cortex-M, exception entry plus exit is roughly 24 cycles, and the ISR prologue/epilogue adds another 20–40 depending on how much state you save. Call it 50 cycles per event at 100 MHz: 0.5 µs. If your event is a 1-byte UART receive at 115200 baud, bytes arrive every 87 µs, so interrupt overhead is under 1% and interrupts are clearly right. If you are reading a 1 MHz SPI sensor in a tight loop, the transfer itself might be 200 cycles; 50 cycles of interrupt overhead is 25% of the budget, and a polled loop that checks the status flag every few cycles costs almost nothing. That crossover, where per-event overhead approaches per-event work, is the first thing to measure.

The second number is the latency budget. A polled loop gives deterministic latency equal to the loop period, provided nothing blocks it. A 10 µs loop gives 10 µs worst-case response, every time. Interrupts give lower average latency but jitter: a higher-priority ISR or a masked region can delay you. If the budget is 50 µs and your poll loop period is 1 ms, polling fails outright. If the budget is 50 µs and your loop period is 10 µs, polling is the more predictable choice.

Power management decides the low-rate case. Polling keeps the CPU awake; you cannot execute WFI while spinning on a flag. At 1 Hz, a polled loop burns milliamps for nothing. An interrupt lets the core sleep in WFI and wake on the event, which is why buttons, RTC alarms and low-rate sensors are interrupt-driven even though the event is trivial.

PollingInterrupt-driven
LatencyLoop period, deterministicLower average, jitter from priority/masking
CPU at high rateLow, no per-event overheadOverhead dominates
CPU at low rateWastes power, CPU awakeNear zero, sleeps in WFI
Failure modeOverrun: event missed while loop blockedStorm, priority inversion, missed ack
DetectionOverrun flag, loop-time counterISR entry counter, NVIC pending bits

Hardware without usable interrupt routing (a shared line you cannot ack, a peripheral whose IRQ is not wired) forces polling regardless. So does a deterministic tight loop where the poll is already part of the control cycle. Use SysTick as the loop timer if you need to prove the period; a free-running counter works too, but SysTick is already there on Cortex-M. If an RTOS is present, the tick interrupt is already consuming cycles; a polled task that spins at high priority can starve it, so the poll loop must yield or run at the lowest priority.

A polled loop needs an overrun check, not just a flag read:

c for (;;) { if (SPI->SR & SPI_SR_RXNE) { buf[i++] = SPI->DR; } else if (SPI->SR & SPI_SR_OVR) { SPI->SR = ~SPI_SR_OVR; /* clear overrun */ overruns++; } if (i == N) break; }

Without the overrun branch, a blocked loop silently drops data. With interrupts, the equivalent detection is an ISR entry counter compared against the expected event rate; a gap means a masked or lost interrupt.

Curated: · Written: · Reviewed:

Difficulty: Medium