Interrupts, DMA and the 12 Cycles

A Cortex-M chip starts a handler in 12 cycles, yet a low-priority handler still waits for every handler above it. Fire three interrupts and watch the waits add up.

Switch the interrupts on, one by one, and read the teal bar: it is how long the low-priority handler waits. Then turn on flash wait states and turn off tail-chaining. Then we build, piece by piece, the chip, the code and the memory behind every number.

You need a little C and the idea that a chip runs one instruction after another. We build the rest from zero, including what an interrupt is.

Built from primary sources: Arm architecture documents, the Memfault Interrupt blog, NXP application note AN12078 and the CMSIS reference. The full list is in the Field Guide. Follows Reset to main().

Fire the interrupts

200 cycles

A model, not silicon. Costs: 12 cycles to stack and start a handler, 12 to unstack, 6 for a tail-chain (Memfault, for a Cortex-M3 with zero-wait-state memory). Handler lengths of 200, 120 and 60 cycles are illustrative. The wait-state switch sets 3 wait states. Each wait state adds 3 cycles to an entry and 2 to a tail-chain in this model: also illustrative. Time shown at 168 MHz, an STM32F4 class clock.

Chapter 0

The Flag That Lost a Bit Once a Day

See how one C line can lose an update when an interrupt lands in a three-instruction window, and how to close that window

A small gadget sits on a shelf. It heats a water tank and talks to a phone over a serial cable. Its firmware keeps one byte of status flags in memory. Bit 0 means “the heater is wanted.” Bit 1 means “a byte arrived from the phone.”

Once a day, on average, the gadget ignores the phone. A byte arrives, and the flag for it is gone a moment later. On the bench the fault never shows. You can run the gadget for an hour and see nothing. This chapter finds that bit.

An interrupt is a doorbell

Most of the time the chip runs a loop called the main loop: read a sensor, decide, act, repeat. The serial hardware cannot wait for the loop to come round. So it rings a doorbell. That doorbell is an interrupt: a signal from hardware that makes the core stop what it is doing, run one small function, and then carry on exactly where it stopped.

The small function is the interrupt service routine, or ISR, also called a handler. The loop does not know the doorbell rang. That is the whole difficulty. The ISR can land between any two instructions of your main code.

One C line is three instructions

The main loop sets bit 0 with the C line flags |= 1;. The core cannot change a byte in memory directly. It must load the byte into a register (one of the core’s few fast storage slots), change it there, and store it back. This pattern is called read-modify-write. On an Arm Cortex-M it looks like this:

arm assemblyldr  r1, [r0]       @ 1. load: r1 = the whole flags byte from memory
orr  r1, r1, #1    @ 2. modify: set bit 0 inside the register
str  r1, [r0]      @ 3. store: write r1 back to memory

The ISR does the same dance for its own bit: load, set bit 1, store. Now picture the doorbell ringing after step 1 of the main code. The main code holds a copy of the old byte in r1. The ISR loads the byte, sets bit 1, and stores it. Control returns to the main code. It sets bit 0 in its stale copy and stores it. Bit 1 is gone.

Try every landing spot

The device below lets you choose where the ISR lands, and which fix is in the code. Start with “no fix.” Click each landing spot and read the final value of the flag byte.

Land the ISR inside the update

Rows are instructions in the order the core runs them. The four boxes at the right are flag bits 3 down to 0. The flag byte starts as 0x04 (bit 2 already set). Pick a landing spot, then a fix.

100 per second
10 per second

A model of three instructions, not a trace from silicon. The window of about 4 cycles (from the load to the store) is illustrative: the real count depends on the core, the memory and the compiler. The loss rate uses a 168 MHz clock. The rule it shows, a lost update needs the ISR inside the window, is exact.

How rare, and why once a day

The bug needs two things at the same time: the ISR rings, and the main code is inside its window. If the two are unrelated in time, the chance that one ISR lands in the window is the window’s share of all time.

L
Lost updates per day: the bug’s rate.
N
ISR arrivals per day. An ISR at 100 per second gives 100 × 86,400 = 8,640,000.
w
The window in seconds: the time from the load to the store.
u
How many times per second the main code runs the update. w × u is the share of time spent inside the window.

Now the numbers, one step at a time. Take a 168 MHz clock: one cycle lasts 1 / 168,000,000 s = 5.95 ns. A window of 4 cycles is 23.8 ns. If the main code runs the update 10 times a second, it spends 10 × 23.8 ns = 238 ns of every second inside the window. That is 2.38 × 10−7 of all time. Multiply by 8,640,000 arrivals and you get 2.06 lost updates per day.

8,640,000 × 4 × 10 / 168,000,000 = 2.06 lost bits per day

That matches the symptom: about once a day, never on the bench. A bench test that lasts ten minutes expects 0.014 failures. Slide the two sliders in the device above and watch the rate move by orders of magnitude. Notice that a fix which makes the update faster does not cure the bug. It only makes the bug rarer, and rare bugs ship.

Three fixes, one idea

All fixes make the three steps look like one step to the ISR. The first turns interrupts off with cpsid i before the load and back on with cpsie i after the store. A doorbell that rings meanwhile waits. The second uses the exclusive pair ldrex and strex (Chapter 4). The store succeeds only if nothing touched the memory since the load; if it fails, the code loads again. The third keeps the two bits in two different bytes, so each writer owns its own byte and no shared update exists.

Measure it before you trust the fix

Symptom: a flag bit vanishes about once a day. Measurement: drive a spare pin high just before the load and low just after the store. Raise the interrupt in software from a second timer, and count how often the ISR fires while the pin is high. Fix: pick one of the three above, repeat the count, and see the lost updates drop to zero.

On real hardware: on an STM32 Nucleo-F446RE (a Cortex-M4 board), set a timer interrupt at a rate near the main loop’s rate. Toggle pin PA5 around the update. Run one million updates with and without cpsid i, and count the bits that vanish.

Walk the four landing spots

Take the flag byte as 0x04 (bit 2 is already set). The main code wants to set bit 0. The ISR wants to set bit 1. The right final value is 0x07. Go through the four places the doorbell can ring.

  1. Before the load. The ISR runs first and the byte becomes 0x06. Main then loads 0x06, sets bit 0 and stores 0x07. Correct.
  2. After the load. Main holds 0x04 in r1. The ISR makes memory 0x06. Main sets bit 0 in its copy (0x05) and stores it. Memory now holds 0x05. Bit 1 is lost.
  3. After the modify. The same story: r1 holds 0x05, the ISR makes memory 0x06, and the store writes 0x05 over it. Lost.
  4. After the store. Memory holds 0x05. The ISR loads it, sets bit 1 and stores 0x07. Correct.

Only two of the four spots lose the update. With three instructions there are two gaps inside the window, and the bug lives in those two gaps. That is why the fix has to cover the whole window, not one instruction.

Why the bench never shows it

On the bench the ISR and the main loop are unrelated in time. The doorbell rings at a random point of the main loop’s cycle. A window of 4 cycles inside a loop of thousands of cycles gets hit very rarely. A ten-minute test sees nothing and passes. The field has millions of chances, and one of them lands in the gap.

Two more things make the bug hide. A compiler that optimises hard may shorten the window, which makes the bug rarer but not gone. And a debugger that stops the core changes the timing, so the bug often disappears when you look for it. A rare, timing-dependent fault is the signature of this kind of race. When a fault depends on when something happens, suspect an interrupt.

