Try Embedded

The Cortex-M exception model

Faults, SVC and PendSV, MSP and PSP, EXCRETURN and fault handlers.

Exceptions are the bigger family

On a Cortex-M, interrupts are one kind of exception: any event that makes the processor stop normal execution and run a handler from the vector table. Faults, the system timer, supervisor calls and the RTOS context switch all use the same machinery. Knowing that machinery is what lets you write a fault handler that tells you what went wrong, configure an RTOS correctly, and answer the probing questions that follow "what is an interrupt?".

The exception numbers

NumberExceptionPriorityPurpose
1Reset−3 (fixed, highest)Power-on and reset
2NMI−2 (fixed)Non-maskable interrupt: clock failure, watchdog early warning
3HardFault−1 (fixed)All faults that cannot be handled elsewhere
4MemManageConfigurableMPU violations (M3 and up)
5BusFaultConfigurableBus errors on instruction or data access
6UsageFaultConfigurableUndefined instruction, invalid state, unaligned access (if trapped), divide by zero (if trapped)
7SecureFaultConfigurableTrustZone violations (Armv8-M)
11SVCallConfigurableSVC instruction: a system call into a privileged kernel
12DebugMonitorConfigurableDebug events without halting
14PendSVConfigurableSoftware-requested, deferrable: RTOS context switches
15SysTickConfigurableSystem timer tick
16+IRQ 0, 1, ...ConfigurablePeripheral interrupts via the NVIC

MemManage, BusFault and UsageFault are disabled by default and escalate to HardFault. Enabling them in SCB->SHCSR gives each its own handler and more precise reporting.

Modes, privilege and two stack pointers

Thread modeHandler mode
RunsNormal code (main, RTOS tasks)Exception handlers
PrivilegePrivileged or unprivileged (CONTROL.nPRIV)Always privileged
Stack pointerMSP or PSP (CONTROL.SPSEL)Always MSP
  • MSP (main stack pointer) is used after reset and by all handlers.
  • PSP (process stack pointer) is what an RTOS gives each task: every task has its own stack, while interrupts share the main stack. This keeps interrupt stack usage out of every task's stack budget.
  • Unprivileged code cannot change interrupt masks, access the system control space or, with the MPU, touch other tasks' memory. It asks the kernel to do privileged work with SVC.

Entry and return

On entry the hardware:

  1. Pushes the exception frame onto the current stack (MSP or PSP): r0, r1, r2, r3, r12, lr, pc (the return address), xPSR. With an active FPU context, s0–s15 and FPSCR too (lazily, only if the handler uses the FPU).
  2. Switches to handler mode and MSP, loads pc from the vector table.
  3. Sets lr to an EXC_RETURN value, not an address.

EXC_RETURN encodes where to return, and the handler returns by branching to it (bx lr):

EXC_RETURN (no FPU frame)Return toStack used
0xFFFFFFF1Handler mode (nested exception)MSP
0xFFFFFFF9Thread modeMSP
0xFFFFFFFDThread modePSP

(Values ending in E1, E9, ED mean an FPU frame was stacked.) A fault handler uses bit 2 of EXC_RETURN to know which stack holds the faulting frame.

#include <stdio.h>
#include <stdint.h>

/* What a fault handler does first: find the stacked frame and pull out the faulting PC. */
typedef struct { uint32_t r0, r1, r2, r3, r12, lr, pc, xpsr; } frame_t;

static void report(uint32_t exc_return, const frame_t *msp_frame, const frame_t *psp_frame) {
  const frame_t *f = (exc_return & 4u) ? psp_frame : msp_frame;     /* bit 2: which stack */
  printf("EXC_RETURN 0x%08X -> frame on %s\n", exc_return, (exc_return & 4u) ? "PSP" : "MSP");
  /* The stacked xPSR holds the IPSR of the interrupted code: 0 means thread mode, otherwise the
     number of the exception handler that was running when the fault happened. */
  printf("  faulting PC 0x%08X, caller (LR) 0x%08X, interrupted IPSR %u\n",
         f->pc, f->lr, f->xpsr & 0x1FFu);
}

int main(void) {
  frame_t on_msp = { 0, 0, 0, 0, 0, 0x08000123, 0x08000456, 0x0100002B };
  frame_t on_psp = { 0, 0, 0, 0, 0, 0x08001201, 0x08001234, 0x21000000 };
  report(0xFFFFFFF1u, &on_msp, &on_psp);   /* fault inside IRQ 27's handler, on MSP */
  report(0xFFFFFFFDu, &on_msp, &on_psp);   /* fault in an RTOS task, which ran on PSP */
  return 0;
}

Fault handling done properly

A HardFault handler that just loops forever wastes the most useful debugging information you will ever get. A good one:

__attribute__((naked)) void HardFault_Handler(void) {
  __asm volatile(
    "tst lr, #4        \n"   /* which stack was in use? */
    "ite eq            \n"
    "mrseq r0, msp     \n"
    "mrsne r0, psp     \n"
    "mov r1, lr        \n"   /* pass EXC_RETURN too */
    "b fault_record    \n");
}

void fault_record(const uint32_t *frame, uint32_t exc_return) {
  crash.pc   = frame[6];
  crash.lr   = frame[5];
  crash.cfsr = SCB->CFSR;    /* which fault and why */
  crash.hfsr = SCB->HFSR;
  crash.bfar = SCB->BFAR;    /* faulting data address, if valid */
  crash.mmfar = SCB->MMFAR;
  crash.magic = CRASH_MAGIC; /* in a no-init RAM section */
  NVIC_SystemReset();        /* or halt with __BKPT in debug builds */
}

