Real-Time Constraints and Interrupt Handling Questions
Interrupts and hard timing in embedded firmware. Covers the interrupt mechanism (vector tables and their relocation, interrupt controllers such as the Cortex-M NVIC, GIC, APIC and PIC, priorities, nesting and its stack cost, tail-chaining, NMIs, and Cortex-M exception and fault handling, including decoding the stacked registers after a HardFault, capturing crash diagnostics across a reset, and MemManage and BusFault handling with the MPU), writing short and re-entrant interrupt service routines, deferring work out of the ISR (including RTOS ISR-safe APIs and priority-aware deferred queues), sharing data between ISRs and main code (volatile, masking, critical sections, and ISR-safe ring buffers), hardware timers for periodic events, and measuring and bounding interrupt latency and jitter. Includes polling versus interrupt-driven I/O, interrupt storms, DMA with interrupt thresholds for sustained data streams, and multicore interrupt routing. Excludes RTOS scheduling theory and schedulability analysis, general concurrency primitives and lock-free algorithms, serial-bus or peripheral driver protocols, and general-purpose OS interrupt handling such as kernel softirqs and bottom halves.
A noisy sensor line floods the CPU with interrupts, the main loop starves and the watchdog resets the device. How do you confirm it is an interrupt storm, stop the damage, and prevent a repeat?
Sample Answer
What an interrupt storm is, and why it resets the device
An interrupt storm is an interrupt that fires so often that the CPU spends nearly all its time in the handler. Two usual causes: noise on an edge-sensitive input (one that requests an interrupt on each voltage transition, so every glitch is a request) and a level-triggered line (one that stays active as long as the cause exists) whose cause the handler never clears, so the request re-asserts the moment the handler returns. The main loop gets no time, it stops servicing the watchdog (a hardware timer that resets the chip unless the software restarts it regularly), and the watchdog resets the device. That matches the story in the question.
CPU load of a storm is the interrupt rate times the cost of one handler call, divided by the clock rate. With an assumed all-in cost of 100 cycles on a 100 MHz core: 100 kHz of noise costs 10 percent, 500 kHz costs 50 percent, and 1 MHz is 100 percent (a stuck level line can re-fire at roughly that back-to-back rate). Starvation does not need a high percentage on the sensor alone: if the handler is above the priority of the code that kicks the watchdog, only the headroom left matters.
1. Confirm that it is a storm
Work through these in order. Each narrows the cause:
- Count, do not guess. Add a counter per interrupt source in the handler and a periodic task that reports the rate (or read it with the debugger). A rate far above anything the sensor can legitimately produce points at the storm and names the IRQ.
- Check main-loop progress. A free-running progress counter in the main loop that stops advancing while the interrupt counter races is the starvation signature.
- Halt the core several times in the debugger. If every halt lands inside the same ISR, or in the few instructions between returns, it is storming. Read the NVIC pending register: a pending bit that is set again right after every return means the request is still asserted.
- Scope the sensor line and a GPIO toggled at ISR entry. A stuck-high level line looks like a flat line with the ISR GPIO at a near 100 percent duty cycle. Noise looks like a ragged line with many short pulses. This distinguishes "cause never cleared" from "noise or a broken sensor".
- Read the reset cause register at boot (vendor-specific) to confirm the watchdog did the resetting, and log how many resets were storm-related.
2. Stop the damage at run time
The containment design is a detector at a priority above the storming source, so it can still run, that masks only the offending source:
- Count the source's interrupts per fixed period (a periodic timer interrupt such as SysTick, running at a higher priority than the sensor).
- If the count exceeds a threshold, disable that one interrupt in the NVIC (
ICER), clear its pending bit (ICPR) and set an error flag. Clearing the pending bit matters: without it, re-enabling later fires one stale request immediately. - Let the main loop log the event and, after a back-off period, re-enable the source. If it trips again several times in a row, keep it disabled and move the device to a degraded or safe mode.
- Keep servicing the watchdog from the main loop's health check, not from a timer ISR; otherwise the watchdog stays quiet while the application is starved, and hides the problem.
Choosing the threshold: limit = ceil(max legitimate rate x period x margin). For a sensor that can legitimately interrupt at 1 kHz, a 10 ms period and a margin of 4, the limit is 40 interrupts per period.
Executed demonstration
NVIC is the Nested Vectored Interrupt Controller, the Cortex-M hardware block that enables, prioritises and tracks pending interrupts. Its registers used below are ISER (set-enable), ICER (clear-enable, i.e. mask), ISPR (set-pending) and ICPR (clear-pending). The program models a stuck line by having the sensor handler pend its own interrupt again every time it runs, and the SysTick handler pend it again every tick, so the line is still asserted even while the NVIC has it masked, with SysTick (the Cortex-M system timer, a down-counter that fires an interrupt each time it wraps) at higher priority than the sensor. Without the guard, the main loop never runs. With it (-DWITH_GUARD), the detector trips and masks the source.
board.h:
#include <stdint.h>
#define REG(a) (*(volatile uint32_t *)(a))
#define REG8(a) (*(volatile uint8_t *)(a))
#define UART0_DR REG(0x4000C000)
#define UART0_CR REG(0x4000C030)
#define NVIC_ISER(n) REG(0xE000E100 + 4 * (n))
#define NVIC_ICER(n) REG(0xE000E180 + 4 * (n))
#define NVIC_ISPR(n) REG(0xE000E200 + 4 * (n))
#define NVIC_IPR(i) REG8(0xE000E400 + (i))
#define SHPR3_PRI15 REG8(0xE000ED23) /* SysTick priority byte (SHPR3 bits 31:24; 0xE000ED22 is PendSV) */
#define SYST_CSR REG(0xE000E010)
#define SYST_RVR REG(0xE000E014)
#define SYST_CVR REG(0xE000E018)
#define SCB_AIRCR REG(0xE000ED0C)
#define SCB_CFSR REG(0xE000ED28)
#define SCB_HFSR REG(0xE000ED2C)
#define SCB_BFAR REG(0xE000ED38)
#define SCB_SHCSR REG(0xE000ED24)
#define SCB_CCR REG(0xE000ED14)
static __attribute__((unused)) void putc_(char c) { UART0_DR = (uint32_t)c; }
static __attribute__((unused)) void puts_(const char *s) { while (*s) putc_(*s++); }
static __attribute__((unused)) void puthex(uint32_t v) {
puts_("0x");
for (int i = 28; i >= 0; i -= 4) putc_("0123456789abcdef"[(v >> i) & 15]);
}
static __attribute__((unused)) void putdec(uint32_t v) {
char b[11]; int n = 0;
do { b[n++] = '0' + v % 10; v /= 10; } while (v);
while (n) putc_(b[--n]);
}
static __attribute__((unused)) void exit_qemu(void) {
register uint32_t r0 __asm("r0") = 0x18, r1 __asm("r1") = 0x20026;
__asm volatile("bkpt 0xAB" :: "r"(r0), "r"(r1));
for (;;) {}
}
A walk through board.h: REG(a) turns an address into a volatile 32-bit memory-mapped register, so each read or write really reaches the hardware. UART0_DR and UART0_CR are the serial port's data and control registers, used only to print the result. NVIC_ISER, NVIC_ICER and NVIC_ISPR are three of those register banks (bank n covers interrupts 32n to 32n+31); the fourth, ICPR, has no macro and is written at its address, 0xE000E280, directly. NVIC_IPR(i) is the priority byte of interrupt i, and SHPR3_PRI15 is the priority byte of SysTick (exception 15), byte 3 of the SHPR3 register at 0xE000ED20, so its address is 0xE000ED23 (byte 2, 0xE000ED22, belongs to PendSV, exception 14); in both, a smaller number is more urgent. The SYST_* macros are SysTick's control, reload and current-value registers. The SCB_* registers and exit_qemu are support for other programs and for ending the run through semihosting, and play no part in the storm logic.
storm.c:
#include "board.h"
#define IRQ_SENSOR 10
#define TICKS_TO_RUN 20
#define STORM_LIMIT 200 /* interrupts allowed per SysTick period */
static volatile uint32_t irq_this_tick, ticks, main_progress;
static volatile uint32_t storm_tripped, masked, irqs_after_mask;
/* The sensor handler never removes the cause, so the request stays active, like a
level-triggered line stuck asserted. The stuck line is modelled by pending the
IRQ again from inside the handler. */
void sensor_isr(void) {
irq_this_tick++;
if (masked) irqs_after_mask++;
NVIC_ISPR(0) = 1u << IRQ_SENSOR;
}
static void report(void) {
puts_("ticks="); putdec(ticks);
puts_(" main_loop_ran="); puts_(main_progress ? "yes" : "no");
puts_(" storm_tripped="); putdec(storm_tripped);
puts_(" sensor_irqs_after_mask="); putdec(irqs_after_mask);
puts_("\n");
exit_qemu();
}
void systick_isr(void) {
ticks++;
#ifdef WITH_GUARD
if (irq_this_tick > STORM_LIMIT && !masked) {
NVIC_ICER(0) = 1u << IRQ_SENSOR; /* mask only the offending source */
REG(0xE000E280) = 1u << IRQ_SENSOR; /* NVIC_ICPR: drop the stale pending request */
masked = 1; storm_tripped = 1;
}
#endif
NVIC_ISPR(0) = 1u << IRQ_SENSOR; /* the stuck line is still asserted, masked or not */
irq_this_tick = 0;
if (ticks == TICKS_TO_RUN) report();
}
int main(void) {
UART0_CR = 0x301;
NVIC_IPR(IRQ_SENSOR) = 0x40;
SHPR3_PRI15 = 0x20; /* SysTick more urgent than the sensor */
SYST_RVR = 50000 - 1; SYST_CVR = 0; SYST_CSR = 7; /* reload, clear counter, enable | tick interrupt | core clock */
NVIC_ISER(0) = 1u << IRQ_SENSOR;
NVIC_ISPR(0) = 1u << IRQ_SENSOR; /* the line goes active */
for (;;) { main_progress++; } /* the application's main loop */
}
void reset(void) { main(); }
__attribute__((section(".vectors"), used)) void (*const vectors[16 + 16])(void) = {
[0] = (void *)0x20010000, [1] = reset, [15] = systick_isr,
[16 + IRQ_SENSOR] = sensor_isr };
Built with arm-none-eabi-gcc -O2 -mcpu=cortex-m3 -mthumb -nostartfiles -ffreestanding -Wl,--section-start=.vectors=0x0 -Wl,-Ttext=0x400 -Wl,-e,reset -Wl,-Tbss=0x20000000 storm.c -o storm.elf (GCC 14.2.1), with and without -DWITH_GUARD, and run with qemu-system-arm -M lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel storm.elf (QEMU 10.0.13). The output is deterministic:
unguarded:
ticks=20 main_loop_ran=no storm_tripped=0 sensor_irqs_after_mask=0
guarded:
ticks=20 main_loop_ran=yes storm_tripped=1 sensor_irqs_after_mask=0
In main, SYST_RVR = 50000 - 1 makes SysTick count 50000 clock ticks from reload to zero before it fires (the reload value is one less than the period), and SYST_CSR = 7 sets three bits: enable the counter (bit 0), raise the interrupt at zero (bit 1) and count the processor clock (bit 2). The sensor's priority byte 0x40 is numerically larger than SysTick's 0x20, so SysTick is the more urgent one and can interrupt the sensor handler. The self-pending write in sensor_isr stands in for a level-triggered line whose cause is never cleared: the request is asserted again as soon as the handler returns. Unguarded, 20 SysTick periods go by and the main loop has not executed once: the pending bit is set again every time the handler returns, so the CPU goes from handler to handler. Guarded, the detector masks the source and the main loop runs. sensor_irqs_after_mask=0 shows the masked source did not fire again. Because the SysTick handler keeps re-asserting the line, it is the mask (ICER), not the pending clear (ICPR), that silences the source: with the ICER line deleted the source fires again and the main loop starves, so the guard visibly depends on the mask. The pending clear matters for the case where the cause has gone away: without it, re-enabling the source later fires one stale request at once. The unguarded: and guarded: labels are added here to name the two builds. QEMU shows this ordering and starvation; the real timing and the actual interrupt rates need the target.
3. Prevent a repeat: remove the storm at its source
Ordered from cheapest and most robust, so try the first two before the rest: items 1 and 2 remove the cause, and items 3 to 7 limit the damage when the cause cannot be removed.
- Fix the electrical cause. A Schmitt-trigger input (one with built-in hysteresis, so a slowly moving or noisy signal switches cleanly once), an RC low-pass filter, a series resistor, proper pull-ups or shielding on the sensor cable. Many parts also offer an input glitch filter or a timer-capture filter in hardware; use it.
- Make the handler clear the cause, and choose the correct sensitivity (edge or level) for the signal. A level-triggered line without a cleared cause is the stuck-line storm above.
- Coalesce (merge many requests into one). The ISR records the event, disables its own interrupt, and the main loop re-arms it after processing. One interrupt per processing cycle, regardless of noise.
- Throttle in software with the detector above as a backstop.
- Turn the interrupt into polling for noisy, low-value inputs: read the pin from a periodic timer at a fixed rate. Work per second is then bounded by design, not by noise.
- Apply backpressure to the sensor (make the producer slow down instead of the CPU absorbing everything). For a sensor that produces data, lower its output rate, or use its FIFO (a small hardware queue) and a watermark interrupt (one raised only when the FIFO holds a set number of samples) so one interrupt delivers many samples.
- Rank priorities so that other interrupt-level work (a control tick, a safety ISR) cannot be starved by a sensor: give the sensor ISR a lower priority than any ISR that must keep running. Priorities do not protect thread-level code: the main loop, where the watchdog is kicked, runs below every ISR, so a storm at any priority still starves it. Only the run-time detector and items 1 to 6 protect the main loop.
4. How to test the throttle
- Inject the fault deliberately. Drive the input at a multiple of the legitimate maximum rate (a function generator at, say, 10 times) and hold the line stuck-active; the demo above is the same idea in software.
- Assert behaviour, not just survival: the detector trips within one period, the main loop's progress counter keeps advancing, the watchdog does not reset, CPU load stays bounded, the event is logged, and after the back-off the source is re-armed (and trips again if the storm continues).
- Test both shapes: noise (many short pulses) and a stuck level.
- Check the cost of masking. Confirm what the application loses while the source is off (for example sensor data) and that the degraded mode is acceptable.
An embedded system has a sensor ISR that must respond within 50 microseconds, a comms ISR with a 200 microsecond budget, and low-priority housekeeping interrupts, with nesting allowed. Lay out your priority assignment, masking approach and worst-case nesting depth, and say where long work goes.
Sample Answer
Design in one paragraph. Give each class its own preemption level (the part of an interrupt's priority that decides whether it can interrupt another handler; on Cortex-M a smaller number is more urgent), ordered by deadline: the sensor ISR (interrupt service routine) most urgent, the comms ISR next, all housekeeping interrupts at one shared, least-urgent level. Use BASEPRI (the base priority mask: it blocks interrupts at or below a chosen urgency and leaves more urgent ones running) for every critical section in thread code, set at the comms level so the sensor ISR is never masked. Keep every ISR to "clear the source, move the data, set a flag", and push long work into the main loop or a task. Worst-case nesting is then three exception levels deep.
Assumptions the numbers depend on (the question gives only the three deadlines). Cortex-M3 at 48 MHz with zero-wait-state memory, so one cycle is 1/48 microsecond (20.8 ns). The Cortex-M3 Technical Reference Manual (Arm DDI 0337G, section 5.5, "Pre-emption", Figure 5-2) shows a 12-cycle latency from asserting the interrupt to the first ISR instruction executing (the vector read and the load of the first instruction run in parallel with the register push). The manual's figure covers entry only, so the 12-cycle exit cost used below is a planning assumption, not a quoted figure. That is 0.25 us at 48 MHz. The other figures are planning assumptions to be replaced by measurements: the sensor ISR body takes 8 us and the sensor fires at most once per 250 us; the comms ISR body takes 60 us and fires at most once per 1 ms; a housekeeping ISR body takes at most 20 us, and all the housekeeping interrupts together fire at most once per 10 ms; thread code never holds BASEPRI longer than 5 us; the instruction in progress when an interrupt arrives can delay entry by up to 12 cycles (0.25 us); exiting an ISR costs 12 cycles. "Response" means from the line being asserted to the ISR having done its time-critical work. One sensor event, traced: the line is asserted at time 0; up to 0.25 us passes while the instruction in progress finishes; 0.25 us of entry latency follows; the 8 us body runs; the response is complete at 8.5 us, well inside the 50 us deadline.
Priority and masking plan.
| Interrupt | Preemption level | Value (3 implemented bits shown) | Masked by thread-code BASEPRI? | Long work goes to |
|---|---|---|---|---|
| Sensor, 50 us | 1 (most urgent) | 0x20 | No: BASEPRI is set to 0x60 | Nothing long: read, timestamp, set flag |
| Comms, 200 us | 2 | 0x60 | Yes | Packet processing in a task, data moved by DMA |
| Housekeeping (several) | 3, all the same level | 0xE0 | Yes | Flag or notification, work in the main loop |
Housekeeping interrupts share a level on purpose: interrupts in the same preemption group cannot preempt one another, so they add one level of nesting in total, not one each. PRIGROUP (the priority-grouping field that splits the priority byte into preemption and subpriority parts) is set so that all implemented bits are preemption bits (no subpriority). The comms and housekeeping levels in the table are examples of such preemption levels: level 2 and level 3 are different groups, so comms can preempt housekeeping. Shared data with the sensor ISR cannot be protected by BASEPRI (the sensor ISR runs through it), so use single-writer variables, retry reads or a PRIMASK section of a few instructions, and add that time to the sensor's budget.
Worst-case response, computed.
- Sensor. Nothing less urgent can delay it except the instruction in progress and its own entry: 0.25 (instruction in progress) + 0.25 (entry) + 8 (body) = 8.5 us, which is 408 cycles at 48 MHz. Budget 50 us, margin 41.5 us. It meets the budget as long as events are at least 8.5 us apart, because an ISR cannot preempt itself; at the assumed 250 us minimum spacing that holds.
- Comms. Waiting for a BASEPRI section (5 us), plus its own 0.25 + 0.25 + 60, plus every sensor ISR that lands inside its window, each costing entry + body + exit = 0.25 + 8 + 0.25 = 8.5 us. At most one sensor event fits in a window of about 74 us when events are 250 us apart: 0.25 + 0.25 + 60 + 5 + 8.5 = 74.0 us, or 3,552 cycles. Budget 200 us, margin 126 us. The count of sensor events is ceil(74 / 250) = 1, which confirms the assumption used in the sum. Housekeeping adds nothing here, because comms preempts it.
- Total interrupt load. Each term is body time divided by minimum period, using the assumed rates (sensor once per 250 us, comms once per 1000 us, housekeeping once per 10,000 us): 8/250 + 60/1000 + 20/10000 = 3.2% + 6.0% + 0.2% = 9.4% of the CPU. Counting entry and exit as well (0.5 us per interrupt) gives 8.5/250 + 60.5/1000 + 20.5/10000 = 3.4% + 6.05% + 0.205% = 9.655%, about 9.7%.
These are an interference sum with stated inputs, not a measurement. If the sensor could fire faster than every 250 us, the count in the comms line goes up and must be recomputed.
Worst-case nesting depth and stack. The deepest chain is housekeeping, preempted by comms, preempted by the sensor ISR: three exception levels, so at most three frames on the stack on top of whatever the interrupted thread code was using. The hardware pushes eight registers per exception (xPSR, PC, LR, r12, r3 to r0), 32 bytes (the Cortex-M3 Devices Generic User Guide, Arm DUI 0552A, section 2.3.7, describes the stack frame as eight data words), and with the STKALIGN bit set (a bit in the configuration and control register, CCR) the hardware inserts one extra 4-byte word when the interrupted code's stack pointer is only 4-byte aligned, so that the stack stays 8-byte aligned. The run below shows the frame size and the three levels directly. It runs on a Cortex-M3 in QEMU (lm3s6965evb); it checks the structure, not timing, and the support header mini.h and linker script mini.ld are listed after the answer text.
#include "mini.h"
/* Three nested exception levels: housekeeping (IRQ2) is preempted by comms (IRQ1), which is preempted by the sensor (IRQ0). */
static volatile uint32_t sp_main, sp_hk, sp_comms, sp_sensor;
static inline uint32_t get_sp(void) { uint32_t s; __asm__ volatile("mov %0, sp" : "=r"(s)); return s; }
static void pend(int irq) { ISPR0 = 1u << irq; DSB(); ISB(); }
void IRQ0_Handler(void) { sp_sensor = get_sp(); } /* sensor: most urgent */
void IRQ1_Handler(void) { sp_comms = get_sp(); pend(0); } /* comms raises the sensor line while it runs */
void IRQ2_Handler(void) { sp_hk = get_sp(); pend(1); } /* housekeeping raises the comms line while it runs */
int main(void) {
AIRCR = 0x05FA0000u | (4u << 8); /* all implemented bits are preemption bits */
IPR8(0) = 0x20; IPR8(1) = 0x60; IPR8(2) = 0xE0;
ISER0 = 7;
sp_main = get_sp();
pend(2);
puts_("SP in thread code "); puthex(sp_main); putc_('\n');
puts_("SP in housekeeping ISR "); puthex(sp_hk); puts_(" below thread by "); putdec(sp_main - sp_hk); putc_('\n');
puts_("SP in comms ISR "); puthex(sp_comms); puts_(" below previous by "); putdec(sp_hk - sp_comms); putc_('\n');
puts_("SP in sensor ISR "); puthex(sp_sensor); puts_(" below previous by "); putdec(sp_comms - sp_sensor); putc_('\n');
puts_("CCR STKALIGN="); putdec((REG(0xE000ED14u) >> 9) & 1); putc_('\n');
quit();
}
arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -O1 -Wall -Wextra -ffreestanding -nostdlib -T mini.ld -o nest_stack.elf nest_stack.c -lgcc
qemu-system-arm -M lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel nest_stack.elf
Output (Arm GNU Toolchain GCC 14.2.1, QEMU 10.0.13; deterministic):
SP in thread code 0x2000fff0
SP in housekeeping ISR 0x2000ffd0 below thread by 32
SP in comms ISR 0x2000ffb0 below previous by 32
SP in sensor ISR 0x2000ff90 below previous by 32
CCR STKALIGN=1
Each level is exactly 32 bytes below the previous one, because at -O1 (and -O2) these leaf handlers push nothing of their own. The figure holds only at that optimisation level: built with -O0 the same program prints 56 bytes per level, because the unoptimised handlers save r7 and lr and get_sp is a real call that pushes its own registers before it samples the stack pointer. STKALIGN=1 is consistent with that: the thread's stack pointer (0x2000fff0) was already a multiple of 8, so no padding word was inserted. The 4-byte alignment words in the budget below cover the case where an interrupted stack pointer is not a multiple of 8, which can happen at each of the three entries. Real handlers add saved registers and locals; assume 24 bytes for the sensor ISR, 64 for comms and 48 for housekeeping, to be replaced by the per-function figures from -fstack-usage (a GCC option that writes each function's stack use to a .su file) and a stack-fill measurement:
| Part | Bytes |
|---|---|
| Three hardware frames, 3 x 32 | 96 |
| Software pushes and locals, 24 + 64 + 48 | 136 |
| Possible alignment words, up to one 4-byte word per frame (a handler can be entered while its stack pointer is only 4-byte aligned, for example part-way through a prologue), 3 x 4 | 12 |
| Subtotal | 244 |
| With a 25% margin (244 x 1.25 = 305) | 305, rounded up to 312 (a multiple of 8 for stack alignment), then to a round 320 |
So reserve about 320 bytes of interrupt stack, plus the depth of the thread code if it shares the same stack. If an RTOS runs its tasks on a separate stack, the interrupt stack is only the 320 bytes. Adding a fourth preemption level costs one more frame plus its handler's usage.
Where the long work goes. Anything over a few microseconds leaves the ISR. The comms ISR validates the frame header and hands a buffer index to a task; for bursty network traffic let DMA (hardware that copies data without the CPU) fill a ring of packet buffers and interrupt once per packet or per half ring, so the ISR never copies payload. The housekeeping ISRs set a flag or send an RTOS notification and the work runs in the main loop.
How to validate it on the target (QEMU cannot show cycles). Toggle a GPIO pin at entry and exit of each ISR and capture it with a logic analyser while injecting worst-case sensor and comms traffic at once; or read the DWT cycle counter (CYCCNT, a free-running register in the Cortex-M3's Data Watchpoint and Trace unit that counts processor cycles) at entry and exit. Record the maximum over a long soak, not the average, compare it with the 50 us, 200 us and 1 ms bounds, and fill the interrupt stack with a known pattern and check how much of it was overwritten.
What would flip the design: if the sensor must also run kernel calls, it has to sit at or below the RTOS ceiling and be masked by kernel critical sections, which adds their length to its 8.5 us; if a measured comms body pushes its response estimate toward 200 us, split the body and defer the rest to a task.
Support files for the run above. mini.h provides the register addresses (IPR8(i) sets interrupt i's priority byte, ISER0 enables interrupts, ISPR0 marks one pending, AIRCR holds the PRIGROUP field), the UART print helpers, and the vector table, the list of handler addresses the core reads at start; handlers the program does not define are weak placeholders resolving to 0. mini.ld puts the vectors and code in flash at address 0 and data in RAM, and NOLOAD on .bss means the section takes RAM but stores nothing in the file.
/* mini.h: just enough start-up for a Cortex-M3 (QEMU lm3s6965evb). QEMU loads the ELF straight into RAM, so there is no .data copy from flash and no .bss clearing (RAM starts zeroed). A real board needs both. */
#include <stdint.h>
#pragma GCC diagnostic ignored "-Wunused-function"
#define REG(a) (*(volatile uint32_t *)(a))
#define IPR8(i) (*(volatile uint8_t *)(0xE000E400u + (i)))
#define ISER0 REG(0xE000E100u)
#define ISPR0 REG(0xE000E200u)
#define ICSR REG(0xE000ED04u)
#define VTOR REG(0xE000ED08u)
#define AIRCR REG(0xE000ED0Cu)
#define DSB() __asm__ volatile("dsb" ::: "memory")
#define ISB() __asm__ volatile("isb" ::: "memory")
#define CPSID() __asm__ volatile("cpsid i" ::: "memory")
#define CPSIE() __asm__ volatile("cpsie i" ::: "memory")
static void putc_(char c) { REG(0x4000C000u) = (uint32_t)c; } /* UART0 data register */
static void puts_(const char *s) { while (*s) putc_(*s++); }
static void puthex(uint32_t v) { puts_("0x"); for (int i = 28; i >= 0; i -= 4) putc_("0123456789abcdef"[(v >> i) & 15]); }
static void putdec(uint32_t v) { char b[11]; int n = 0; do b[n++] = '0' + v % 10; while (v /= 10); while (n) putc_(b[--n]); }
static void quit(void) { /* semihosting SYS_EXIT */
register uint32_t r0 __asm__("r0") = 0x18, r1 __asm__("r1") = 0x20026;
__asm__ volatile("bkpt 0xab" :: "r"(r0), "r"(r1)); for (;;) {}
}
int main(void);
extern uint32_t _estack;
static void Reset_Handler(void) { REG(0x4000C030u) = (1u << 0) | (1u << 8) | (1u << 9); /* UART0 CTL: enable, TX, RX */ main(); for (;;) {} }
/* Handlers a program does not define stay weak and resolve to 0 (never taken in these programs). */
#define WEAK(n) void n(void) __attribute__((weak))
WEAK(NMI_Handler); WEAK(HardFault_Handler); WEAK(SVC_Handler); WEAK(PendSV_Handler); WEAK(SysTick_Handler);
WEAK(IRQ0_Handler); WEAK(IRQ1_Handler); WEAK(IRQ2_Handler);
__attribute__((section(".vectors"), used)) static const void *const vectors[16 + 3] = {
&_estack, Reset_Handler, NMI_Handler, HardFault_Handler, 0, 0, 0, 0, 0, 0, 0, SVC_Handler, 0, 0, PendSV_Handler, SysTick_Handler,
IRQ0_Handler, IRQ1_Handler, IRQ2_Handler };
MEMORY { FLASH (rx) : ORIGIN = 0x0, LENGTH = 256K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 64K }
SECTIONS {
.vectors : { KEEP(*(.vectors)) } > FLASH
.text : { *(.text*) *(.rodata*) } > FLASH
.data : { *(.data*) } > RAM
.bss (NOLOAD) : { *(.bss*) *(COMMON) } > RAM
_estack = ORIGIN(RAM) + LENGTH(RAM);
}
Technical deep-dive: Describe how tail-chaining and lazy stacking (floating-point stacking) interact on an ARM Cortex-M with FPU enabled. What hazards exist when an ISR that uses FP registers preempts another FP-using context, and how can you mitigate stack and latency costs while preserving correctness?
Sample Answer
The mechanism, in the order it happens
Terms: stacking is the hardware pushing the interrupted code's registers onto the stack when an exception starts. Tail-chaining is the hardware skipping the pop-then-push when one interrupt finishes while another is already pending: it starts the next handler directly, with the original stack frame left in place. FPU is the floating-point unit; on a Cortex-M4F or M7 it adds the registers s0 to s31 and the status register FPSCR.
- Basic frame. Without FP state in use, exception entry pushes 8 words (32 bytes):
r0-r3, r12, LR, PC, xPSR. - Extended frame. If the interrupted code has live FP state (the
CONTROL.FPCAbit, the Floating-Point Context Active flag in the CONTROL register, is set because the code executed an FP instruction), entry also reserves room fors0-s15,FPSCRand one reserved word: 26 words (104 bytes) in all, 18 words more than the basic frame.EXC_RETURN(the special value placed inLRon entry) records which frame was used: bit 4 clear means extended. FreeRTOS's Cortex-M4F context switch tests that same bit (tst r14, #0x10) to decide whether to saves16-s31itself, because the hardware frame covers onlys0-s15(r14is another name for LR, and bit 4 ofEXC_RETURNis 0x10). - Lazy stacking (control bits in
FPCCR, the floating-point context control register:ASPEN, automatic state preservation enable, bit 31, makes the hardware preserve FP state on exception entry whenFPCAis set;LSPEN, lazy state preservation enable, bit 30, makes that preservation lazy). With both set the hardware reserves the space but does not copy the FP registers. It records the slot address inFPCAR(the FP context address register, which holds where the registers will be saved) and setsFPCCR.LSPACT(lazy state preservation active: space reserved, registers not yet copied). The copy happens only if the handler (or something that preempts it) executes its first FP instruction. Then the registers are written to the reserved slot andLSPACTclears. If no FP instruction runs, the 18 extra words are never moved and the exception costs the same as a non-FP one. - Tail-chaining does not restack, so the reserved slot and the
LSPACTstate belong to the original entry. If handler A (no FP) is followed by handler B (FP) in a chain, B's first FP instruction saves the thread's registers into the slot reserved at the start.
With ASPEN set and LSPEN clear, the FP registers are copied at entry whenever the interrupted code has live FP state (FPCA set), instead of at the handler's first FP instruction. That costs more at entry but removes the dependence on whether the handler itself touches FP. If the interrupted code had no FP state, a basic frame is pushed and nothing is copied. Adding FPCCR &= ~(1u << 30); (clear LSPEN) before the NVIC_IPR(IRQ_FP) = 0x40; line of the first program below and running it in the same QEMU build, the thread-uses-FP run prints FPCCR 0x80000000 (no LSPACT) at entry and after the handler's FP use, with the same 0x70 stack distance, and the -DNO_THREAD_FP run prints EXC_RETURN 0xfffffff9 and a 0x28 distance. That output does not show the copy happening at entry; copying at entry is the architectural behaviour of LSPEN clear, and a cycle counter on silicon is the way to see its cost.
Executed check of the mechanism
The programs below use two small helpers. semi makes a semihosting call: the bkpt 0xAB instruction asks the debugger or emulator to perform a host service, with the operation number in r0 (4 is SYS_WRITE0, print a zero-terminated string; 0x18 is SYS_EXIT) and its argument in r1. puthex builds a string from a label plus a 32-bit value in hex and prints it. CPACR (the Coprocessor Access Control Register) must have the CP10 and CP11 fields set (bits 20 to 23) before any FP instruction, because the FPU is coprocessors 10 and 11 and access to them is off at reset.
A Cortex-M4 (QEMU machine mps2-an386, QEMU 10.0.13), built with arm-none-eabi-gcc -O1 -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -mthumb -nostartfiles -ffreestanding -Wl,--section-start=.vectors=0x0 -Wl,-Ttext=0x400 -Wl,-e,reset -Wl,-Tbss=0x20000000 (GCC 14.2.1). The thread uses FP, then an interrupt whose handler uses FP preempts it; the program prints EXC_RETURN, FPCCR at entry and after the first FP instruction, and the distance between the thread's stack pointer and the handler's.
#include <stdint.h>
#define REG(a) (*(volatile uint32_t *)(a))
#define FPCCR REG(0xE000EF34)
#define CPACR REG(0xE000ED88)
#define NVIC_ISER0 REG(0xE000E100)
#define NVIC_ISPR0 REG(0xE000E200)
#define NVIC_IPR(i) (*(volatile uint8_t *)(0xE000E400 + (i)))
#define IRQ_FP 10
static void semi(uint32_t op, const void *arg) {
register uint32_t r0 __asm("r0") = op; register const void *r1 __asm("r1") = arg;
__asm volatile("bkpt 0xAB" :: "r"(r0), "r"(r1) : "memory");
}
static void puts_(const char *s) { semi(4, s); } /* SYS_WRITE0 */
static void puthex(const char *label, uint32_t v) {
char b[64]; int n = 0;
while (*label) b[n++] = *label++;
b[n++] = '0'; b[n++] = 'x';
for (int i = 28; i >= 0; i -= 4) b[n++] = "0123456789abcdef"[(v >> i) & 15];
b[n++] = '\n'; b[n] = 0; puts_(b);
}
static volatile uint32_t sp_before, sp_in_isr, lr_in_isr, fpccr_entry, fpccr_after_fp;
void fp_isr(void) {
uint32_t lr, sp;
__asm volatile("mov %0, lr" : "=r"(lr));
__asm volatile("mov %0, sp" : "=r"(sp));
lr_in_isr = lr;
sp_in_isr = sp;
fpccr_entry = FPCCR;
volatile float x = 1.5f; /* first FP instruction in the ISR */
x = x * 2.0f;
fpccr_after_fp = FPCCR;
}
int main(void) {
puthex("FPCCR at reset (before any setup): ", FPCCR);
CPACR |= (0xFu << 20); /* enable CP10 and CP11 */
__asm volatile("dsb; isb");
puthex("FPCCR after enabling CP10/CP11: ", FPCCR);
NVIC_IPR(IRQ_FP) = 0x40;
NVIC_ISER0 = 1u << IRQ_FP;
#ifndef NO_THREAD_FP
volatile float t = 3.0f; t = t * t; /* the thread now owns live FP state */
#endif
uint32_t sp; __asm volatile("mov %0, sp" : "=r"(sp)); sp_before = sp;
NVIC_ISPR0 = 1u << IRQ_FP;
__asm volatile("dsb; isb");
puthex("EXC_RETURN seen in ISR: ", lr_in_isr);
puthex("FPCCR at ISR entry: ", fpccr_entry);
puthex("FPCCR after first FP use in ISR: ", fpccr_after_fp);
puthex("bytes between thread SP and ISR SP: ", sp_before - sp_in_isr);
puts_("done\n");
register uint32_t r0 __asm("r0") = 0x18, r1 __asm("r1") = 0x20026;
__asm volatile("bkpt 0xAB" :: "r"(r0), "r"(r1));
return 0;
}
void reset(void) { main(); for (;;) {} }
__attribute__((section(".vectors"), used)) void (*const vectors[16 + 16])(void) = {
[0] = (void *)0x20010000, [1] = reset, [16 + IRQ_FP] = fp_isr };
Run: qemu-system-arm -M mps2-an386 -nographic -semihosting-config enable=on,target=native -kernel fpu_lazy.elf. First with the thread using FP, then built again with -DNO_THREAD_FP (thread never touches FP):
== thread uses FP
FPCCR at reset (before any setup): 0xc0000000
FPCCR after enabling CP10/CP11: 0xc0000000
EXC_RETURN seen in ISR: 0xffffffe9
FPCCR at ISR entry: 0xc0000019
FPCCR after first FP use in ISR: 0xc0000018
bytes between thread SP and ISR SP: 0x00000070
done
== thread never uses FP (-DNO_THREAD_FP)
FPCCR at reset (before any setup): 0xc0000000
FPCCR after enabling CP10/CP11: 0xc0000000
EXC_RETURN seen in ISR: 0xfffffff9
FPCCR at ISR entry: 0xc0000000
FPCCR after first FP use in ISR: 0xc0000000
bytes between thread SP and ISR SP: 0x00000028
done
(The == ... header lines are added here to label the two runs; the program does not print them.)
Reading it:
FPCCR = 0xc0000000at reset: 0xc0000000 is bits 31 and 30 set and nothing else, and bit 31 isASPENand bit 30 isLSPEN, so both are set and lazy stacking is on by default in this model.EXC_RETURNis0xffffffe9with FP state and0xfffffff9without: bit 4 is the frame-type flag.- At entry
FPCCR = 0x19: bit 0LSPACTis set (registers not yet copied), plus status bitsTHREAD(bit 3) andHFRDY(bit 4). QEMU's model reports only these two; the other ready bits (MMRDYbit 5,BFRDYbit 6 andMONRDYbit 8 in the CMSISFPCCRdefinitions) may also read 1 on silicon, depending on the fault priorities. After the handler's first FP instruction it is0x18:LSPACTcleared, the copy happened. - The stack distance differs by
0x70 - 0x28 = 72bytes = 18 words, the extra part of the extended frame (the remaining 40 bytes in each case are the 32-byte basic frame plus 8 bytes the handler reserves for its own local variable: this -O1 build startsfp_isrwithsub sp, #8, and the stack pointer is read after that).
Does the chain case preserve the thread's registers? A second program sets s0 = 3.0 in the thread, pends two same-priority interrupts at once, where A uses no FP and B overwrites s0 with 8.0, and prints the result:
#include <stdint.h>
#define REG(a) (*(volatile uint32_t *)(a))
#define FPCCR REG(0xE000EF34)
#define CPACR REG(0xE000ED88)
#define NVIC_ISER0 REG(0xE000E100)
#define NVIC_ISPR0 REG(0xE000E200)
#define NVIC_IPR(i) (*(volatile uint8_t *)(0xE000E400 + (i)))
static void semi(uint32_t op, const void *arg) {
register uint32_t r0 __asm("r0") = op; register const void *r1 __asm("r1") = arg;
__asm volatile("bkpt 0xAB" :: "r"(r0), "r"(r1) : "memory");
}
static void out(const char *label, uint32_t v) {
char b[64]; int n = 0;
while (*label) b[n++] = *label++;
b[n++] = '0'; b[n++] = 'x';
for (int i = 28; i >= 0; i -= 4) b[n++] = "0123456789abcdef"[(v >> i) & 15];
b[n++] = '\n'; b[n] = 0; semi(4, b);
}
static volatile uint32_t fpccr_a, fpccr_b_entry, fpccr_b_after;
void isr_a(void) { fpccr_a = FPCCR; } /* integer only */
void isr_b(void) { /* same priority, runs after A */
fpccr_b_entry = FPCCR;
__asm volatile("vmov.f32 s0, #8.0" ::: "s0"); /* clobbers the thread's s0 */
fpccr_b_after = FPCCR;
}
int main(void) {
CPACR |= (0xFu << 20);
__asm volatile("dsb; isb");
NVIC_IPR(10) = 0x40; NVIC_IPR(11) = 0x40;
NVIC_ISER0 = (1u << 10) | (1u << 11);
__asm volatile("vmov.f32 s0, #3.0" ::: "s0"); /* thread's live FP state */
NVIC_ISPR0 = (1u << 10) | (1u << 11); /* both pending at once */
__asm volatile("dsb; isb");
uint32_t s0_bits;
__asm volatile("vmov %0, s0" : "=r"(s0_bits));
out("FPCCR in ISR A (no FP use): ", fpccr_a);
out("FPCCR at ISR B entry: ", fpccr_b_entry);
out("FPCCR after FP use in ISR B: ", fpccr_b_after);
out("thread s0 after both ISRs: ", s0_bits);
register uint32_t r0 __asm("r0") = 0x18, r1 __asm("r1") = 0x20026;
__asm volatile("bkpt 0xAB" :: "r"(r0), "r"(r1));
return 0;
}
void reset(void) { main(); for (;;) {} }
__attribute__((section(".vectors"), used)) void (*const vectors[16 + 16])(void) = {
[0] = (void *)0x20010000, [1] = reset, [16 + 10] = isr_a, [16 + 11] = isr_b };
FPCCR in ISR A (no FP use): 0xc0000019
FPCCR at ISR B entry: 0xc0000019
FPCCR after FP use in ISR B: 0xc0000018
thread s0 after both ISRs: 0x40400000
Decoded: 0xc0000019 is ASPEN + LSPEN + LSPACT (bit 0) + the status bits THREAD and HFRDY; 0xc0000018 is the same with LSPACT clear. LSPACT stays set through A (nothing used FP), clears when B uses FP, and the thread's s0 is still 0x40400000, the bit pattern of 3.0f. Whether the model physically tail-chains between the two handlers is not visible from this output; what the output shows is the architectural result any correct implementation must give. The conclusion for the interaction: in a chain the thread's FP registers are saved at most once, by the first handler that executes an FP instruction, into the slot reserved at the original entry, and restored when the chain finally returns; handlers earlier in the chain that use no FP pay nothing for them.
QEMU does not model cycle cost, so none of the above says how many cycles the extra stacking takes; that needs a cycle counter (the DWT CYCCNT) on real silicon.
Hazards when an FP-using ISR preempts an FP-using context
- Variable latency inside the ISR. With lazy stacking the cost does not hit at entry but at the handler's first FP instruction, and only when the interrupted context had live FP state. The same handler therefore has different execution times depending on what it interrupted. For a handler with a tight deadline, that is jitter you must include.
- Stack growth per nesting level. Each preemption pushes one frame, and its size depends on the context being interrupted: 104 bytes if that context has FP state, 32 if not. Worked example: a thread with FP is preempted by ISR1, which is preempted by ISR2. That is two preemptions, so two frames. The first frame holds the thread's registers (the thread has FP state: 104 bytes). The second holds ISR1's registers: 32 bytes if ISR1 used no FP, 104 if it did. If ISR1 and ISR2 use no FP: 104 + 32 = 136 bytes of hardware frames. If ISR1 uses FP: 104 + 104 = 208 bytes, because once ISR1 executes an FP instruction its own context has FP state and the next level stacks the extended frame. These are minimum figures: when
CCR.STKALIGN(bit 9 of the configuration and control register) is set, the hardware adds one padding word (4 bytes) to a frame whenever the stack pointer it interrupted was not 8-byte aligned, which can happen when an interrupt lands in the middle of a function that has pushed an odd number of registers. Allow up to 4 more bytes per frame, and check the reset value of that bit on your part. (ISR2's own frame is pushed only if a third handler preempts it, and then costs 32 or 104 by the same rule.) Each handler's own locals and saved registers come on top. - Stack faults surface late. The lazy copy happens at the first FP instruction, so a stack that was too small for the reserved slot can fault there, not at entry. The fault status register (
CFSR) has dedicated flags for this:MLSPERR(CFSRbit 5, in the memory-management byte: a MemManage fault occurred during lazy state preservation) andLSPERR(CFSRbit 13, which is bit 5 of the bus-fault byte: a bus fault occurred during lazy state preservation), per the CMSIS definitions. - Callee-saved FP registers. Callee-saved means a called function must preserve them for its caller;
s16-s31are such registers and are not in the hardware frame. If an ISR's compiled code uses them, the compiler saves and restores them in its prologue like any function; an RTOS context switch must save them by hand (the FreeRTOS test above). - Hand-written assembly or a wrapper that treats the stacked frame as 8 words breaks on an extended frame. Any code that walks the stacked frame (fault decoders, RTOS port code) must test
EXC_RETURNbit 4 first.
Recommendation
- Keep FP out of ISRs. Capture raw integer data in the ISR (an ADC sample, a timer count), and do the floating-point work in a task or main loop. Then ISRs never trigger the lazy copy and their cost is constant, and every level of ISR-over-ISR nesting costs the 32-byte basic frame. The first preemption of a task that does use FP still reserves the 104-byte extended frame, so the worst case is 104 bytes for that first level plus 32 for each further level.
- If an ISR must use FP (a control loop in a timer interrupt, say), keep lazy stacking on, but measure the entry-to-completion time with and without FP state in the interrupted context on the target and budget the larger one. For a handler that must be deterministic above all, clear
LSPENand keepASPEN, so that whenever the interrupted code has live FP state the copy happens at entry and the handler's own execution time no longer depends on when it first touches FP: slower at entry, but the cost inside the handler is constant. - Size every stack with the extended frame at each possible nesting level (the worked example above), and place a guard region (a small no-access address range at the end of the stack, built with the MPU, the memory protection unit, where the core has one) under each task stack.
- Do not turn off
ASPENto save time unless you can prove that nothing running in any exception handler or task preempted by an exception ever touches FP: if one does, the interrupted context's FP registers get corrupted silently.
Explain the difference between a hardware interrupt and an exception (fault) on a CPU such as ARM Cortex-M. Give examples of exceptions and describe how their handling and semantics differ from asynchronous external interrupts.
Sample Answer
The distinction
If you remember three things: a hardware interrupt is asynchronous (it arrives at some instruction boundary regardless of what the code is doing), a fault is synchronous (one particular instruction caused it, so returning without fixing the cause repeats it), and a fault whose own handler cannot run is escalated to HardFault. The rest of this card shows each in a program.
On Cortex-M everything the core can be diverted to is called an exception, and each has a number (the value in the IPSR register, the Interrupt Program Status Register, a read-only register that holds the number of the exception being handled, or 0 in ordinary code): 1 Reset, 2 NMI, 3 HardFault, 4 MemManage, 5 BusFault, 6 UsageFault, 11 SVCall, 14 PendSV, 15 SysTick, and 16 and up the external interrupts (IRQ0 is exception 16). In ordinary usage, "interrupt" means the asynchronous kind raised by hardware outside the instruction stream (a peripheral line, a timer), and "fault" means the synchronous kind: a direct consequence of the instruction the core is executing (divide by zero, bad address, undefined instruction). Synchronous means the exception is raised by the instruction being executed; asynchronous means it arrives independently of the instruction stream. The Cortex-M3 Technical Reference Manual (ARM DDI 0337G) tags each one asynchronous or synchronous, and calls a BusFault synchronous when it is precise and asynchronous when it is imprecise. A precise BusFault is reported at the very instruction that made the bad access, so the stacked PC points at it. An imprecise one is reported later, typically because a store went into a write buffer and the bus error came back after the core had moved on, so the stacked PC points somewhere after the offending store.
The differences that matter in firmware:
- Cause and timing. An interrupt arrives at an arbitrary instruction boundary and has no relationship to what the code is doing. A fault is caused by one particular instruction.
- Where execution resumes. After an interrupt the core continues after the interrupted instruction. After a MemManage or UsageFault the manual says the return PC points to the faulting instruction, so simply returning repeats it and faults again unless the handler removed the cause (or skips the instruction, or resets the system).
- Enabling. An external interrupt is enabled per source in the NVIC. MemManage, BusFault and UsageFault each have an enable bit in SHCSR; while disabled, that fault goes to HardFault instead. SVCall, PendSV and SysTick are always available and only gated by priority.
- Escalation. Escalation means a fault being handled as HardFault instead of by its own handler. The manual describes HardFault as taking all classes of fault when the fault cannot activate, either because its priority does not allow it to run right now or because its configurable handler (the MemManage, BusFault or UsageFault one) is disabled. Interrupts never escalate.
- Diagnostics. A fault comes with status registers (CFSR, the Configurable Fault Status Register, with one bit per cause; HFSR, the HardFault Status Register; and the stacked registers, meaning the copies of r0-r3, r12, LR, PC and xPSR the core pushes on entry) saying what happened. An interrupt carries no such record.
- Software-triggered exceptions. SVC (a supervisor call, for example an RTOS service entry) is synchronous, and PendSV (a pended request used for deferred work such as context switching) is set by software but runs when its priority allows, like an interrupt.
Run it
The program triggers each kind and prints its exception number, then tests what PRIMASK (the global mask bit set by cpsid i) does to each.
#include <stdint.h>
#define REG(a) (*(volatile uint32_t *)(a))
#define NVIC_ISER REG(0xE000E100)
#define NVIC_ISPR REG(0xE000E200)
#define NVIC_IPR ((volatile uint8_t *)0xE000E400)
#define SCB_ICSR REG(0xE000ED04)
#define SCB_CCR REG(0xE000ED14)
#define SCB_SHCSR REG(0xE000ED24)
#define SCB_CFSR REG(0xE000ED28)
#define SCB_HFSR REG(0xE000ED2C)
static void puts_(const char *s) { while (*s) REG(0x4000C000) = *s++; }
static void putu(uint32_t v) { char b[11]; int i = 10; b[i] = 0; do { b[--i] = '0' + v % 10; v /= 10; } while (v); puts_(&b[i]); }
static void puth(uint32_t v) { puts_("0x"); for (int i = 28; i >= 0; i -= 4) REG(0x4000C000) = "0123456789abcdef"[(v >> i) & 15]; }
static void done(void) {
register uint32_t r0 __asm("r0") = 0x18, r1 __asm("r1") = 0x20026;
__asm volatile("bkpt 0xAB" :: "r"(r0), "r"(r1));
for (;;) {}
}
static uint32_t ipsr(void) { uint32_t v; __asm volatile("mrs %0, ipsr" : "=r"(v)); return v; }
static void log_(const char *who) { puts_(" "); puts_(who); puts_(": IPSR (exception number) = "); putu(ipsr()); puts_("\n"); }
static void sync(void) { __asm volatile("dsb\n isb" ::: "memory"); }
void nmi(void) { log_("NMI"); }
void svc(void) { log_("SVCall"); }
void pendsv(void) { log_("PendSV"); }
void systick(void) { log_("SysTick"); }
void irq0(void) { log_("external IRQ0"); }
void usagefault(void) {
log_("UsageFault"); puts_(" UFSR/CFSR = "); puth(SCB_CFSR); puts_("\n");
SCB_CFSR = SCB_CFSR; /* write 1 to clear the sticky bits */
SCB_CCR &= ~(1u << 4); /* stop trapping, so the retried divide completes */
}
void hardfault(void) {
log_("HardFault"); puts_(" HFSR = "); puth(SCB_HFSR); puts_(" CFSR = "); puth(SCB_CFSR); puts_("\n");
SCB_HFSR = SCB_HFSR; SCB_CFSR = SCB_CFSR;
SCB_CCR &= ~(1u << 4);
__asm volatile("cpsie i"); /* clear PRIMASK so the program can finish */
}
int main(void) {
NVIC_IPR[0] = 0x80; NVIC_ISER = 1;
volatile uint32_t zero = 0, q;
puts_("1. software-triggered:\n");
__asm volatile("svc 0");
SCB_ICSR = 1u << 28; sync(); /* PENDSVSET */
SCB_ICSR = 1u << 26; sync(); /* PENDSTSET */
NVIC_ISPR = 1; sync(); /* external interrupt */
puts_("2. fault with its handler enabled (UsageFault, divide by zero):\n");
SCB_SHCSR |= 1u << 18; SCB_CCR |= 1u << 4; /* USGFAULTENA, DIV_0_TRP */
q = 99; q = 10 / zero;
puts_(" divide retried after the handler, result (was 99) = "); putu(q); puts_("\n");
puts_("3. same fault with its handler disabled:\n");
SCB_SHCSR &= ~(1u << 18); SCB_CCR |= 1u << 4;
q = 10 / zero;
puts_("4. PRIMASK set, then NMI, PendSV, SysTick and IRQ0 are all requested:\n");
__asm volatile("cpsid i" ::: "memory");
SCB_ICSR = (1u << 31) | (1u << 28) | (1u << 26); NVIC_ISPR = 1; sync(); /* NMIPENDSET too */
puts_(" releasing PRIMASK\n");
__asm volatile("cpsie i" ::: "memory"); sync();
puts_("5. svc executed while PRIMASK is set:\n");
__asm volatile("cpsid i\n svc 0" ::: "memory");
done();
return 0;
}
void reset(void) { main(); }
__attribute__((section(".vectors"), used)) void (*const vectors[17])(void) = {
[0] = (void *)0x20010000, [1] = reset, [2] = nmi, [3] = hardfault, [6] = usagefault,
[11] = svc, [14] = pendsv, [15] = systick, [16] = irq0 };
Built with arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -O2 -nostartfiles -ffreestanding -Wl,--section-start=.vectors=0x0 -Wl,-Ttext=0x400 -Wl,-e,reset -Wl,-Tbss=0x20000000 exc_kinds.c -o exc_kinds.elf (GCC 14.2.1) and run under QEMU 10.0 (qemu-system-arm -M lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel exc_kinds.elf), it prints:
1. software-triggered:
SVCall: IPSR (exception number) = 11
PendSV: IPSR (exception number) = 14
SysTick: IPSR (exception number) = 15
external IRQ0: IPSR (exception number) = 16
2. fault with its handler enabled (UsageFault, divide by zero):
UsageFault: IPSR (exception number) = 6
UFSR/CFSR = 0x02000000
divide retried after the handler, result (was 99) = 0
3. same fault with its handler disabled:
HardFault: IPSR (exception number) = 3
HFSR = 0x40000000 CFSR = 0x02000000
4. PRIMASK set, then NMI, PendSV, SysTick and IRQ0 are all requested:
NMI: IPSR (exception number) = 2
releasing PRIMASK
PendSV: IPSR (exception number) = 14
SysTick: IPSR (exception number) = 15
external IRQ0: IPSR (exception number) = 16
5. svc executed while PRIMASK is set:
HardFault: IPSR (exception number) = 3
HFSR = 0x40000000 CFSR = 0x00000000
Reading the register pokes: SHCSR (System Handler Control and State Register) bit 18, USGFAULTENA, enables the UsageFault handler. CCR (Configuration and Control Register) bit 4, DIV_0_TRP, makes an integer divide by zero raise a fault instead of silently returning 0. ICSR (Interrupt Control and State Register) bit 28 (PENDSVSET) pends PendSV, bit 26 (PENDSTSET) pends SysTick and bit 31 (NMIPENDSET) pends the NMI; pending means requested but not yet running. Writing the CFSR or HFSR value back clears them, because their bits are sticky (they stay set until software writes a 1 to them). dsb and isb are barrier instructions that make sure the register write has completed before the next instruction. Decoding the printed values: CFSR 0x02000000 has only bit 25 set, which is UFSR bit 9, DIVBYZERO (the divide-by-zero cause); HFSR 0x40000000 has only bit 30 set, FORCED, meaning a configurable fault was escalated. In section 5 CFSR is 0 because an SVC is not a fault with its own status bit; only FORCED explains it. The HardFault handler there only clears PRIMASK so the program can finish: no SVCall line follows it in the output, so the SVC is not re-run in this run.
Section 2 shows a fault with its handler enabled; the divide was retried after the handler turned the trap off, so q changed from 99 to 0. Section 3 shows the same fault with the UsageFault enable bit cleared: it arrives as HardFault, with the FORCED bit (bit 30 of HFSR, 0x40000000) saying it was escalated and CFSR still naming the divide-by-zero. Section 5 shows that an SVC executed under PRIMASK does not reach the SVCall handler: a synchronous exception that cannot be taken because of its priority becomes a HardFault (the manual's exception-subtype table says the same for SVCall).
Maskability
PRIMASK blocks every exception whose priority is configurable and leaves the fixed-priority ones running:
| Exception | Number | Priority | Blocked by PRIMASK |
|---|---|---|---|
| Reset | 1 | -3, fixed | No |
| NMI | 2 | -2, fixed | No (ran in section 4) |
| HardFault | 3 | -1, fixed | No (ran in section 5) |
| SVCall | 11 | configurable | Yes: escalates to HardFault when issued (section 5) |
| PendSV | 14 | configurable | Yes: stays pending, runs on release (section 4) |
| SysTick | 15 | configurable | Yes: stays pending, runs on release (section 4) |
| External IRQs | 16 and up | configurable | Yes: stay pending, run on release (section 4) |
The fixed priorities are from the manual's exception table; the "ran" and "stays pending" entries are what the program printed. FAULTMASK, a stronger mask than PRIMASK (set with cpsid f), makes the code run at HardFault priority, so only NMI and Reset can preempt it.
What a production fault handler does
It should not return. It saves the stacked PC and LR, CFSR, HFSR and the fault address registers (MMFAR and BFAR) to a RAM area that survives reset, then resets the system (or enters a safe state), so the next boot can report what happened.
An ISR frees a buffer back to a custom pool and nulls the pointer, while the main task checks the pointer and then processes the buffer. Interrupts cannot be disabled for long. What can go wrong, and how would you redesign ownership of the buffer so it is safe?
volatile uint8_t* buf;
void ISR_free(void) { pool_free(buf); buf = NULL; }
void main_task(void) { if (buf) process(buf); }
Sample Answer
What can go wrong. There are three separate defects.
- Use after free (a time-of-check to time-of-use race).
main_task()seesbufnon-null, and then the ISR (interrupt service routine) runs, returns the block to the pool and setsbuf = NULL.main_task()carries on and callsprocess()on a block it no longer owns. That memory can be handed to the nextpool_alloc()caller, for example the same ISR starting a new receive, so the main task reads garbage or overwrites live data. The window is not the instant between theifand the call: it is the whole run time ofprocess(), which can be long. Interrupts cannot be disabled for that long, so masking is not an option here. - A dangling pointer inside the ISR.
pool_free(buf)runs beforebuf = NULL. Any code that looks atbufin between (a higher-priority ISR, or the same code after a nested interrupt) sees a non-null pointer to a freed block. The order of the two statements matters. - The declaration does not say what it seems to.
volatile uint8_t* bufdeclares a pointer to volatile bytes, not a volatile pointer; the variablebufitself is an ordinary variable. Compiling the question's code (saved asownorig.cwithexterndeclarations forpool_freeandprocess) witharm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -Wall -Wextra -O2 -c ownorig.calso warns about it:
#include <stdint.h>
extern void pool_free(uint8_t *p);
extern void process(uint8_t *p);
volatile uint8_t* buf;
void ISR_free(void) { pool_free(buf); buf = 0; }
void main_task(void) { if (buf) process(buf); }
ownorig.c: In function 'ISR_free':
ownorig.c:5:33: warning: passing argument 1 of 'pool_free' discards 'volatile' qualifier from pointer target type [-Wdiscarded-qualifiers]
ownorig.c: In function 'main_task':
ownorig.c:6:41: warning: passing argument 1 of 'process' discards 'volatile' qualifier from pointer target type [-Wdiscarded-qualifiers]
The qualifier ended up on the wrong thing, and the compiler is free to read buf once and reuse the value. The corrected declaration is uint8_t *volatile buf, but fixing the declaration alone does not remove defect 1: even a freshly re-read pointer can be freed a microsecond later.
The redesign: exactly one owner at any moment, and the pointer changes hands atomically. Treat the slot as a token. Whoever swaps the pointer out of the slot and receives a non-NULL value is the owner, and only the owner may use or free the buffer. The other side gets NULL and does nothing. _Atomic(uint8_t *) is the C11 type specifier that makes accesses to the pointer indivisible, and atomic_exchange(&slot, NULL) stores NULL and returns the previous value in one indivisible step, so two callers can never both receive the same non-NULL pointer. A use after free, which is what defect 1 describes, means touching memory after it was returned to the allocator.
static _Atomic(uint8_t *) slot; /* non-NULL: the buffer sits in the slot, owned by whoever takes it first */
static uint8_t *take(void) { return atomic_exchange(&slot, NULL); }
void ISR_free(void) { uint8_t *p = take(); if (p) pool_free(p); }
void main_task(void) { uint8_t *p = take(); if (p) { process(p); pool_free(p); } }
If main takes the buffer first, the ISR gets NULL, does not free, and main frees it after processing. If the ISR takes it first, main sees NULL and skips. The ISR can now fire in the middle of process() with no effect on the buffer, and interrupts stay enabled the whole time.
Run, with the interrupt injected at the dangerous point. The program below is a host model (gcc:14 container, -fsanitize=address,undefined): pool_free is free, so AddressSanitizer (ASan, a checker that reports heap errors) sees any misuse, and the function standing in for the ISR is called at the exact points where a real interrupt could land. It models the logic, not the timing.
/* Host model: pool_free is free(), and ISR_free() is called by the test at the points where
a real interrupt could arrive. The pool of 1 buffer is malloc/free so ASan can see misuse. */
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void pool_free(uint8_t *p) { free(p); }
static void process(uint8_t *p, void (*window)(void)) {
p[0] = 1; /* start of processing */
window(); /* an interrupt can arrive here */
p[63] = 2; /* end of processing */
}
static void no_window(void) {}
/* ---- original design ---- */
static uint8_t *buf_orig;
static void ISR_free_orig(void) { pool_free(buf_orig); buf_orig = NULL; }
static void main_task_orig(void (*window)(void)) {
uint8_t *p = buf_orig; /* the compiler loads the pointer once */
if (p) { window(); process(p, no_window); }
}
/* ---- single-owner design ---- */
static _Atomic(uint8_t *) slot;
static uint8_t *take(void) { return atomic_exchange(&slot, NULL); }
static int isr_got;
static void ISR_free_new(void) { uint8_t *p = take(); if (p) { isr_got = 1; pool_free(p); } }
static void window_new(void) { ISR_free_new(); }
static void main_task_new(void (*window)(void)) {
uint8_t *p = take();
if (p) { process(p, window); pool_free(p); }
}
int main(int argc, char **argv) {
if (argc > 1 && strcmp(argv[1], "orig") == 0) {
buf_orig = malloc(64);
main_task_orig(ISR_free_orig); /* ISR fires between the NULL check and process() */
puts("orig finished");
} else {
slot = malloc(64);
main_task_new(window_new); /* ISR fires in the middle of process() */
printf("new: ISR freed it = %d, slot now %p\n", isr_got, (void *)slot);
slot = malloc(64);
isr_got = 0;
ISR_free_new(); /* ISR wins the race instead */
main_task_new(no_window);
printf("new, ISR first: ISR freed it = %d\n", isr_got);
}
return 0;
}
gcc -O1 -g -Wall -Wextra -fsanitize=address,undefined buf_owner.c -o buf_owner
./buf_owner
./buf_owner orig 2>&1 | head -30
Output, trimmed to the lines that matter (the process id, addresses and library frames in the ASan lines differ from run to run, and the report continues with a dump of shadow memory, which is ASan's own bookkeeping of which bytes are valid):
new: ISR freed it = 0, slot now (nil)
new, ISR first: ISR freed it = 1
==19==ERROR: AddressSanitizer: heap-use-after-free on address 0x506000000080 at pc 0x000000400c9c bp 0xffffdf8f68a0 sp 0xffffdf8f68b8
WRITE of size 1 at 0x506000000080 thread T0
#0 0x400c98 in process /w/buf_owner.c:11
#1 0x400eb8 in main_task_orig /w/buf_owner.c:22
#2 0x400eb8 in main /w/buf_owner.c:39
...
0x506000000080 is located 0 bytes inside of 64-byte region [0x506000000080,0x5060000000c0)
freed by thread T0 here:
#0 0xffffbe4f2dec (libasan)
#1 0x400bdc in pool_free /w/buf_owner.c:9
#2 0x400bdc in ISR_free_orig /w/buf_owner.c:19
#3 0x400ea8 in main_task_orig /w/buf_owner.c:22
...
previously allocated by thread T0 here:
#0 0xffffbe4f3f08 in malloc (libasan)
#1 0x400e94 in main /w/buf_owner.c:38
...
SUMMARY: AddressSanitizer: heap-use-after-free /w/buf_owner.c:11 in process
How to read the report: the first stack (WRITE of size 1 ... #0 process) is the bad access, the one-byte write p[0] = 1 at buf_owner.c:11, the first store process() makes into the freed block (the report says 0 bytes inside the region, and ASan stops at the first bad access, so the later p[63] = 2 is never reached). Frame #0 is the function that made the access, and each higher number is its caller (main_task_orig, then main). The freed by stack names who released the block: ISR_free_orig calling pool_free, reached from main_task_orig because the test calls the stand-in ISR at the injection point. The previously allocated stack is the malloc in main. So the report states the whole story: allocated in main, freed by the ISR, then written by process(). In the first output line, (nil) is how the C library prints a null pointer with %p: it confirms the slot was emptied by the exchange. The original design is reported as a heap-use-after-free written by process() after ISR_free_orig freed the block. The single-owner design runs both orders cleanly: when the ISR fires during process() it frees nothing (ISR freed it = 0), and when the ISR wins first it frees the buffer (ISR freed it = 1).
What the exchange compiles to on a Cortex-M. The take() function compiled as a stand-alone (non-static) function with arm-none-eabi-gcc -O2 -mthumb and the -mcpu named in each column (declared static, as in the redesign, it would be inlined into its callers at -O2 and the listing would be mixed into theirs):
cortex-m3: cortex-m0plus:
movs r2, #0 push {r4, lr}
dmb ish movs r2, #5
ldr r3, [pc, #20] movs r1, #0
ldrex r0, [r3] ldr r0, [pc, #8]
strex r1, r2, [r3] bl __atomic_exchange_4
cmp r1, #0 pop {r4, pc}
bne.n <retry>
dmb ish
bx lr
The listing is condensed by hand from the objdump -d output: addresses, the padding nop and the literal word that the ldr reads are left out, the branch target is written <retry> and the call target __atomic_exchange_4. Read the Cortex-M3 column as follows: movs r2, #0 loads the new value (NULL); dmb ish is a data memory barrier, which keeps earlier memory accesses ordered before later ones (the exchange is sequentially consistent by default); ldrex reads the old pointer and arms an exclusive monitor; strex stores the NULL only if the monitor is still armed and writes 0 to r1 on success; cmp r1, #0 and bne.n <retry> jump back to the load if the store failed (the label is the ldrex line); the final dmb ish orders what follows. In the Cortex-M0+ column, movs r2, #5 passes the memory-order argument (5 is the numeric value of the sequentially-consistent order) and movs r1, #0 the new value to the library call. On Cortex-M3 and above the compiler emits an inline load-exclusive/store-exclusive loop (ldrex/strex), so nothing is masked. On Cortex-M0 and M0+ it emits a call to a library function, __atomic_exchange_4, which must exist in your build; the portable alternative there is a three-step PRIMASK section (save PRIMASK and mask, swap, restore PRIMASK) written by hand, a handful of instructions, which delays interrupts for a handful of instructions and never for the length of process().
Two details the redesign still needs.
- The pool itself is shared. In this design both
ISR_freeandmain_taskcallpool_free, so the pool's own free list is touched from two contexts. Either make the pool operations interrupt-safe (a short PRIMASK section around the list push and pop, or a lock-free stack, a list that threads update with atomic operations instead of locks), or make main hand the buffer back to the ISR (a flag the ISR checks) so that only one context frees. - A stream of buffers. For continuous traffic, replace the single slot with two queues of buffer indices: a ready queue the ISR fills and main drains, and a free queue main fills and the ISR drains. Each queue has exactly one producer and one consumer, so each index has one owner at any time, and the pointer-nulling trick is no longer needed.
What would flip the choice: if process() is always shorter than the interrupt latency budget, a PRIMASK section around check-and-use is simpler and correct, but the question states that interrupts cannot be disabled for long, so the ownership hand-off is the safe answer.
Unlock Full Question Bank
Get access to all 49 Real-Time Constraints and Interrupt Handling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.