The road

  1. Exceptions and the NVIC: who may interrupt whom, and how priority is stored.
  2. Entry mechanics: what the chip does in 12 cycles.
  3. ISR design: why a short handler is a number, not a slogan.
  4. Critical sections: the price of turning interrupts off.
  5. DMA: moving data while the core sleeps, and the cache trap.
  6. Watchdogs: where the kick must live.
  7. Faults: reading a HardFault.
  8. Field Guide: the numbers, the checklist, the code.
The main code runs flags |= 1 and an ISR runs flags |= 2. When can bit 1 be lost?

Chapter 1

Exceptions vs Interrupts: The NVIC

Learn who may interrupt whom, how the chip stores that rule in one byte per interrupt, and how three mask registers switch it off

A robot arm holds a cup of coffee. Three things want the core at once. The motor encoder has ticked and needs a position update. The serial port has received a byte. A timer says the control loop is due. Only one can run. Which one goes first, and may one stop another that has already started?

The chip answers with a small block of hardware and one number per interrupt. This chapter reads that number.

Exceptions, and the interrupts inside them

An exception is any event that makes the core leave its normal flow and run a handler. Reset is one. A fault is one. A tick of the system timer is one. An interrupt is the kind of exception that comes from a peripheral, such as a UART or a timer. Every exception has a number, and the table below lists the ones you meet first.

Exception numberNameWhat raises it
1Resetpower on or a reset pin
2NMIa non-maskable source, such as a clock failure
3HardFaulta serious error, or a smaller fault that could not run (Chapter 7)
11SVCallthe svc instruction, used by an RTOS
14PendSVsoftware, to ask for a task switch at the lowest priority
15SysTickthe core’s own timer
16 and upIRQ0, IRQ1, …peripherals: the vendor decides which is which

Chapter 1 of Reset to main() showed the vector table: a list of addresses, one per exception number, with entry 0 holding the starting stack pointer. Entry n sits at address 4 × n. So IRQ0, exception 16, has its handler address at 0x40. The core reads that word when the doorbell rings, and jumps there.

The NVIC keeps four facts per interrupt

The NVIC, the nested vectored interrupt controller, sits next to the core and keeps a small record for every interrupt line. The record has four parts. Enabled: may this line ring at all? Pending: has it rung and not yet been served? Active: is its handler running now? Priority: how urgent is it?

Priority works like seniority in a hospital. A lower number means more urgent. Priority 0 beats priority 1. A running handler can be stopped only by a more urgent one. That stop-and-resume is what “nested” means in the name.

One byte of priority, fewer bits in practice

The Arm architecture gives each interrupt an 8-bit priority field. Chip makers do not build all eight bits. The number of levels is chosen by the vendor and lies between 4 and 256. The bits they leave out read as zero, and they sit at the low end of the byte (Memfault Interrupt). The nRF52840 implements 3 bits, so 8 levels. An STM32F4 part implements 4 bits, so 16 levels; its CMSIS device header names the count __NVIC_PRIO_BITS.

You can find out on your own chip. Write 0xFF to a priority register and read it back. Memfault shows the nRF52840 returning 0xE0: the top three bits stuck, the other five read zero. CMSIS describes the same test.

The life of one interrupt

It helps to follow a single doorbell from ring to return. A peripheral, say a UART that has received a byte, raises its line. The NVIC sets that interrupt’s pending bit. Now the NVIC compares the priority of every pending interrupt with the priority of whatever is running. If the pending one is more urgent, in the sense of the group rule above, the core takes it. The pending bit clears and the active bit sets. The handler runs. When it returns, the active bit clears.

Notice what the pending bit is: one bit. If the UART rings twice before the core serves the first ring, the bit is still just set. The two rings merge into one handler call. Interrupts are not a queue. A handler that assumes “one call, one byte” will lose bytes when the chip is busy. The safe handler asks the peripheral how much work is waiting and drains all of it.

Another rule trips people up. The NVIC clears its pending bit for you, but the peripheral keeps its own flag. If the handler returns without clearing that flag, the line is still high, the pending bit sets again at once, and the handler runs forever. This is an interrupt storm. The cure is the first line of most handlers: read the status, clear the cause.

Worked: three interrupts, one core

Say the encoder timer is level 1, the UART is level 2 and the control timer is level 3, all with PRIGROUP 3 so every level is its own group. The UART handler is running. The control timer rings: it is less urgent, so it waits in the pending state. The encoder rings: it is more urgent, so the core stacks a new frame and runs it on top of the UART handler. When the encoder handler returns, the UART handler resumes from its frame. When the UART handler returns, the pending control timer runs. The order of finishing is encoder, UART, control: the order of urgency, not of arrival.

Grouping: who preempts, and who only queues

The chip splits the priority byte in two with a setting called PRIGROUP (a field of the AIRCR register). The upper part is the group priority. It decides preemption. The lower part is the subpriority. It only breaks ties between interrupts that are both waiting and share a group. A handler is stopped only by an interrupt in a strictly lower group number.

The device shows the byte as eight cells. Blue cells are group bits, purple cells are subpriority bits, and grey cells are bits the chip does not build. Move the two sliders and the grouping, and read who preempts whom.

Decode the priority byte

Choose how many priority bits the chip builds, then set A and B and the PRIGROUP value. Watch the colours of the cells move.

2
3
3

The split follows the Armv7-M rule: with PRIGROUP g, the group field is bits [7:g+1] and the subpriority is bits [g:0]; at g = 7 there is no group field. STM32 HAL calls g = 3 “NVIC_PRIORITYGROUP_4”: four group bits, no subpriority. A level is placed in the top bits of the byte, as the hardware does.

With 4 bits built and PRIGROUP = 3, level 2 is the byte 0x20 and level 3 is 0x30. Their groups are 2 and 3. A preempts B. Now set PRIGROUP to 4: the group field shrinks to bits [7:5], both levels fall into group 1, and the subpriority differs. Neither stops the other. The one with the lower subpriority simply goes first when both wait.

Three switches that turn it all off

Three special registers mask interrupts without touching the NVIC records. They are cheap to set and easy to forget. The table shows what each one hides (Memfault Interrupt).

RegisterEffectWhere it exists
PRIMASKset to 1: disables every exception of configurable priority; only NMI, HardFault and Reset still runall Cortex-M
BASEPRIblocks exceptions up to a chosen priority; 0 means no effectnot on Armv6-M (M0, M0+)
FAULTMASKdisables everything except NMInot on Armv6-M

Failure: a kernel call from a too-urgent interrupt

An RTOS such as FreeRTOS uses BASEPRI to protect its own data. Its settings pick a limit, called configMAX_SYSCALL_INTERRUPT_PRIORITY. An ISR at or below that urgency may call the kernel functions that end in FromISR. An ISR above it is never masked, so it must never call the kernel. If it does, the kernel’s lists can be changed in the middle of an update, which is the race of Chapter 0 again, now inside the scheduler. This rule comes from the FreeRTOS port documentation for Cortex-M, which this lesson did not check line by line: confirm it for your own port.

Symptom: the system crashes or asserts rarely, only when one specific interrupt fires. Measurement: at the assert, read the interrupt’s priority register and compare it with BASEPRI and with the config limit. A grouping that is not all preemption bits also breaks the rule, so set it once at start-up and never change it. Fix: lower the ISR’s urgency below the limit, or stop it from calling the kernel.

On real hardware: on an nRF52840 DK, write 0xFF to NVIC_IPR0 in a debugger and read it back. You should see 0xE0. Try it on an STM32 Nucleo: expect 0xF0.

A chip builds 4 priority bits. Interrupt A is level 2 and B is level 3 with PRIGROUP = 3 (four group bits). A is running. B rings. What happens?

Chapter 2

Entry Mechanics: 12 Cycles, 8 Words, Tail-Chaining