After the reset, the application finds the record, reports it, and addr2line turns the PC and LR into source lines. The debugging lesson shows how to decode CFSR.

SVC and PendSV: how an RTOS uses exceptions

  • SVC is a synchronous exception triggered by the svc #n instruction. Unprivileged tasks use it to request kernel services; many RTOSes also use it once at start-up to launch the first task.
  • PendSV is triggered by software setting a pending bit (SCB->ICSR = SCB_ICSR_PENDSVSET_Msk). Set to the lowest priority, it runs only when no other exception is active, which makes it the ideal place for the context switch: interrupts that make a higher-priority task ready just pend PendSV, and the switch happens once, after all of them finish.
  • SysTick drives the RTOS tick.

Priorities and masking, in full

  • Lower number means higher priority. Reset, NMI and HardFault have fixed negative priorities.
  • An exception preempts the running one only if its group priority is strictly higher.
  • PRIMASK = 1 masks everything except NMI and HardFault.
  • FAULTMASK = 1 also masks HardFault-escalated faults (used by fault handlers themselves).
  • BASEPRI = n masks exceptions with priority value ≥ n, leaving more urgent ones running. Not available on Armv6-M (M0/M0+), which is why RTOS critical sections there must use PRIMASK.

Pitfall: If a fault occurs while the HardFault handler itself is running (a lockup), the core stops executing and asserts LOCKUP until reset or debugger intervention. Keep the fault handler minimal and avoid touching possibly corrupt stacks or peripherals in it.

Interview question: What is the difference between MSP and PSP, and why does an RTOS use both?

Answer: The Cortex-M has two stack pointers. The main stack pointer is used after reset and always in handler mode; the process stack pointer can be selected for thread mode. An RTOS gives each task its own stack and points PSP at the running task's stack, while all interrupt handlers use the single main stack. That keeps interrupt stack usage out of every task's budget, so task stacks can be smaller, and makes context switching a matter of saving and swapping PSP.

Interview question: What should a production HardFault handler do?

Answer: Determine which stack held the exception frame from bit 2 of EXC_RETURN, read the stacked PC, LR and xPSR, and capture CFSR, HFSR, BFAR and MMFAR. Store them, with a magic value and checksum, in a RAM section not cleared at start-up, then reset (or break into the debugger in debug builds). On the next boot, report the record so the PC and LR can be mapped to source with the matching ELF. It should avoid complex code, since the stack or peripherals may be corrupt.

Build it: which interrupt goes first?

This is step 5, the last of the module project. The ESC has three interrupts: the commutation timer that switches the motor's phases (late by microseconds and the motor loses sync), the ADC that samples the current, and the UART that receives throttle commands. Their priorities and the NVIC's priority grouping decide who can interrupt whom. Get it wrong and a burst of UART traffic stalls the motor.

Lab: NVIC priorities, grouping and pre-emption

This chip implements 4 priority bits: priorities 0 (most urgent) to 15. The grouping setting splits them: the top preempt_bits bits (0 to 4) are the group priority and the rest the subpriority.

  • group_of(prio, preempt_bits) returns the group priority, prio >> (4 - preempt_bits); sub_of(prio, preempt_bits) the subpriority, the remaining low bits.
  • preempts(new_prio, running_prio, preempt_bits) returns true when an interrupt can interrupt the running one: only when its group priority is strictly more urgent (lower). The subpriority never pre-empts.
  • next_pending(p, n, preempt_bits) picks which of n pending interrupts runs next: the lowest group priority, then the lowest subpriority, then the lowest IRQ number. It returns that IRQ number, or -1 if n is 0.

Going deeper

Interview question: What should an industrial robot arm's firmware do when it hits a HardFault?

Answer: Make the motion safe first: the fault handler (which must not depend on anything that might be broken) cuts the motor drives or applies brakes, then records the stacked registers and fault status registers in memory that survives reset, and resets or halts. The record shows where and why it failed, and the next boot reports it.

Interview question: What happens on the Cortex-M if a fault occurs inside the HardFault handler?

Answer: The processor enters lockup: it stops executing instructions, asserts the LOCKUP signal and stays there until a reset or a debugger intervenes (many MCUs can be configured to reset automatically on lockup). That is why fault handlers must be simple, run on a valid stack, and not depend on the state that may have caused the fault.

Interview question: Why can't an RTOS on a Cortex-M0 use BASEPRI for critical sections, and what does it do instead?

Answer: BASEPRI exists only on Armv7-M and Armv8-M Mainline; Armv6-M (Cortex-M0 and M0+) lacks it. So an RTOS there disables all configurable interrupts with PRIMASK in critical sections, which delays every interrupt, including urgent ones, for the duration. On M3 and later it can raise BASEPRI to mask only interrupts at or below the kernel's syscall priority, leaving higher-priority interrupts that never call the kernel running with zero added latency.

Explain it: In your own words, explain what happens on a Cortex-M from the moment an interrupt is accepted to the moment the interrupted code resumes.

Answer: The core finishes or abandons the current instruction, pushes r0 to r3, r12, LR, the return PC and xPSR onto the active stack (plus FPU registers if needed), switches to handler mode on the main stack, puts an EXC_RETURN code into LR and loads the handler address from the vector table. The handler runs as a normal C function, saving any callee-saved registers it uses. When it returns by branching to the EXC_RETURN value, the hardware recognises it, pops the stacked registers from the stack the code indicates, and resumes the interrupted code, unless another exception is pending, in which case it tail-chains straight into that handler.