Follow the chip through the 12 cycles between the doorbell and the first handler instruction, and count what tail-chaining saves

You are in the middle of a function. Register r0 holds a pointer, r1 a sum, r2 a loop count. The doorbell rings. In the next few cycles the core will run a different function that also wants r0, r1 and r2. When it finishes, your function must wake up with every register exactly as it left it.

Someone must save the registers first. On many chips the handler’s first lines of code do it. On a Cortex-M the hardware does it, which is why a handler can be an ordinary C function.

Why exactly eight registers

A C compiler follows a rule for function calls, the Arm procedure call standard. It says a function may freely overwrite r0 to r3, r12 and the link register lr. Those are caller-saved: whoever called the function must expect them to change. Registers r4 to r11 are callee-saved: any function that uses them must put them back.

So the chip has to save only the caller-saved set, and it must also save where to return and the status flags. That is the program counter pc and the status register xPSR. The count: r0, r1, r2, r3, r12, lr, pc, xPSR. Eight words of 4 bytes is 32 bytes. The handler’s compiled code saves r4 to r11 itself, if it needs them. This is why Memfault Interrupt says the hardware “will automatically stack the registers that are caller-saved.”

The eight words are pushed in the order r0 at the lowest address, then r1, r2, r3, r12, lr, pc, xPSR. That makes the saved pc the word at offset 6 from the stack pointer. Chapter 7 uses this to find a crash. The word is also called the exception frame.

What happens in the 12 cycles

Four things must happen. The chip pushes the frame. It reads the handler’s address from the vector table. It loads lr with a special magic value that means “this is an exception return.” And it fetches the handler’s first instruction. The chip overlaps several of these steps, so the total is shorter than their sum.

Interrupt latency is the time from the moment the request reaches the core to the first handler instruction. NXP calls this the narrow sense and gives zero-wait-state figures in AN12078. Table 1 of that note lists them. Newer cores such as the M23 and M33 have their own figures in their technical reference manuals; look them up there, not in a blog.

CoreCycles to first handler instruction
Cortex-M016
Cortex-M0+15
Cortex-M3, Cortex-M412
Cortex-M710 to 12

A cycle is one tick of the core clock. To turn cycles into time, divide by the clock: ns = cycles × 1000 / MHz. Twelve cycles at 80 MHz take 150 ns. At 168 MHz they take 71.4 ns. Try other cores and clocks below, and tick the floating-point box to see a bigger frame.

Count the entry

The bar is the entry time. The cells are the words the hardware pushes. Choose a core, then drag the clock.

168 MHz

Cycle counts are NXP AN12078 Table 1 (zero wait states); the M7 range is 10 to 12 and the lowest end is drawn. The floating-point frame is the 8 base words, the 17 caller-saved floating-point words (s0 to s15 and FPSCR) and one reserved word: 26 words, 104 bytes. That total is the Armv7-M extended frame size, derived here and not checked against the manual text.

Walk one entry, step by step

Here is the sequence for a Cortex-M3 or M4, with the order the hardware follows. The chip overlaps some of these, so the steps do not each cost one cycle.

  1. The NVIC finds the most urgent pending interrupt and tells the core. The core finishes or abandons its current instruction.
  2. The core pushes the eight-word frame onto the stack that was in use.
  3. It reads the handler’s address from the vector table, entry 16 + n for interrupt n.
  4. It puts a special value in lr. This is the exception return code: bit 2 of it records which stack held the frame, as Chapter 7 uses.
  5. It fetches and starts the first handler instruction. This is the end of the latency count.

At the end of the handler, the core sees the special value in lr loaded into the program counter (a plain bx lr does it). That is the signal to pop the frame and resume. Memfault Interrupt counts 12 cycles for this return too.

Where the extra cycles come from

The 12 assumes memory that answers at once. Flash does not. A fast core waits several cycles for each read from flash, which are the wait states. The vector fetch and the first instruction fetch both come from flash, so each wait state delays the entry. The device above does not model this; the hero does, with an illustrative three extra cycles per entry per wait state. Switch it on and watch every entry bar stretch.

Take a worked case. At 168 MHz, with 3 modelled wait states, the entry becomes 12 + 3 × 3 = 21 cycles, which is 125 ns instead of 71.4 ns. The handler body is untouched. The wait of the lowest handler in the hero grows from 344 to 365 cycles, because it pays that extra for the first entry and for each chain.

Two other things stretch the entry. A multi-cycle instruction must finish first: a long division or a load of several registers. And a more urgent interrupt may arrive during the stacking and win. NXP lists both. So the honest number to design with is the 12 plus whatever your own measurement shows, with your memory setup, at your clock.

Tail-chaining: skip the pop and the push

Suppose handler A is running and handler B has rung. Without a trick, A would finish and pop its frame (12 cycles). The chip would then notice B and push a new frame (12 cycles more). But the frame it just popped is the same frame it would push again, because the interrupted code has not run in between.

The chip skips both. This is tail-chaining. It keeps the frame in place and jumps straight to B. The cost is 6 cycles, instead of 12 + 12 = 24. Memfault Interrupt states it for a Cortex-M3: 12 cycles to start, 12 to return, and 6 to exit one exception and start another, “saving 18 cycles in total.”

no tail-chain: A ends, +12 pop, +12 push, B starts  =  24 cycles  |  tail-chain: 6 cycles  |  saved: 18

Try it. Two handlers are pending at the same moment. Switch tail-chaining off and read how far B moves to the right.

Chain two handlers

Yellow is overhead the chip adds. Blue is your code. The dashed teal box is the wait of the second handler.

100 cycles

The 12, 12 and 6 are Memfault Interrupt’s Cortex-M3 figures with zero-wait-state memory. The second handler runs 60 cycles, an illustrative length.

The claim “12 cycles, period” and the measurement

The 12 is a floor, not a promise. NXP lists what pushes it up on a real chip: memory with wait states, because flash is slower than the core; a multi-cycle instruction that must finish first; synchronising an outside signal to the core clock; and a more urgent interrupt that may preempt at any time, even before the first handler instruction. A task woken by an interrupt takes far more. On the i.MX RT1050 (a Cortex-M7 at 600 MHz) NXP measured a timer interrupt at 10 cycles (16.67 ns), a GPIO interrupt at 11 cycles (18.33 ns), and an RTOS task woken by the timer at 490 cycles (816.67 ns). That is 49 times the bare handler.

NXP’s measurement trick is worth copying. The handler’s first lines toggle a pin twice. A scope shows the input edge and the pin. Here are the steps with their numbers:

  1. The scope shows 73.4 ns between the two rising edges (call it t1) and 53.4 ns between the pin’s rise and fall (t2).
  2. At 600 MHz the core runs 0.6 cycles per ns. So t1 = 73.4 × 0.6 = 44 cycles and t2 = 53.4 × 0.6 = 32 cycles.
  3. The first handler instruction, an ldr, takes 2 cycles, so the pin rises at t3 = 2 + 32 = 34 cycles after the handler starts.
  4. Latency = t1 − t3 = 44 − 34 = 10 cycles, equal to the theoretical M7 figure.

On real hardware: on an STM32 Nucleo-F446RE, let a timer raise an interrupt and set one pin high in the handler’s first lines. Trigger a scope on the timer’s output pin. Repeat with the code running from flash and then from RAM, and write down the difference in cycles.

A handler on a Cortex-M4 ends and another interrupt is already pending. Tail-chaining runs the next handler after how many cycles, and what does it skip?

Chapter 3

ISR Design: Short, Deferred, Reentrant

Turn “keep ISRs short” into a sum you can compute, then move the work out of the handler

A drone’s motor loop must run every millisecond, or it tumbles. An engineer adds a line of debug output to the sensor handler. The sensor handler is more urgent than the motor handler. One day in three, the motor loop runs 400 microseconds late and the drone twitches. The advice is always the same: keep ISRs short. But how short? Short compared with what?

Chapter 2 gave us the pieces. Now we add them up.

The wait of a low-priority handler is a sum

Take one handler, call it L, at low urgency. An interrupt rings. It might have to wait for three kinds of cycles. First, the chip needs 12 cycles to stack and start (call it E). Second, every handler more urgent than L that is pending or rings meanwhile runs to its end first. Third, between two handlers the chip spends a gap g: 6 cycles with tail-chaining, 24 without.

If each more urgent handler rings once, the worst case for L is the sum below. The chip starts the most urgent handler first, so there is one stacking and then one gap for each handler after it, plus one gap before L itself.

TL
How long L waits before its first instruction, in cycles.
E
The entry cost: 12 cycles on a Cortex-M3 or M4 with zero-wait-state memory.
Σj
Add up one term for each handler j that is more urgent than L.
dj
The length of handler j’s body, from its first instruction to its return.
g
The gap that follows each handler: 6 with tail-chaining, 24 without.

The numbers from the hero: HIGH takes 200 cycles and MED takes 120. Then TLOW = 12 + (200 + 6) + (120 + 6) = 344 cycles. That is 2.05 µs at 168 MHz. Switch off tail-chaining and every gap becomes 24: TLOW = 12 + 224 + 144 = 380 cycles. Nothing in the sum depends on LOW’s own length. The wait is made of other people’s work.

A more urgent handler may ring again while L waits. If handler j rings every Tj cycles, it can run ceil(w / Tj) times in a wait of w cycles. Use that count in place of 1 and solve by repeating: guess w, count the runs, add them up, and use the result as the next guess. When the guess stops changing you have the worst case. If it keeps growing, the system cannot meet its deadline at all.

Now try it. The device runs the model with a deadline of 1,000 cycles for LOW. Raise HIGH’s body and watch the teal bar cross the dashed line. Then press Defer the work.

Add up the wait

LOW waits for HIGH and MED. The dashed line is LOW’s deadline. Drag the bodies of the two handlers above it.

200 cycles
120 cycles

Illustrative lengths and an illustrative 1,000-cycle deadline (5.95 µs at 168 MHz). Deferring leaves each handler 30 cycles: it copies a byte or sets a flag, and the rest of the work runs later in the main loop, below LOW. Costs 12, 12 and 6 are Memfault’s Cortex-M3 figures; tail-chaining is on.

Worked: when the higher handlers ring again

The sum above assumes each higher handler rings once. Real handlers repeat. Take three handlers on a 168 MHz core: ENC (priority 0) runs 150 cycles and repeats every 50 µs, which is 8,400 cycles; UART (priority 1) runs 400 cycles and repeats every 1 ms, 168,000 cycles; CTRL (priority 2) is the one we watch. We iterate on the wait w.

  1. Start with the entry alone: w = 12.
  2. In 12 cycles ENC can run ceil(12 / 8,400) = 1 time, UART 1 time. New w = 12 + 1 × (150 + 6) + 1 × (400 + 6) = 574.
  3. Check again with 574: ENC still runs ceil(574 / 8,400) = 1 time, UART 1 time. The sum is 574 again. It stopped changing.
  4. CTRL waits 574 cycles = 3.42 µs. Its own 3,000-cycle body then ends at 3,574, well inside its 168,000-cycle period.

Now give ENC a 2,000-cycle body. The first guess becomes 12 + 2,006 + 406 = 2,424, and ENC still fits once. Make ENC repeat every 1,000 cycles instead, and the count rises each time the wait grows. The loop never settles: the handlers above take more than all the time, and CTRL starves. The Field Guide has the loop in code and a calculator for it.

Four rules for a handler body

Defer: the handler takes a ticket, the loop does the work

The fix is a habit with a name: deferred processing. The handler does only what cannot wait: read the hardware, clear its flag, save the data. The slow part goes to the main loop or to an RTOS task. Think of a restaurant host. The host writes your name on a list and returns to the door. The kitchen cooks later.

The common shape is a ring buffer: a fixed array with a write position and a read position. The handler writes. The main code reads. Each position is changed by one side only, so the race of Chapter 0 cannot occur. This works for one writer and one reader.

c · STM32F4 UART receivestatic volatile uint8_t rx_buf[64];
static volatile uint8_t head;            // written by the ISR only
static uint8_t          tail;            // written by the main loop only

void USART2_IRQHandler(void) {
    if (USART2->SR & USART_SR_RXNE) {      // a byte has arrived
        uint8_t b = (uint8_t)USART2->DR; // reading DR clears the flag
        rx_buf[head] = b;
        head = (head + 1) & 63;          // 64 slots: wrap with a mask
    }
}

void main_loop_step(void) {
    while (tail != head) {               // anything new?
        parse_byte(rx_buf[tail]);        // slow work happens here
        tail = (tail + 1) & 63;
    }
}

Reentrancy: one function, two callers

A function is reentrant if it still works when something interrupts it and calls it again. A function that keeps its state in a static variable is not. Standard strtok, rand and printf all keep hidden state. So does malloc, which edits a shared list of free blocks. If the main code is inside malloc and a handler calls it, the list is half-edited and the handler reads garbage.

Failure: printf in a handler

Symptom: a HardFault that appears only under load, in a different place each time. Measurement: in the fault handler, read the Interrupt Control and State Register at 0xE000ED04. Its VECTACTIVE field holds the exception number of the running handler, or 0 if none. A non-zero value tells you the crash happened inside a handler (Memfault Interrupt). Then list every function that handler can reach. Compilers and tools such as cflow or a linker map make this list. Fix: replace the call with a ring-buffer write, and print from the main loop.

On real hardware: on an nRF52840 DK, set a pin at the start of the handler and clear it at the end. Measure the pulse on a scope or a logic analyzer. Add the printf-style call, measure again, and compare with your deadline.

HIGH runs 200 cycles and MED runs 120. The chip uses tail-chaining (gap 6) and entry costs 12. How long does LOW wait if all three ring together?

Chapter 4

Critical Sections and Atomics

Close the race of Chapter 0 three ways, and see what each way costs every other interrupt on the chip

A tank-level controller keeps a running total of litres in a 32-bit counter. An interrupt adds to it. The main loop reads it and resets it. After the lesson of Chapter 0 the engineer wants to be safe, so he wraps a whole page of code in __disable_irq(). The race is gone. A week later, the flow-sensor interrupt misses pulses. Every interrupt on the chip waited while the page ran.

A critical section is a stretch of code that must not be interrupted. The tool is simple. The art is keeping it small.

Two ways to say “not now”

Chapter 1 introduced the mask registers. PRIMASK is a one-bit switch. When it is 1, every interrupt of configurable priority waits. In CMSIS, __disable_irq() sets it and __enable_irq() clears it. BASEPRI is a level. Setting it to a number blocks interrupts at that urgency and below, and lets more urgent ones through. Setting it to 0 turns the mask off (Memfault Interrupt). BASEPRI does not exist on the M0 and M0+.

The price of a mask is easy to state. If a more urgent interrupt rings the instant a section starts, it waits for the whole section. Add the section’s length B to the sum of Chapter 3. For any handler the mask blocks, the worst-case wait becomes:

T = B + E + Σ ( dj + g )

Here B is the longest critical section that can block this handler. The device below applies one such section to the three handlers of the hero. Choose the mask, then drag the length.

Hold the doorbell

The three handlers ring at cycle 10, inside a critical section that starts at cycle 0. Choose what the section masks.

300 cycles

Illustrative lengths. The BASEPRI setting masks interrupts at MED urgency and below, so HIGH still enters in 12 cycles. In the model the section is thread code at cycle 0; the handler lengths are HIGH 200, MED 120 and LOW 60 cycles; tail-chaining is on.

With PRIMASK and a 300-cycle section that started 10 cycles before the ring, HIGH waits 302 cycles instead of 12. That is about 25 times its normal latency. With BASEPRI, HIGH is untouched and only MED and LOW pay. This is the main reason to prefer BASEPRI where the chip has it: protect only against the handlers that touch the data.

The safe pattern: save, mask, restore

Code often runs inside another critical section already. If a function ends with __enable_irq(), it turns interrupts back on in the middle of its caller’s section. The safe habit is to save the old state and put it back:

c · CMSISuint32_t add_litres(volatile uint32_t *total, uint32_t n) {
    uint32_t primask = __get_PRIMASK();  // remember: were interrupts already off?
    __disable_irq();                     // cpsid i
    uint32_t t = (*total += n);          // a few cycles: keep it tiny
    __set_PRIMASK(primask);              // restore, do not just enable
    return t;
}

Atomics: no mask at all

A masked section stops the whole chip. An atomic operation instead makes one update happen all at once or not at all. On a Cortex-M3 or later, the pair ldrex (load exclusive) and strex (store exclusive) does it. The load marks the address. The store succeeds only if nothing disturbed the address since the load. It returns 0 for success and 1 for failure. On failure you load again.

An interrupt that lands between the two makes the store fail on Cortex-M3 and M4, because exception entry clears the chip’s exclusive marker (this is Armv7-M behaviour, not checked against the manual text here). That is the exact case that lost a bit in Chapter 0. Now it just costs one retry. The M0 and M0+ have no such pair.

c · atomic OR with retrystatic inline uint32_t atomic_or(volatile uint32_t *p, uint32_t mask) {
    uint32_t old, failed;
    do {
        old    = __LDREXW(p);            // load and mark the address
        failed = __STREXW(old | mask, p);// 0 = stored, 1 = marker lost
    } while (failed);                    // an ISR landed: try again
    return old;
}

Bit-banding: an alias for every bit

The Cortex-M3 and M4 offer a third way for single bits. Every bit in the first megabyte of SRAM, from 0x20000000, has its own full word in an alias area from 0x22000000. Writing 1 or 0 to that word sets or clears the bit in one atomic step. For byte offset o and bit b the alias address is 0x22000000 + 32 × o + 4 × b. For the flag byte at 0x20000010, bit 1: 32 × 16 = 512 = 0x200, plus 4, so the alias is 0x22000204. The M0, M0+ and M7 do not offer it (from the Armv7-M design, not checked against the manual text here).

Nesting: restore, never enable

Suppose function log_event() disables interrupts, does its work and enables them. A caller that already holds a critical section calls it. When log_event() returns, interrupts are on again, in the middle of the caller’s section. The caller’s protection is silently gone, and the race is back, now with a different shape. Saving the old PRIMASK value and putting it back makes sections nest safely. Treat “enable” as a bug in any function that can be called from elsewhere.

Choose by what you protect

There is no single best tool. Match the tool to the data.

What the code updatesGood toolWhy
One counter or flag wordldrex / strex, or a short PRIMASK sectionone variable: the update is the whole window
Two fields that must agreea short section, BASEPRI if possiblean atomic on each field would still let the pair tear
A stream of bytes from a handlera ring buffer with one writer, one readerno shared index, no section
A single bit on an M3 or M4bit-band alias writeone store, no read

Worked: one retry of ldrex and strex

Follow the retry loop with the numbers of Chapter 0. The main code runs atomic_or(&flags, 1) and the flag byte is 0x04.

  1. ldrex loads 0x04 and marks the address.
  2. The doorbell rings. The chip enters the handler, which sets bit 1 and stores 0x06. Exception entry clears the mark.
  3. Main returns and computes 0x04 | 1 = 0x05. strex finds the mark gone and refuses: it returns 1 and writes nothing. Memory still holds 0x06.
  4. The loop sees a non-zero result and goes round again. ldrex loads 0x06, the code computes 0x07, and strex stores it and returns 0.

The cost is a few cycles, once, and only in the rare case that the doorbell rang. Nobody else is delayed. Compare that with a 300-cycle mask, which delays everybody every time.

RTOS critical sections

An RTOS offers its own versions. They usually use BASEPRI, so the kernel is protected from the handlers that call it, and urgent handlers keep running. Prefer them to a raw cpsid inside tasks. Keep the section in the kernel’s own sense of “short”: a handful of instructions, with no loop that depends on data and no call that might wait.

Failure: one long mask, every latency grows

Symptom: interrupts miss events at random, worse after a software update. Measurement: read the cycle counter (the DWT counter on M3, M4 and M7) at the start and end of each mask. Log the longest. It is the B in the formula. Fix: shrink the section, switch to BASEPRI so urgent handlers keep running, or use an atomic or a ring buffer.

On real hardware: on an STM32 Nucleo-F446RE, put a 300-cycle loop inside __disable_irq(). Raise a timer interrupt and measure its latency with a pin and a scope, as in Chapter 2. Change the mask to BASEPRI and measure again.

A 300-cycle PRIMASK section starts just before a more urgent interrupt rings. Roughly how much later does that interrupt’s handler start?

Chapter 5

DMA: Circular, Double-Buffered, Half-Transfer

Let a second piece of hardware move the samples, work out the time budget of each half-buffer, and avoid the cache trap on a Cortex-M7

A microphone board sends the chip one million 16-bit samples every second. If every sample rings a doorbell, the core runs one million handlers a second. Each costs 12 cycles to enter, 12 to leave and, say, 30 for the work: 54 cycles. At 168 MHz that is 54 × 1,000,000 = 54 million cycles a second, 32 percent of the chip, spent only on carrying numbers. The core never gets to think about them.

There is a better courier. DMA, direct memory access, is a small hardware engine that copies data between a peripheral and memory by itself, while the core does other work or sleeps. You tell it where to read, where to write and how many items. It rings one doorbell when it is done.

Circular mode and two halves

One doorbell per buffer has a flaw. While the core processes the buffer, new samples need somewhere to go. The answer is a circular buffer with two interrupts. The DMA engine fills the buffer from the start. When it passes the middle it raises the half-transfer interrupt. When it reaches the end it raises the transfer-complete interrupt and wraps back to the start without stopping.

Now there are two halves, and they trade jobs. While DMA fills the second half, the core reads the first. While DMA fills the first again, the core reads the second. This is double buffering, also called ping-pong. The core has exactly one half-buffer of time to finish each half.

That time is simple to compute. A buffer holds N samples, so a half holds N/2. At a rate of f samples a second, a half fills in (N/2)/f seconds. The core clock gives it that many seconds of cycles.

C
The cycles the core may spend on one half-buffer before DMA wraps onto it.
Fclk
The core clock in cycles per second, such as 168,000,000.
N / 2
Samples in one half. For a 512-sample buffer, 256.
f
The sample rate, in samples per second.

Worked: a 512-sample buffer at 1,000,000 samples a second at 168 MHz. A half holds 256 samples. It fills in 256 / 1,000,000 = 256 µs. The core has 168,000,000 × 0.000256 = 43,008 cycles, which is 168 cycles per sample. At 48,000 samples a second the same half lasts 5.33 ms and the core has 896,000 cycles, 3,500 per sample. The rate sets the budget, not the buffer size: a bigger buffer only delays the deadline and uses more memory.

Fill the two halves

Press Run DMA. The purple bar is the write pointer. The warm bracket is the half the core is processing. Change the rate and the cost per sample.

512 samples
120 cycles

Exact arithmetic at a 168 MHz clock; the picture is a model, not a bus trace. One interrupt per sample is costed at 12 + 12 + 30 = 54 cycles (illustrative 30-cycle body); with DMA the model counts one half-transfer interrupt per half, at the same 54 cycles.

The trap: the cache is not told

Bigger Cortex-M chips, such as the M7, have a data cache: a small fast copy of recent memory, kept in lines of 32 bytes. The core reads the copy, not memory. The DMA engine writes memory directly and does not update the copy. So the core may read a line that is out of date.

Two CMSIS functions fix it. SCB_InvalidateDCache_by_Addr(addr, size) throws away cached lines so the next read goes to memory: call it after DMA wrote, before the core reads. SCB_CleanDCache_by_Addr(addr, size) pushes the core’s changes out to memory: call it before DMA reads a buffer you filled. CMSIS asks for the address to be aligned to a 32-byte boundary.

That alignment rule hides the nasty case. Say your DMA buffer ends in the middle of a line, and a CPU variable frames_done lives in the rest of the line. Invalidating the line throws away the cached, newer frames_done. The variable snaps back to an old value at exactly the moment DMA completes. The device shows a 128-byte buffer in four lines.

Read through the cache

DMA has just written the new samples into memory. Each box is one 32-byte line. Press Core reads to see what the core gets.

A model of the mechanism: lines of 32 bytes, the CMSIS alignment rule, and the stale-read and lost-write cases. Real caches also evict lines on their own, so a stale read can be intermittent, which is what makes this bug hard.

Throughput, and where the data goes

DMA has a bandwidth bill too. One million 16-bit samples a second is 1,000,000 × 2 bytes = 2 MB a second. Four such channels make 8 MB a second. The chip’s buses can carry far more, but DMA and the core share some of them. When both want the same bus the core waits a few cycles. This is bus contention: it can stretch interrupt entry, one of the reasons the measured latency exceeds 12.

A DMA transfer needs four facts: where to read, where to write, how many items, and whether each address moves on after an item. For a sample stream the read address is fixed, the peripheral’s data register. The write address steps forward by one sample each time, through the buffer. In circular mode the engine reloads the count and the start address by itself when it reaches the end, so the stream never has a gap.

What the core must not do

The half-transfer interrupt tells you that half A is ready. It does not stop the engine. The engine keeps writing half B, and in half a buffer time it comes back to half A. If your code takes longer than that, it reads half A while DMA overwrites it, and the samples tear halfway through. No fault is raised. The symptom is a click in the audio or a spike in the signal, once in a while.

The measurement is simple: set a pin when your processing starts and clear it when it ends, and watch it against the half-transfer rate. The pin must stay low for at least a little while in every cycle. The device shows the same idea as the overrun state.

Worked: is my buffer aligned?

Say the buffer starts at 0x20001010 and holds 100 bytes. A cache line is 32 bytes. 0x10 is 16, so the buffer starts 16 bytes into a line: 0x20001010 modulo 32 = 16. It ends at 0x20001073, and 0x73 is 115, with 115 modulo 32 = 19, so the last line is shared as well. Two lines are shared with neighbours. The fix has three parts. Align the start to 32. Round the size up to 128 bytes, a multiple of 32. Keep no other variable in those four lines. In GCC the attribute is __attribute__((aligned(32))).

Failure: a neighbour that changes when DMA ends

Symptom: a variable beside the DMA buffer takes a wrong value only when a transfer completes. Measurement: print the buffer address modulo 32. If it is not 0, or if the buffer length is not a multiple of 32 bytes, the buffer shares a line with something else. Fix: align the buffer to 32 bytes and round its size up to a multiple of 32. Or mark the buffer’s memory non-cacheable with the memory protection unit. ST describes both options for the F7 and H7 families in application note AN4839, which this lesson did not check: read it before you rely on a detail.

On real hardware: on an STM32 Nucleo-F746ZG or H743ZI (Cortex-M7 boards), start an ADC with circular DMA into a buffer that is deliberately not aligned. Print the first and last samples at each half-transfer, then enable alignment and invalidate, and repeat.

A 512-sample circular DMA buffer fills at 1 MS/s on a 168 MHz core. Roughly how many cycles does the core have to finish each half?

Chapter 6

Watchdogs: Where to Kick

Learn why a watchdog kick proves only that the kicker is alive, and place it where it proves the whole system is

A weather station sits on a mountain. Its firmware enables the hardware watchdog. One winter morning it stops sending data. Nobody can climb up to check. A week later the team gets to it: the screen is frozen, the radio is silent, and the watchdog never fired. How can a watchdog fail to catch a frozen device?

A countdown that must be reloaded

A watchdog is a hardware timer that counts down. If it reaches zero, it resets the chip. To stop the reset, your code must kick it (also called feed or pet it) before zero: write a value that reloads the counter. A healthy program kicks often. A hung program stops kicking and the chip restarts, hopefully in a good state.

Two kinds are common. An independent watchdog runs from its own clock, so it keeps counting even if the main clock fails. A window watchdog is stricter: a kick that is too early also resets the chip, so a runaway loop that kicks every microsecond is caught. Memfault Interrupt suggests a hardware timeout somewhere in the 5 to 30 second range, and uses 10 seconds in its demo.

What a kick proves

A kick proves one thing only: the code that kicks ran. The weather station kicked from a timer interrupt. That interrupt kept firing while the main loop sat in an infinite wait. The kicker was alive; the device was not. The watchdog watched the wrong thing.

So ask of every kick: which code runs it, and what does that code prove? Three placements, three answers.

  1. In a timer interrupt. It proves the timer and interrupts work. It proves nothing about the main loop, the tasks or the data.
  2. At the top of the main loop. It proves the loop came round. A loop that spins without doing useful work, a livelock, still comes round.
  3. After a health check. The kicker is the lowest-priority code. It kicks only if every important part has recently checked in. Memfault Interrupt describes this rule: feed only if all tasks have recently checked in.

Try each placement against four situations. Choose where the kick lives, then inject a fault, and watch the countdown.

Place the kick

A fault begins at second 8. Ticks are kicks. The bar is the watchdog’s 5-second countdown. Pick a placement, then a fault.

A model of three designs and four faults. The health check in the third design tests that the sensor code finished, that comms made progress and that the interrupt tick counter advanced. The 5-second timeout and the second-8 fault are illustrative.

Run all twelve combinations. The timer interrupt only catches “interrupts left off.” The loop-top kick catches a stuck sensor but not a livelock. Only the health check catches all three faults and still lets a healthy device run.

Independent and window, in practice

The independent watchdog is the one that rescues you from a stuck clock, since it counts on its own oscillator. The window watchdog catches the opposite error. If a runaway loop kicks again and again, an independent watchdog is happy. A window watchdog sees a kick that came too early and resets. Use the window kind when a faulty loop can reach the kick by accident, and plan the kick to fall inside the allowed time.

Worked: a check-in table

Three parts check in. The sensor task runs every 100 ms and sets bit 0 when it completes. The comms task runs every 500 ms and sets bit 1. The tick counter, which the system timer interrupt increments, gives bit 2 if it moved. The health task runs once a second and follows four steps:

  1. Read the three bits and clear them together, inside a very short critical section (Chapter 4).
  2. If all three are set, kick the watchdog. If any is missing, do nothing.
  3. A missing bit means that part did not complete in the last second. The countdown keeps running.
  4. After the 5 s timeout with no kick, the chip resets, and the reset-reason register shows a watchdog reset.

Look at the margins. Comms runs every 500 ms, so in a 1 s window it should check in twice. One check-in is enough to set the bit. A slow flash write that holds comms for 800 ms still sets the bit within the window. A hang of 5 s gets caught. Choose the timeout from the longest legal pause plus margin, not from how fast you wish the system recovered.

What to do on the way down

A reset throws away the state. Before it, save what you can. Some chips offer an early-warning interrupt that fires when the watchdog expires, so a handler can save crash data. Memfault Interrupt warns that the window is tiny. On the nRF52840 the reset follows two 32.768 kHz clock cycles after the timeout event, which is about (64 MHz × 2) / 32,768 = 3,900 core cycles. Memfault avoids the feature for that reason: the chip may reset in the middle of cleanup. If you use it, write only a few words: the program counter and the check-in bits.

Why the lowest priority

The health task runs at the lowest urgency on purpose. Chapter 3 showed that the wait of a low-priority piece of code is the sum of everything above it. If the handlers above the kicker take all the time, the kicker never runs and the chip resets. That is the right behaviour: the system lost its slack, so restart it. A kicker that sits above everything would hide the problem.

Choose the timeout from the slowest part. Say the sensor task runs each 100 ms, comms each 500 ms and the health task checks once a second. The worst delay before the health task sees a missed check-in is its own 1 s plus the slowest 500 ms. A timeout of 5 s allows about four missed health checks before reset, enough for a slow flash write and short enough to recover. A timeout shorter than the longest legal pause resets a healthy device.

c · health-check kickstatic volatile uint32_t alive_bits;        // each part sets its own bit
#define ALIVE_SENSOR (1u << 0)
#define ALIVE_COMMS  (1u << 1)
#define ALIVE_TICK   (1u << 2)

void health_task(void) {                     // lowest priority, runs once a second
    static uint32_t last_ticks;
    if (systick_count != last_ticks) { alive_bits |= ALIVE_TICK; last_ticks = systick_count; }
    uint32_t primask = __get_PRIMASK(); __disable_irq();
    uint32_t bits = alive_bits; alive_bits = 0;      // read and clear as one step
    __set_PRIMASK(primask);
    if (bits == (ALIVE_SENSOR | ALIVE_COMMS | ALIVE_TICK))
        watchdog_kick();                     // only now do we prove the system is alive
}

Failure: it hangs although the watchdog is on

Symptom: the device freezes and never resets. Measurement: toggle a spare pin in the code that kicks and watch it on a logic analyzer while the device is frozen. If the pin still toggles, the kicker is alive and the kick is in the wrong place. After a reset, read the reset-reason register to learn whether a watchdog reset occurred: Memfault points to RCC_CSR on STM32F parts and RCC_RSR on STM32H parts. Fix: move the kick to the health task.

On real hardware: on an STM32 Nucleo, enable the independent watchdog with a 5 second timeout. Kick it from a SysTick interrupt, then add while(1); to the main loop and watch it never reset. Move the kick behind a flag check and repeat.

A device hangs in its main loop, yet the watchdog never fires. The kick is in a timer interrupt. Why?

Chapter 7

Faults: HardFault, BusFault and the Stacked PC

Read the chip’s own crash report: which register says what went wrong, and which saved word says where

Your board stops. The debugger shows the core sitting in HardFault_Handler, in a loop that does nothing. The program counter points at that loop, and that tells you only that something went wrong. It does not tell you what, or where. The evidence is still there, in a few registers and on the stack. You only have to know where to look.

A ladder of faults

A fault is an exception the core raises when an instruction cannot complete. Armv7-M cores such as the M3, M4 and M7 have three specific fault handlers: BusFault (a bad memory access on the bus), MemManage (a break of the memory protection rules) and UsageFault (a bad instruction, such as divide by zero or an opcode the core does not know). If one of them is disabled, or if a fault happens inside a fault handler, it climbs the ladder to HardFault, the catch-all. A HardFault caused this way has the FORCED bit set in its status register (Memfault Interrupt).

The crash report registers

The addresses come from Memfault Interrupt’s HardFault guide.

RegisterAddressWhat it holds
CFSR0xE000ED28Configurable Fault Status: three parts packed into one 32-bit read
  MMFSR0xE000ED28MemManage status (bits 7 to 0)
  BFSR0xE000ED29BusFault status (bits 15 to 8)
  UFSR0xE000ED2AUsageFault status (bits 31 to 16)
HFSR0xE000ED2CHardFault status, including FORCED
MMFAR0xE000ED34the address a MemManage fault touched
BFAR0xE000ED38the address a BusFault touched

The address registers are valid only when a flag says so: BFARVALID for BFAR and MMARVALID for MMFAR. Read the flag first.

Finding the instruction: the stacked PC

Chapter 2 showed that exception entry pushes eight words. The seventh, at offset 6 from the stack pointer, is the pc that was running. That is the clue to the crash. Which stack holds the frame? The link register holds a magic value on entry. Its bit 2 tells you: set means the process stack pointer was in use, clear means the main stack pointer (Memfault Interrupt). This small piece of assembly picks the right one and hands the pointer to C.

c · Cortex-M4, GCC__attribute__((naked)) void HardFault_Handler(void) {
    __asm volatile(
        "tst lr, #4        \n"   // bit 2 of EXC_RETURN: which stack?
        "ite eq            \n"
        "mrseq r0, msp     \n"   // clear: main stack
        "mrsne r0, psp     \n"   // set: process stack
        "b hardfault_c     \n"); // r0 = pointer to the stacked frame
}

void hardfault_c(uint32_t *frame) {
    uint32_t pc   = frame[6];                 // seventh word: where it died
    uint32_t cfsr = *(volatile uint32_t *)0xE000ED28;
    uint32_t bfar = *(volatile uint32_t *)0xE000ED38;
    log_crash(pc, cfsr, bfar);                // save, then reset
    NVIC_SystemReset();
}

The device decodes a register dump the way you would at the desk. Choose a crash, read which bits are lit, and read the verdict.

Decode the crash

Choose a sample crash, or type your own CFSR in hex. Lit cells are bits that are set. The verdict says what to do next.

The sample dumps are made up for teaching. Bit positions follow the Armv7-M layout: UFSR in bits 31 to 16, BFSR in 15 to 8, MMFSR in 7 to 0; The register addresses and flag names come from Memfault Interrupt; not every bit position was checked against the manual. The BFAR of 0x20040000 is just past the end of a 256 KB RAM, an invented example.

Worked: decode 0x00008200

  1. Write it in binary: 0x8200 is 1000 0010 0000 0000. Set bits are 15 and 9.
  2. Bits 15 to 8 belong to BFSR. Bit 9 is PRECISERR: the faulting instruction is known exactly. Bit 15 is BFARVALID: BFAR holds the address.
  3. Read BFAR: 0x20040000. The instruction touched memory that does not exist.
  4. Read the stacked pc: word 6, at SP + 24 bytes. For a precise fault it is the faulting instruction. Look it up with addr2line -e firmware.elf 0x08001A3C.

The imprecise case

Some writes are buffered: the core thinks the store is done, and the bus fails a few cycles later. This is an imprecise BusFault (IMPRECISERR). By then the core has moved on, so the stacked pc points at a later, innocent instruction, and BFAR is not valid. On Cortex-M3 and M4 you can switch the write buffer off while debugging: set bit 1, DISDEFWBUF, in the ACTLR register at 0xE000E008. The fault then becomes precise. It costs speed, and the M7 has no such switch (Memfault Interrupt).

Worked: reading a frame by hand

Suppose the crash handler prints the eight words at the stacked frame. With the main stack pointer at 0x20007FD0, you see these values:

OffsetRegisterValue
+0r00x20040000
+4r10x0000002A
+8r20x00000001
+12r30x00000000
+16r120x20000A10
+20lr0x08001B05
+24pc0x08001A3C
+28xPSR0x61000000

pc is at SP + 6 × 4 = SP + 24 = 0x20007FE8, and holds 0x08001A3C

The values are made up for teaching, but the method is real. The word at +24 is the PC. Here it is 0x08001A3C. Feed it to addr2line with your ELF file to get the source line. The word at +0, r0, is 0x20040000, which matches the BFAR in our earlier decode: the faulting instruction used r0 as the pointer. The saved lr shows the caller, 0x08001B05, with its lowest bit set because it is a Thumb address. It gives you one frame up the call chain for free.

A guard for the stack

Stack overflow is the hardest fault to read, because the damage happens far from the cause. The stack grows downward. When it passes its limit it overwrites whatever sits below, often global variables. A guard region fixes this. With the memory protection unit you mark, say, the 32 bytes below the stack as no-access. The first write into it raises a MemManage fault at the exact instruction that overflowed. The device’s fifth sample, with DACCVIOL and MMARVALID set and an address just below the stack, shows what you would see.

Without an MPU, use the pattern method described below. At start-up fill the whole stack with 0xA5A5A5A5. From time to time scan upward from the bottom for the first word that is not the pattern. The distance from there to the top is the most stack the program has ever used. Log it. When it passes 75 percent of the stack, enlarge the stack before the field finds out for you.

Failure: a stack overflow

Symptom: random crashes that move when you change unrelated code. Measurement: fill the stack with a known pattern at start-up, such as 0xA5A5A5A5, and later scan for the lowest word still holding it; that is the stack’s high-water mark. A fault during stacking sets STKERR, and the frame may be incomplete. Fix: give the stack more room, and put a memory protection region at its bottom, so the overflow raises a fault at the moment it happens.

On real hardware: on an STM32 Nucleo, write through a pointer to an address outside the memory map and catch the fault. Compare BFAR with what you wrote. Then switch to a buffered write and see the imprecise bit.

CFSR shows IMPRECISERR and BFARVALID is clear. What does that tell you about the stacked PC?

Chapter 8

Field Guide

Keep the numbers, the checklist and the one calculation that turns a priority table into a worst-case wait

One idea ran through this lesson. An interrupt on a Cortex-M costs a fixed, small number of cycles to enter, and a few more to leave or chain. Everything else is addition. The wait of a low-priority handler is the sum of the work above it, plus any stretch where interrupts are masked. DMA lets the core stop paying per sample. A watchdog kick must live where it proves the whole system is alive. A fault leaves a report you can read.

The numbers

WhatValueSource
Entry latency, zero wait statesM0 16, M0+ 15, M3/M4 12, M7 10 to 12 cyclesNXP AN12078, Table 1
Return, and tail-chain12 cycles to return, 6 to chain, saving 18 (Cortex-M3)Memfault Interrupt
Stacked framer0 to r3, r12, lr, pc, xPSR: 8 words, 32 bytes; stacked PC is word 6Memfault Interrupt
Frame with floating point26 words, 104 bytes (8 + 17 + 1 reserved)derived; confirm in the Armv7-M manual
Cycles to time12 cycles = 150 ns at 80 MHz, 71.4 ns at 168 MHzns = cycles × 1000 / MHz
Measured on i.MX RT1050, 600 MHztimer ISR 10 cycles (16.67 ns), GPIO ISR 11 (18.33 ns), RTOS task wake 490 (816.67 ns)NXP AN12078, Table 2
Priority levels4 to 256, vendor choice; low bits read zero; nRF52840 3 bits, STM32F4 4 bitsMemfault Interrupt; CMSIS
Fault registersCFSR 0xE000ED28, HFSR 0xE000ED2C, MMFAR 0xE000ED34, BFAR 0xE000ED38Memfault Interrupt
Cache maintenanceaddress aligned to a 32-byte boundaryCMSIS Dcache functions
Hardware watchdog timeout5 to 30 s rule of thumb; 10 s in the demoMemfault Interrupt
M23 and M33 entry latencynot stated here: read the core’s technical reference manualnot verified

The core as code

This is the whole worst-case calculation for any handler in a table. It repeats the guess-and-count step from Chapter 3 until the answer stops changing. If it passes the deadline, it stops and says so.

c · worst-case wait of handler `me`typedef struct { uint32_t pri, body, period; } isr_t;   // all in CPU cycles; pri 0 = most urgent

#define ENTRY 12u   // Cortex-M3/M4, zero wait states
#define GAP    6u   // tail-chain (use 24 without it)

uint32_t worst_wait(const isr_t *t, int n, int me, uint32_t B, uint32_t deadline) {
    uint32_t w = B + ENTRY;                         // B = longest mask that can block it
    for (;;) {
        uint32_t next = B + ENTRY;
        for (int j = 0; j < n; j++) {
            if (t[j].pri >= t[me].pri) continue;     // only more urgent handlers
            uint32_t runs = (w + t[j].period - 1) / t[j].period;   // ceil(w / period)
            next += runs * (t[j].body + GAP);
        }
        if (next == w) return w;                    // settled: this is the worst case
        if (next > deadline) return next;           // it only grows: give up
        w = next;
    }
}

Use the calculator below on a small table. Change a body length or the longest mask, and read the wait of each handler.

Resolve the table

Three handlers at 168 MHz. Edit the body and the period of each, and the longest critical section B. Priority 0 is the most urgent.

0 cycles

A teaching model with illustrative numbers: the same entry and gap costs as the hero, the same re-arrival count as Chapter 3, and no memory wait states. A real analysis also adds the cost of the exit and any blocking by shared data.

The checklist

Keep going

Registers and bus basics are in hardware interfacing, and the C that goes with them in embedded C and advanced C. Scheduling theory is in real-time systems, and the next step in this track is the RTOS under the hood, which builds on PendSV and SysTick from Chapter 1. For the same ideas on a robot, see real-time performance and sensor and actuator integration. The step before this one is Reset to main(); the same trade between interrupts and polling on an application core is in real-time Linux. A later lesson in the Physical AI series covers caches and coherence on bigger cores in detail; the pipeline and privilege lesson is here. The full fail-safe design is the fail-safe lesson.

Latency is a sum, so you can budget it. Twelve cycles to enter, 6 to chain, the work above you, and every stretch where interrupts are off. Write them down in a table, add them up, and compare with the deadline before you run the code.

Sources and credit

Sources opened while building this lesson: the Memfault Interrupt posts A Practical Guide to ARM Cortex-M Exception Handling, How to debug a HardFault and Firmware watchdog best practices; NXP application note AN12078, Measuring Interrupt Latency; and the CMSIS reference for data cache functions and NVIC functions.

These sources were not checked, so claims that depend on them are marked in the text: Arm’s Beginner guide on interrupt latency (the M23, M33 and M7 worst-case figures), the FreeRTOS Cortex-M interrupt priority page, ST application note AN4839 on the cache, and Joseph Yiu’s The Definitive Guide to Arm Cortex-M3 and Cortex-M4 Processors for the LDREX, bit-banding and register bit positions. Check those against the sources before you quote them.

Now press Present or Teach and explain it back from memory: the 8-word frame, the 12 and the 6, and the sum for the lowest handler. Then go back to the timeline, switch on all three interrupts, and predict the teal bar before you read it.

Interrupts, DMA and the 12 Cycles
Reset to main() · Back to Gleams