Top 100 Embedded Systems Engineer Interview Questions and Answers
The questions most likely to come up in your Embedded Systems Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.
Curated: · Written: · Reviewed:
Q&A-13A file-scope uint32_t filter_state is not 0 after reset. Where did the zeroing go?
What a strong candidate says first
The zeroing didn't disappear; the object stopped being covered by it. C guarantees that a file-scope object with static storage duration and no initializer is zero before main. On bare metal that guarantee is implemented by the startup code (Reset_Handler in startup_*.s, or crt0) which walks the linker-provided __bss_start__ to __bss_end__ range and stores zeros. If filter_state is not inside that range, nothing zeroes it, and you read whatever SRAM held from the previous power cycle or the bootloader.
So the first move is not to add filter_state = 0. That hides the bug for one object and leaves every other .bss object broken. It's to find out which of three things happened:
- The zero loop was removed or
#if 0'd. - The object was placed in a section the loop doesn't cover (
.noinit, or a custom output section). - The linker script's
__bss_start__/__bss_end__don't bracket the object: common when a section is added and the symbols aren't updated.
How to tell them apart
arm-none-eabi-nm and the map file answer it in a minute. nm gives the address of filter_state; the map file gives __bss_start__ and __bss_end__. If the address is outside the range, it's case 2 or 3. If it's inside and the value is still garbage, the loop didn't run: check the startup file and whether the reset vector actually reaches it.
/* startup: the loop that must run before main */
extern uint32_t __bss_start__[], __bss_end__[];
for (uint32_t *p = __bss_start__; p < __bss_end__; p++)
*p = 0;
Failure modes
- Loop removed to hit a boot budget. This is the one that bites, because it works on a cold boot with fresh SRAM and fails on a warm reset.
.noinitused for a "persistent" counter, then reused for state that must be zero.- A bootloader that jumps to the application without re-running the C runtime: the app's
.bssis never cleared. - Linker script edited so a new section sits between
__bss_start__and__bss_end__but isn't word-aligned, so the loop's word stores skip the tail.
Worked example
A motor controller had 48,128 bytes of .bss and a 20 ms boot budget. The zero loop at 48 MHz measured about 1 ms. The pure store count is the floor: 48,128 bytes / 4 bytes per word = 12,032 word stores, and at one store per cycle that is 12,032 cycles / 48 MHz ≈ 0.25 ms; loop overhead and flash wait states take it to the ~1 ms that was measured. Someone #if 0'd the loop to buy margin. On a warm reset filter_state came up 0xFFFFFFFF from SRAM remnant, the IIR output pegged, the actuator saturated, and RUN current went from 18 mA to 42 mA.
How I'd confirm it
Dump the first 64 bytes of .bss over SWD immediately after Reset_Handler returns and require zeros; then time boot with the loop in and out. If the dump is non-zero, the loop or the range is wrong, and no amount of application-level initialization fixes that class of bug. C says zero. SRAM says remnant.
Curated: · Written: · Reviewed:
Q&A-105A main loop spins on a status flag set by the UART ISR, and reads a memory-mapped status register. Why must both be volatile, and what does volatile not guarantee?
volatile tells the compiler the object's value can change at any time outside the program's visible control flow, so every access must be a real load or store, in program order relative to other volatile accesses. It forbids two optimisations: caching the value in a register across statements, and deleting an access that appears to have no effect.
Two cases in embedded C:
- Memory-mapped status register. The hardware changes the bits, not your code. Without
volatile, the compiler sees a loop reading the same address and hoists the load out:
/* broken: one load, then spin forever */
uint32_t *sr = (uint32_t *)0x40011000;
while ((*sr & USART_SR_RXNE) == 0) { }
/* fixed: reload every iteration */
volatile uint32_t *sr = (volatile uint32_t *)0x40011000;
while ((*sr & USART_SR_RXNE) == 0) { }
- Flag set in an ISR. The interrupt handler runs asynchronously; the compiler cannot prove the flag is unchanged inside the polling loop, so it turns
while (!rx_done) {}intowhile (1) {}.
volatile uint8_t rx_done; /* written in USART1_IRQHandler */
while (!rx_done) { } /* without volatile: infinite loop */
What volatile does not guarantee
- Atomicity.
volatile uint32_t cnt; cnt++;is a load, add, store. An ISR that also incrementscntloses updates. Use__atomic_fetch_add(&cnt, 1, __ATOMIC_SEQ_CST)or mask the interrupt. - Memory ordering / barriers. The compiler will not reorder volatile-to-volatile accesses, but it can move non-volatile accesses around a volatile one. The CPU can also reorder. The classic "ISR writes buffer, then sets flag; main reads flag, then buffer" needs a release/acquire pair:
__DMB()before the flag store and after the flag load on Cortex-M, or C11 atomics withmemory_order_release/acquire. - Optimisation of surrounding code.
volatiledoes not make the code thread-safe, does not stop the compiler from reordering non-volatile data, and does not prevent the CPU from speculating.
| Property | volatile | _Atomic / atomic_* | __DMB() / __DSB() |
|---|---|---|---|
| Forces real load/store | yes | yes | no |
| Prevents compiler caching | yes | yes | no |
| Atomic read-modify-write | no | yes | no |
| Ordering vs other memory | volatile-to-volatile only | yes (seq_cst) | yes (explicit) |
| Stops CPU reordering | no | yes (with barriers) | yes |
Failure modes to name
- Polling loop that never exits after
-O2: inspect the disassembly: oneLDRbefore the loop label. - Lost counts on a
volatilecounter shared with an ISR: reproduce with a scope on a GPIO toggled in the ISR. - Torn data on a weakly-ordered core (Cortex-A) when the flag is volatile but the payload is not: fix with
__DMB()or atomics.
For a 32-bit memory-mapped register, also match the access width: use uint32_t, not uint8_t, and respect read-clear or write-1-to-clear semantics. volatile is necessary for MMIO and ISR flags, but it is not a substitute for atomics or barriers.
Curated: · Written: · Reviewed: —
Q&A-3You write GPIO BSRR then spin 2 cycles and sample the pin on an input. It is still low. Why is volatile not enough?
Three things have to be true before IDR reads high, and volatile only covers the first.
- The compiler must emit the store and keep the load after it. That is
volatile. - The store must complete at the GPIO peripheral. That is a bus/barrier concern, not a C keyword.
- The pad voltage must rise past the input threshold. That is analog, and it takes nanoseconds to tens of nanoseconds.
Two cycles at 80 MHz is 25 ns. If the pad needs longer, IDR reads 0 no matter how correct the C is. volatile is a compiler constraint; it has no opinion about the bus or the pad.
Assumptions: Cortex-M4 (STM32F407), GPIO on AHB1, push-pull output, IDR read back on the same pin, 80 MHz HCLK.
Layer by layer
volatile: without it the compiler may delete the BSRR store outright (nothing in the abstract machine observes it) or hoist the IDR load above it. With it, the store is emitted and ordered against other volatile accesses. It emits no barrier instruction and does not stop the CPU's write buffer from holding the store.- DSB: drains the write buffer so the AHB write to BSRR has completed and another bus master (DMA, second core) would see it. It returns when the bus transaction is done, not when the pad has settled. On Cortex-M, Device accesses are already ordered against each other, so the IDR load is not issued before the BSRR store completes at the bus interface, which is exactly why the failure here is the pad, not the ordering.
- Pad: the driver charges C_load. Rise time comes from drive strength and load, and it lives in the datasheet's I/O AC characteristics (t_r(IO)out at the stated C_L), not in the core manual.
Worked example (80 MHz, 12.5 ns/cycle, 22 pF probe load)
| Step | Time after store | State |
|---|---|---|
| BSRR store issued | 0 | write buffer holds it |
| DSB retires | ~2 cycles | AHB write complete, BSRR updated |
| two NOPs | 25 ns | CPU has moved on |
| IDR load | 25 ns | pad still below V_IH, reads 0 |
| pad crosses V_IH | ~40 ns (scope) | IDR would read 1 |
The firmware takes the "pin stuck" branch; a later loop sees the rise and the LED looks fine.
What to do instead
Do not spin a fixed cycle count. Poll IDR with a timeout, or wait the datasheet rise time plus margin, or scope the pad. If the pin drives another chip, the consumer's setup time is the deadline, not your CPU's.
What would change this
A scope showing the pad crossing V_IH inside 25 ns at this drive strength and load means the two-cycle spin is fine and the bug is elsewhere: wrong pin, wrong mode, wrong BSRR bit, or the read hitting a different port. If removing DSB makes the failure disappear, the write buffer was the culprit, not the pad. Open-drain or a heavier load only widens the pad delay and makes the race worse.
Curated: · Written: · Reviewed:
Q&A-106The timer ISR updates a 64-bit sample counter and an aligned 16-bit ADC value; the main loop reads both. You marked them volatile. The 64-bit read is still torn. What does volatile actually guarantee, and what do you use instead?
Assumptions first: single Cortex-M core, no data cache, the ISR preempts the main loop, and the shared objects are a 64-bit counter and an aligned 16-bit ADC value. Under those, volatile is necessary but not sufficient, and the gap is atomicity and ordering, not visibility.
volatile tells the compiler the object can change outside the program's control. It must emit every load and store, and it must not keep the value in a register across a sequence point. That fixes the main loop that reads a flag once and caches it forever. It does not make a read-modify-write atomic, it does not stop the compiler moving a non-volatile store past a volatile one, and it does not order anything at the hardware level.
Atomicity is about width. On a 32-bit MCU an aligned 32-bit load or store is a single instruction and is atomic against an ISR on the same core. A uint64_t is two instructions; the ISR can fire between them and you get a torn value: high half from before the update, low half from after. A struct is worse. On an 8-bit MCU even a uint16_t is torn. So the first question is always: how wide is the object, and is it aligned?
Ordering is about the compiler. This is the classic bug:
buf[i] = sample; // non-volatile
flag = 1; // volatile
The compiler can move the store to buf after the store to flag, because volatile only orders volatile accesses against each other. The reader sees flag set and reads stale data. A release fence before publishing flag, and an acquire fence after reading it, fixes it. On Cortex-M, __DMB() from CMSIS is the barrier; for compiler-only ordering, atomic_signal_fence(memory_order_seq_cst) or an empty asm with a memory clobber.
The toolkit, in order of preference:
- Lock-free single-producer single-consumer. If exactly one context writes and one reads, nobody needs to block. A ring buffer with head and tail, each index written by one side only:
#define RB_SIZE 256
static volatile uint8_t rb_buf[RB_SIZE];
static volatile uint32_t rb_head; // ISR writes
static volatile uint32_t rb_tail; // main writes
void TIM2_IRQHandler(void) {
uint32_t next = (rb_head + 1) & (RB_SIZE - 1);
if (next != rb_tail) {
rb_buf[rb_head] = read_sample();
__DMB(); // publish data before head
rb_head = next;
} else {
overrun_count++;
}
}
int rb_get(uint8_t *out) {
if (rb_tail == rb_head) return 0;
*out = rb_buf[rb_tail];
__DMB(); // consume data before tail
rb_tail = (rb_tail + 1) & (RB_SIZE - 1);
return 1;
}
The DMB is a compiler barrier plus a hardware barrier. On a single core with no cache the hardware part is mostly belt-and-braces; the compiler part is what stops the reorder. If you prefer C11, _Atomic uint32_t with memory_order_relaxed for the indices and memory_order_acquire/release on the publish is the same thing with the compiler's help.
-
Briefly disable interrupts.
uint32_t pm = __get_PRIMASK(); __disable_irq(); ... __set_PRIMASK(pm);: save and restore, never a blind__enable_irq(). Keep it to a handful of instructions. CPSID takes effect after a couple of cycles, and the longest instruction in the section adds to it. At 168 MHz, 20 cycles is 119 ns; that is invisible to a 50 µs PWM period and fatal if you hold it for 2 µs. -
RTOS critical section.
taskENTER_CRITICAL()on FreeRTOS Cortex-M raises BASEPRI toconfigMAX_SYSCALL_INTERRUPT_PRIORITY, masking only ISRs at or below that priority. Higher-priority ISRs still run. That is the right tool when tasks and ISRs share the data.
Why not a mutex: a mutex is a blocking object. Taking one can suspend the caller and call into the scheduler. FreeRTOS's xSemaphoreTake with a non-zero timeout is illegal from an ISR, and the FromISR variants don't cover mutexes because priority inheritance has no meaning for an ISR. An ISR that blocks is a deadlock waiting for the next interrupt.
Failure modes to name: torn 64-bit timestamp (read high, read low, read high again and retry if changed. A seqlock), flag-before-data reorder, ring buffer full/empty ambiguity (keep one slot open or carry a count), and silent overrun (count drops and expose them). Detect with a sequence counter or a watchpoint, but remember the watchpoint changes the timing.
Curated: · Written: · Reviewed: —
Q&A-7The datasheet says bits 31:16 of CR1 are reserved, must be kept at reset. You OR in 0xFFFF0000 "for future use." What breaks?
Assumptions: a 32-bit memory-mapped control register, bits 31:16 marked reserved "keep at reset," and a reset value that is not necessarily zero. "Reserved" in a datasheet means not documented for this die: it does not mean ignored by the hardware.
The 90-second answer. Nothing may break on the bench today, and that is the trap. OR-ing 0xFFFF0000 forces 16 bits to 1 that the datasheet told you to leave alone. Three outcomes are possible and the datasheet does not tell you which: the bits are hardwired to 0 and the write is silently dropped; the bits are implemented on another stepping or a larger part in the family and you just enabled an undocumented feature; or the register has write-1-to-clear/set semantics and you just cleared or set 16 flags. If the reset value is nonzero, you also clobbered it. The safe move is to write only documented fields and leave reserved bits at their reset value.
Two ways to write the register, and when each is wrong.
- Read-modify-write with a mask of documented fields only. Portable across steppings, survives a reset value you don't know. Costs a read, and is not atomic: if an ISR writes the same register between your read and your write, you lose its update. Fix with a critical section or a set/clear alias register.
- Write a constant =
reset_value | intended_bits. No read, atomic, but only correct if you know the reset value exactly and it is identical on every part you ship. A stepping that changes the reset value makes you write stale bits. - Vendor HAL/LL. Encodes the reset value for you, but hides the mask and can lag the errata sheet.
When not to use RMW: write-only registers, or registers whose reserved bits read back garbage. There a constant is the only safe option.
Failure modes and how you catch them.
- W1C/W1S flags: OR-ing 1s clears or sets them. Detect by reading the status register before and after init.
- Undocumented implemented field: peripheral output changes. Detect by reading CR1 back and comparing to the expected field packing, then scoping the output.
- Clobbered reset value: detect by reading the reset value from a fresh part or the reference manual and asserting it.
/* STM32-style SPI_CR1: BR[2:0] at bits 5:3, SPE bit 6, MSTR bit 2.
Bits 31:16 reserved. Reset value 0x00000000. */
#define SPI_CR1_RESET 0x00000000u
#define SPI_CR1_WRITABLE 0x0000FFFFu /* documented bits only */
#define SPI_CR1_BR_DIV256 (0x7u << 3)
_Static_assert((SPI_CR1_RESET & ~SPI_CR1_WRITABLE) == 0,
"reset value must not set reserved bits");
void spi_init(void) {
uint32_t cr1 = SPI1->CR1;
cr1 &= SPI_CR1_WRITABLE; /* drop anything reserved */
cr1 |= SPI_CR1_BR_DIV256 | SPI_CR1_MSTR | SPI_CR1_SPE;
SPI1->CR1 = cr1;
}
| Reserved-bit semantics | What OR 0xFFFF0000 does | How you find out |
|---|---|---|
| Hardwired 0, write ignored | nothing today | read CR1 back |
| Implemented on another die/stepping | enables an undocumented field | read back, scope output |
| W1C / W1S flags | clears or sets 16 flags | read status before/after |
| Nonzero reset value | clobbers reset state | reference-manual reset value |
The reason to be this specific is that the failure is silent: the register reads back plausibly, the peripheral still runs, and the bug only shows up on the part or stepping where those bits are real. Read CR1 after init, require it to equal the documented field packing, and scope the peripheral's output against the intended timing.
Curated: · Written: · Reviewed:
Q&A-5You set RCC enable then write the USART BRR in the next instruction. BRR reads back 0. What happened?
The RCC enable is a posted write, and the USART's clock does not start the moment the bit lands. Your store to BRR ran while the peripheral still had no clock, so it was discarded, and the read that followed returned 0 because the USART was not yet driving the bus. BRR is still at its reset value, 0x0000.
Why the store vanishes
RCC->APB2ENR |= USART1EN is a read-modify-write that retires in the core immediately. The write is buffered in the AHB-to-APB bridge and forwarded to the RCC later; nothing back-pressures the core. The clock gate for USART1 opens a few AHB cycles after the enable bit is committed. In that window the USART has no clock: APB writes to it are ignored (no fault, no error flag), and reads return 0 because the peripheral is not responding. Both symptoms come from the same cause: you touched the peripheral before its clock existed.
The fix
Read the enable register back before touching the peripheral:
/* CMSIS device headers, STM32F4 */
RCC->APB2ENR |= RCC_APB2ENR_USART1EN;
(void)RCC->APB2ENR; /* drain the posted write; clock is now up */
USART1->BRR = 0x2D9; /* 84 MHz APB2, 16x oversampling, 115200 */
USART1->CR1 = USART_CR1_UE | USART_CR1_TE;
The read-back forces the posted write to complete before the BRR store issues. A DSB before the read is belt-and-braces; the read-back is the part that matters.
What BRR should hold
| APB2 | Oversampling | BRR | Resulting baud |
|---|---|---|---|
| 84 MHz | 16x | 0x02D9 (45 + 9/16) | 84e6/(16 x 45.5625) = 115,226 |
| 84 MHz | 16x | 0x0000 (store dropped) | divider is zero: no usable clock, TX idle |
| 84 MHz | 16x | 0x02D9 | 115,200, error +0.023% |
84e6 / (16 x 115200) = 45.5729; mantissa 45, fraction round(0.5729 x 16) = 9, so BRR = (45 << 4) | 9 = 0x02D9.
Why it is easy to miss
Nothing faults. On APB peripherals a gated access is silently ignored, so the LED task keeps blinking and the code looks fine. The only symptom is on the wire: TX idles, or a receiver reports framing errors because it is sampling a line that never transitions. On AHB peripherals (DMA, some GPIO banks) the same mistake can raise a bus fault instead, which is why the failure mode differs by bus.
How I would confirm it
Dump BRR over SWD after the read-back and require 0x02D9 for 84 MHz APB2 at 16x oversampling. Then scope TX and check the bit time: 1/115200 = 8.68 µs.
Curated: · Written: · Reviewed:
Q&A-93You disable USART clock then write CR1. The write is ignored. You re-enable and the old CR1 is back. What did you read?
You read the reset value: CR1 = 0x0000. Not the value you wrote, and not a preserved configuration: the register file was never written, so there was nothing to preserve. The symptom reads as "the old CR1 is back" only because the old value was already 0x0000, which makes a dropped write and an untouched register indistinguishable.
Why the write vanishes
CR1 sits in the USART register block, clocked by the peripheral clock on APB1/APB2. RCC's USARTxEN bit gates that clock. With it stopped, the flops in the register file get no clock edge, so the data the APB bridge presents is never latched: the store is dropped at the peripheral boundary. The read path is the same block, so it drives whatever the flops hold. On the STM32 families I've checked the read returns 0x0000 and does not fault; some families raise a bus fault on a gated access instead. That is the one family-dependent claim here: check your reference manual before relying on either.
The experiment that settles it
The premise hides the answer because the old value was already the reset value. Configure first, then gate, then write:
| Step | CR1 read back |
|---|---|
| after reset | 0x0000 |
| clock on, write CR1 = UE|TE|RE = 0x200C | 0x200C |
| clock off, write CR1 = 0x0000 | write dropped |
| clock on, read CR1 | 0x200C: the gated write never landed |
If the last read is 0x0000 instead, your part also clears the register file when the clock is gated. Either way the gated write did not land; only the retention differs.
The order that works
RCC->APB1ENR |= RCC_APB1ENR_USART2EN; // clock on
(void)RCC->APB1ENR; // read-back: ensure the enable has landed
USART2->CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE;
USART2->BRR = 0x008B; // 115200 @ 16 MHz PCLK
__DSB(); // let the writes complete before gating
// ... operate ...
RCC->APB1ENR &= ~RCC_APB1ENR_USART2EN; // gate only when idle
Trade-offs
- Configure-then-gate is the default: enable, configure, operate, gate when idle. The gate saves the USART's own dynamic power, which is real if the link is idle for long stretches.
- Gate-with-retention: on families that hold the register file across a gate, you can re-enable and resume with the configuration intact. That is the case where "the old CR1 is back" is genuinely the old value.
- The rule is not "never gate." It is "never write while gated." Gating during idle is still worth doing.
Failure mode and detection
The failure is silent: the write returns, no fault, and the peripheral is dead. Detect it by reading CR1 back after the sequence and requiring UE=1, and by confirming a bit on TX: at 115200 8N1 one bit is 8.68 µs, so a loopback capture shows the start bit within a few microseconds of the write. If CR1 reads 0x0000 after you set UE, the clock was gated when you wrote.
Curated: · Written: · Reviewed:
Q&A-97You init USART before GPIO AF and before PLL. Baud is 9,600 on a 16 MHz HSI, then PLL goes to 80 MHz. What is the on-wire baud?
48,000 baud.
The USART's baud rate is produced by dividing its clock input by the divider stored in BRR. BRR is a register value, not a frequency. You wrote BRR while the USART was clocked from HSI at 16 MHz, so the divider is sized for 16 MHz. When the PLL takes over and the USART's clock input becomes 80 MHz, 5× higher, the same BRR value divides a 5× faster clock. The on-wire baud is 9,600 × 5 = 48,000.
GPIO AF configuration is irrelevant here; it only routes the pin to the peripheral. The PLL change is what moves the baud.
Why, exactly.
For oversampling 16 (OVER8=0), USARTDIV = f_ck / (16 × baud), and BRR holds USARTDIV with a 4-bit fraction. At 16 MHz, 9,600 baud:
USARTDIV = 16,000,000 / (16 × 9,600) = 104.1666... BRR = (104 << 4) | round(0.1666 × 16) = 0x0683
The actual divider is 104 + 3/16 = 104.1875, so the actual baud is 16e6 / (16 × 104.1875) = 9,595: 0.05% low. After the PLL, BRR is unchanged:
| Stage | f_ck | BRR | On-wire baud |
|---|---|---|---|
| USART init on HSI | 16 MHz | 0x0683 | 9,595 |
| After PLL | 80 MHz | 0x0683 | 47,990 |
So the on-wire rate is ≈ 47,990 baud, nominally 48,000: five times the intended 9,600. A receiver expecting 9,600 sees a bit time of ~20.8 µs instead of 104 µs and will frame-error.
Two fixes, and when each is acceptable.
-
Recompute BRR after the PLL is up. Disable the USART (clear UE), write the new BRR for the real PCLK, set UE again. This is the minimal fix and is fine when the USART hasn't transmitted yet: you correct the divider before the first character. It's also the fix when you can't change the init order, e.g. a vendor or bootloader sequence you don't control.
-
Re-init in the correct order: clocks first (including PLL), then GPIO AF, then USART. This is the general fix and the one to prefer in new code, because it makes the dependency explicit and removes the class of bug. It costs a few lines of reordering and no runtime.
If the USART is already enabled and running when the clock changes, neither fix is safe without first disabling it: the reference manual requires UE=0 before changing the clock, and a character in flight can be corrupted.
Failure modes.
- Framing errors on the far end: the peer samples at 9,600 while you transmit at 48,000, so the stop bit lands in the wrong place. On a scope the bit time is ~20.8 µs, not 104 µs.
- Silent loopback: TX-to-RX on the same MCU uses the same wrong clock on both ends, so the loopback passes and the bug ships. Test against a known-good peer or a scope.
- Any PCLK change (prescaler change, PLL on/off) has the same effect. The invariant is: BRR is only valid for the clock it was computed against.
How to verify.
Measure the TX bit time after init and require 104 µs ±2% for 9,600 baud. Assert that SystemCoreClock and the actual PCLK match what BRR was computed for. A one-line check in the init path catches this before the first character goes out.
Curated: · Written: · Reviewed:
Q&A-94PB3 is SWO in AF0 and UART TX in AF7. You enable both. The console is garbage. Who owns the pin?
Who owns it: whoever wrote GPIOB_AFRL last. On a normal boot that is the debug init, so PB3 ends up as SWO (AF0) and the UART's TX is no longer connected to the pad. The UART does not know this.
Mechanism
STM32 alternate functions are not arbitrated. Each pin has exactly one 4-bit field in GPIOx_AFRL (pins 0–7) or GPIOx_AFRH (pins 8–15). PB3 is bits [15:12] of GPIOB_AFRL. Writing AF7 and then AF0 leaves 0b0000 in that field: the second write overwrites the first, with no error and no lock. Both peripherals stay enabled: USART_CR1.TE is still set, DBGMCU_CR.TRACE_IOEN is still set. Only the mux field decides which one reaches the pad.
So the UART keeps shifting. TXE empties, TC sets at the bit rate, the shift register clocks bits out: into a pin now driven by the trace unit. Nothing in the USART status registers shows a problem.
Why garbage, not silence
The terminal decodes whatever edges the trace unit puts on the line at 115200. If SWO is emitting, its edges run at the SWO clock (2 MHz → 0.5 µs/bit) and the UART receiver frames them as random bytes. If SWO is idle, the line sits high and you may see nothing at all: "garbage" is the case where SWO is active.
GPIOB_AFRL [15:12] | Pin function | What the UART sees |
|---|---|---|
AF7 (0b0111) | USART TX | correct |
AF0 (0b0000) | SWO | TX register still shifts, pad not driven by USART |
Detection, in order
- Read
GPIOB_AFRLand mask bits [15:12].0= SWO owns the pin,7= UART owns it. This is ground truth. - Scope PB3 during a known byte. UART at 115200 8N1 is 8.68 µs per bit; SWO at 2 MHz is 0.5 µs per bit. The bit period tells you which peripheral is driving.
- Check
DBGMCU_CR.TRACE_IOEN. If SWO is enabled and you don't need it, that is the write to remove.
Options, and when each wins
- Move the UART. Remap the USART to another TX pin, or use a different USART instance. Wins when you need SWO for ITM tracing during development and the UART is the flexible one.
- Disable SWO. Clear
TRACE_IOENso debug init never writes AF0. Wins when you need the UART in production and only use SWO occasionally. Cost: no ITM printf. - Rely on init order. Fragile: it depends on nobody re-initialising debug later. Don't ship it.
On most STM32 parts SWO is fixed to PB3, so you usually cannot remap SWO; the UART is the one that moves.
Failure mode
Debug init running after UART init, or a re-init on debugger attach, silently steals the pin. It is caught by the AFRL read, not by the UART error flags: the USART reports success the whole time.
Curated: · Written: · Reviewed:
Q&A-83You use the same 48-bit MAC from a header file on every board. Provisioning thinks there is one device. What ID did you skip?
The ID you skipped is the per-die unique ID the fab programs into the silicon. STM32 documents it as a 96-bit unique device ID; Nordic exposes a 64-bit DEVICEID in FICR; ESP32 keeps a factory MAC in eFuse. The MAC in your header file is a build constant, the same six bytes linked into every image, so it identifies the firmware, not the board.
That is what breaks provisioning. Your cloud registry, DHCP lease table, MQTT client ID and device certificate are all keyed on the MAC. Twenty thousand boards present the same address, so the registry holds one row, one certificate and one session. The boards then evict each other from the broker in a loop, and the fleet looks like a single device that flaps.
Read the UID at first boot, derive the MAC from it, and persist the result once. On STM32F4 the UID lives at 0x1FFF7A10; the address differs by family, so check the reference manual's "Unique device ID" section rather than copying an address from a forum post.
#include <stdint.h>
/* STM32F4: 96-bit UID at 0x1FFF7A10. Address varies by family. */
#define UID_BASE ((const uint32_t *)0x1FFF7A10UL)
void derive_mac(uint8_t mac[6])
{
const uint32_t *uid = UID_BASE;
/* Copy 46 bits of the UID; the two low bits of the first octet
are reserved for the I/G and U/L flags. */
mac[0] = (uint8_t)(uid[0] >> 24);
mac[1] = (uint8_t)(uid[0] >> 16);
mac[2] = (uint8_t)(uid[0] >> 8);
mac[3] = (uint8_t)(uid[0]);
mac[4] = (uint8_t)(uid[1] >> 24);
mac[5] = (uint8_t)(uid[1] >> 16);
mac[0] = (uint8_t)((mac[0] & 0xFC) | 0x02); /* U/L = 1, I/G = 0 */
}
Trace the last line: mac[0] & 0xFC clears bits 0 and 1, then | 0x02 sets bit 1 and leaves bit 0 clear. The first octet always ends in 0b10, which is a locally administered unicast address: the form you are allowed to assign yourself without an OUI. The other 46 bits are copied verbatim from the UID, so two dies with different UIDs in those bits produce different MACs.
| ID | Width | Source | Distinct across 20,000 boards |
|---|---|---|---|
| MAC in header file | 48 bits | build constant | no: one value on every board |
| Silicon UID | 96 bits | fab-programmed, read-only | yes, per die |
| Derived LAA MAC | 46 bits of UID | computed at first boot | yes, inherits UID uniqueness |
The 46-bit space holds 7.0e13 addresses. For 20,000 boards the birthday bound is about n²/2^47 ≈ 2.8e-6, so a collision is unlikely but not impossible; the real guarantee is that the UID is unique per die, and the derivation is injective on the bits it copies.
There are failure modes worth testing for. Some clone parts (CH32, GD32, certain ESP32 clones) return a constant or a non-unique value from the UID register. Detect it by reading the UID on 100 boards off the line and asserting 100 distinct values, and by comparing against the constant a known clone returns. Reading the wrong address returns flash contents or a fixed word, so verify the address against the reference manual and against a second board. The UID is readable by anyone holding the firmware, so it is an identifier, not a secret: do not use it as an encryption key or an auth token. If you need a per-device secret, put it in a secure element such as the ATECC608A and keep the UID as the lookup key.
If the part has no UID at all, some cheap MCUs and pre-certified modules, you need an external serial: a 1-Wire or EEPROM serial number, a secure element, or a factory-programmed OTP page. Key provisioning on that serial, not on the MAC, and store the derived MAC in OTP or EEPROM so it survives a firmware update.
Curated: · Written: · Reviewed:
Q&A-86You store a 32-byte key at flash address 0x0807F000. PSA ITS exists on the part. Why is the raw address a defect?
Short answer: a raw flash address is a byte container, not a key store. It gives you none of the four properties a key needs (confidentiality, integrity, atomicity, and lifecycle) and PSA ITS exists to supply them. Storing at 0x0807F000 means you have re-implemented key storage with the guarantees of a memcpy. The address is also not a UID: it has no namespace, no per-partition isolation, and it collides with whatever the linker puts there after the next firmware update.
What ITS actually gives you. You hand the service a UID and a buffer; it hands back a status. The service owns the address, the encryption, the integrity tag, the journal, and the access policy.
#include <psa/internal_trusted_storage.h>
static const psa_storage_uid_t KEY_UID = 0x0001A001;
psa_status_t store_key(const uint8_t key[32])
{
return psa_its_set(KEY_UID, sizeof key, key, 0);
}
psa_status_t load_key(uint8_t out[32])
{
size_t len = 0;
return psa_its_get(KEY_UID, 0, 32, out, &len);
}
psa_its_set returns PSA_SUCCESS or a defined error: PSA_ERROR_INSUFFICIENT_STORAGE, PSA_ERROR_ALREADY_EXISTS, PSA_ERROR_NOT_PERMITTED, PSA_ERROR_STORAGE_FAILURE. The raw address returns nothing; a failed flash program is something you have to notice yourself.
The four defects, in the order they bite.
-
Confidentiality.
0x0807F000sits in the same address space as your application. Any code with a pointer reads it: a buffer overrun, a logging path, a debug probe on an open RDP level. ITS keeps the key encrypted at rest under a device key held in the secure processing environment, and the non-secure app never sees the plaintext address. -
Integrity. Flash bits flip: retention, read disturb, a half-finished erase. A raw 32-byte key has no tag, so a flipped bit yields a wrong key that gets used silently. ITS verifies a MAC on read and returns
PSA_ERROR_DATA_CORRUPTinstead. -
Atomicity. This is the one that shows up in the field. Take a part with a 16-byte flash program unit and a 32-byte key:
t=0 ms erase sector, all 0xFF
t=1 ms program bytes 0..15 -> new key, first half
t=2 ms VDD drops
t=3 ms program bytes 16..31 never runs
next boot: bytes 0..15 = new key, bytes 16..31 = 0xFF
No error is raised. The device derives from a key that is half new and half erased. ITS journals the write: after a brownout you read either the old value or the new one, never a mix.
- Lifecycle. A fixed address has no destroy, no write-once, no rollback protection, and no wear leveling: you rewrite the same sector every rotation until it hits the erase limit (typically 10k cycles on STM32-class flash; check the datasheet). ITS gives you
psa_its_remove, a write-once flag where the driver supports it, and a wear-leveled backing store.
Where the hedge belongs. PSA ITS is not a magic word. The PSA Secure Storage API requires confidentiality and integrity; rollback protection and wear leveling are implementation-defined, and the PSA Certified profile your part claims decides what is actually in scope. So the correct move is not "use ITS and relax": it is "use ITS, then read the driver's documented guarantees and the certification level, and name them." If the driver does not provide replay protection and you need it, that is a gap to close, not an assumption to make. (TF-M's older Protected Storage service predates ITS.)
How I would prove it. Brownout during psa_its_set 40 times and require 40 good keys or a defined empty result: never a 16-byte mix. Then read the key back through the non-secure app and confirm it cannot name the address at all.
Curated: · Written: · Reviewed:
Q&A-1The map file shows .text plus .rodata larger than the 512 KiB flash. The image still flashes. What failed?
What failed: the declared flash size, in two places.
GNU ld does enforce a MEMORY region's LENGTH. Give it FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K and a 530,944-byte image, and the link fails: ld reports the region overflowed by 6,656 bytes and exits non-zero. So a link that succeeded on this image proves the script's LENGTH is not 512K. It is 1M, copied from a sibling part, or the script has no MEMORY region at all and just places sections with . = 0x08000000; and no bound.
The probe runs the same check, against the flash bank size in its target config. OpenOCD and J-Link both refuse a write past the bank they were told about. The image still flashes because that config carries the same wrong number: the probe believes the part has 1 MiB, so 0x08081000 is in range as far as it knows. It writes, reports success, and the flash controller, which does not implement those addresses, never stores the bytes past 0x0807FFFF.
The board boots because the vector table at 0x08000000 sits inside the written region. It dies the first time it calls a function placed past the end. Fetching from 0x08081000 returns 0xFFFFFFFF (an undefined instruction) or raises a bus fault; either escalates to HardFault. If HardFault_Handler is itself past the end, the core locks up.
Trade-offs
- Shrink the image. Right when you own the code and the 6,656 bytes are fat you can cut:
-Os, LTO, drop an unused library, move a const table to external flash. Costs engineering time, and may not exist if the code is already tight. - Bootloader + app. Right when you need field updates anyway. A 32 KiB bootloader plus a 480 KiB app fits, and you get A/B and recovery. Costs bootloader complexity and 32 KiB of the flash you were already short of.
- Programmer verify. Right as a second check, never the first. It only covers the region the probe wrote; it cannot see a tail that has no address. And it depends on the probe's config being right, which is the thing that was wrong.
Detection
The check that catches this is a size comparison, not a CRC. CRC the physical 524,288 bytes against the first 524,288 bytes of the .bin and they match: the truncation is invisible, because the dropped tail was never addressed. Compare the map's LOAD size (530,944) to the datasheet flash size (524,288) instead, and fail the build on it.
Belt and braces for scripts without a MEMORY region:
FLASH_LENGTH = 512K;
ASSERT(SIZEOF(.text) + SIZEOF(.rodata) + SIZEOF(.data) <= FLASH_LENGTH,
"FLASH overflow");
.data counts at its load size, which is what lands in flash. With a MEMORY region, use LENGTH(FLASH) in place of the literal.
| Region | Bytes |
|---|---|
| FLASH LENGTH (device) | 524,288 |
| .text | 498,176 |
| .rodata | 32,768 |
| LOAD total | 530,944 |
| overflow | 6,656 |
Fix the number in the linker script and the probe config, and both stop lying.
Curated: · Written: · Reviewed:
Q&A-2The application lives at 0x0800_4000. Interrupts still hit bootloader handlers. What did you forget to write?
My first question on VTOR after bootloader handoff is which register bit actually flipped, not which breakpoint I hit.
I treat VTOR as part of the handoff contract. Relocating the image without writing SCB->VTOR leaves IRQ vectors at the bootloader's table, so the LED that the reset handler toggles is not evidence that the application's USART ISR will run.
Concretely, i write SCB->VTOR = 0x08004000 after the bootloader jumps, with a DSB, then I fire a software interrupt whose vector exists only in the application table and require that handler to run.
The reason for that specificity is a failure I have seen: I left VTOR at 0x0800_0000. USART1 IRQ 37 still entered the bootloader stub at offset 0xD4. The application printed "up" on UART from main and never received a byte. We spent two days blaming the baud rate.
IRQ 37 vector with VTOR left at the bootloader.
| Table base | IRQ 37 vector address | Who runs |
|---|---|---|
| 0x0800_0000 bootloader | 0x0800_00D4 | bootloader stub |
| 0x0800_4000 application | 0x0800_40D4 | application ISR |
I would not consider it settled without evidence: I would pend a software IRQ whose application vector writes a known SRAM cell, then read that cell on a debug probe with the bootloader table zeroed in a second capture.
Handoff is VTOR plus the stack pointer, not a branch.
Curated: · Written: · Reviewed:
Q&A-16You enable -flto --gc-sections. USART1_IRQHandler is absent and the slot is the weak Default_Handler. What root did the linker drop?
The linker dropped the section holding your strong USART1_IRQHandler, because the vector table that references it was not a garbage-collection root.
--gc-sections keeps a section only if it is reachable from the entry point or from a section marked KEEP. The vector table is the odd one out: nothing references it; it references everything else. If the linker script doesn't wrap it in KEEP, the table looks unreferenced, gets collected, and the handler it pointed at loses its only reference and goes with it. What's left is the weak alias in the startup file, USART1_IRQHandler aliased to Default_Handler, so the slot resolves to Default_Handler.
LTO is not the culprit. LTO changes what the compiler emits; it does not rewrite a live handler into the default. The drop is a section-GC decision, and it happens with or without -flto.
Confirm it in a minute. arm-none-eabi-nm firmware.elf | grep -i usart1: a W (weak) with no T (text) definition means the strong one is gone. arm-none-eabi-objdump -h firmware.elf, if .isr_vector is absent, the table was collected. The map file (-Wl,-Map=fw.map) lists both under "Discarded input sections".
The linker script should read:
.isr_vector : {
. = ALIGN(4);
KEEP(*(.isr_vector)) /* the table is the root of the IRQ graph */
. = ALIGN(4);
} > FLASH
The three fixes, and when each is right:
| Fix | Effect | Verdict |
|---|---|---|
KEEP(*(.isr_vector)) | Marks the table a GC root; handlers stay reachable | Correct default. The table is the root of the interrupt graph. |
__attribute__((used)) on the handler | Stops the compiler dropping the symbol | Not enough. used is a compiler attribute; --gc-sections is a linker pass and still collects the unreferenced section. |
Linker ASSERT / CI check | Fails the build when an enabled IRQ resolves to Default_Handler | The guard that catches this and the misspelled-name case. |
The failure mode that makes this expensive: it builds clean and fails only at runtime. Polling UART from main still works, no interrupt is involved, so a console demo passes. The first RX interrupt vectors to Default_Handler, which is typically a BKPT or an infinite loop. Detection is a CI step that parses nm/the map and fails if any IRQ you enable resolves to Default_Handler.
The look-alike: a misspelled handler (USART1_Handler instead of USART1_IRQHandler) leaves the table intact but the weak alias in place. Same symptom, different root. That's why the CI check should assert symbol resolution, not just that .isr_vector exists.
Curated: · Written: · Reviewed:
Q&A-19You store a crash PC in .noinit. After IWDG it is 0. Who cleared it?
The watchdog didn't clear it. Your startup code did.
IWDG resets the core; it does not touch SRAM. On STM32 and most Cortex-M parts, SRAM contents survive a watchdog reset, a software reset and a pin reset as long as VDD stays above the retention threshold. A breadcrumb that reads 0 after IWDG was zeroed by software, and the usual culprit is the BSS zero loop in Reset_Handler.
The mechanism: your linker script puts .noinit at 0x2000_7FF0, but the startup loop is bounded by _sbss.._ebss and _ebss sits at 0x2000_8000. Above your section. The loop writes 0x2000_7FF0..0x2000_7FFF and your 16 bytes are gone before main. The map file shows it in one line.
Confirm in five minutes:
arm-none-eabi-nmor the map file: is.noinitinside_sbss.._ebss?- Read RCC_CSR (RCC_RSR on H7): IWDGRSTF set, PORRSTF/BORRSTF clear? If PORRSTF or BORRSTF is set, the supply dipped and SRAM was lost for real: a different bug.
- Check the bootloader: does it zero RAM or use that region as stack or scratch?
The fix is section placement, not branching around BSS zeroing. Skipping the zero loop when IWDGRSTF is set is a trap: .bss holds globals that must be zero, and you would leave them holding garbage from the previous run. Keep the loop, move .noinit out of its range.
SECTIONS {
.bss (NOLOAD) : { _sbss = .; *(.bss*) *(COMMON) _ebss = .; } >RAM
.noinit (NOLOAD) : { . = ALIGN(4); *(.noinit) . = ALIGN(4); } >RAM
}
Place .noinit after .bss so _ebss never covers it, and declare the variable __attribute__((section(".noinit"))).
Alternatives, and when .noinit is the wrong tool:
| Store | Survives IWDG | Survives POR/brownout | Notes |
|---|---|---|---|
.noinit SRAM | yes, if not zeroed | no | free; needs correct linker placement |
| RTC backup registers | yes | yes (VBAT) | a handful of 32-bit words; backup domain must be clocked |
| Backup SRAM (BKPSRAM) | yes | yes (VBAT) | ~4 KB; needs VBAT |
| Retained SRAM bank | yes | part-dependent | check the datasheet retention table |
| External FRAM/EEPROM | yes | yes | BOM and bus cost |
If the breadcrumb must survive a power cycle, a brownout, or a bootloader that owns SRAM, .noinit is the wrong choice: use backup registers or backup SRAM.
Failure modes to rule out:
- Brownout alongside the IWDG: BORRSTF/PORRSTF set means SRAM was lost; the watchdog is a red herring.
- Bootloader scratch: it zeroes or reuses your region before your app starts.
- ECC SRAM (e.g. H7): reading uninitialized ECC RAM faults, so startup may initialize the whole bank. Your section included.
- Debugger "connect under reset" clears SRAM too.
Verify: write 0xA5A5A5A5 into the breadcrumb, trip IWDG, and read it back over SWD before any C++ constructor runs. If it returns 0xA5A5A5A5, placement is right; if it is 0, re-read the map file before blaming the watchdog.
Curated: · Written: · Reviewed:
Q&A-79HardFault writes PC to 0x20007FF0 then spins. After reset the word is 0. Where should it have lived?
The 60-second answer
Assuming an STM32F4-class part: 0x20007FF0 is inside SRAM1, and SRAM1 is where .bss lives. The C runtime startup (Reset_Handler in startup_stm32f4xx.s) zeroes _sbss to _ebss before it calls main, so your PC write landed and was then erased. The word should have lived in a section the startup code does not zero: a NOLOAD section placed outside the .bss range, or in backup SRAM in the VBAT domain.
Why it happened
The startup zero loop is:
ldr r2, =_sbss
ldr r4, =_ebss
movs r3, #0
b LoopFillZerobss
FillZerobss:
str r3, [r2], #4
LoopFillZerobss:
cmp r2, r4
bcc FillZerobss
_sbss and _ebss come from the linker script's .bss output section. 0x20007FF0 falls inside that range, so the loop writes 0 over your PC. The fault handler is fine; the storage was in the wrong place.
Where it should have lived
Option A: NOLOAD SRAM section. Add to the linker script:
.noinit (NOLOAD) :
{
. = ALIGN(4);
*(.noinit)
. = ALIGN(4);
} >RAM
Place it after .bss so _ebss stops before it, and declare the breadcrumb __attribute__((section(".noinit"))). NOLOAD keeps it out of the load image, and because it sits outside _sbss.._ebss the startup loop never touches it. Cost: zero. Survives reset, lost on power cycle.
Option B: backup SRAM. On STM32F4 it is 4 KB at 0x40024000, in the VBAT domain. Enable it with RCC->AHB1ENR |= RCC_AHB1ENR_BKPSRAMEN and unlock the backup domain with PWR->CR |= PWR_CR_DBP. It survives system reset and, with VBAT present, power-down. Cost: VBAT coin cell and its leakage, plus the enable sequence before use.
Option C: RTC backup registers, 20 x 32-bit at 0x40002850. Enough for PC, LR and CFSR. Survive reset, no VBAT needed for reset survival, but only 80 bytes.
| NOLOAD SRAM | Backup SRAM | RTC backup regs | |
|---|---|---|---|
| Survives reset | yes | yes | yes |
| Survives power-down | no | yes (VBAT) | yes (VBAT) |
| Size | as much as you allocate | 4 KB | 80 bytes |
| Cost | none | VBAT cell + leakage | none |
| Setup | linker + startup | RCC/PWR enable | DBP unlock |
For a breadcrumb that only needs to survive a reset, NOLOAD SRAM is the right default. Reach for backup SRAM when the board loses power and you still need the last PC.
Failure modes
- Section placed inside the
.bssrange: zeroed again, PC reads 0. Detect by reading the map file and checking_ebssis below your section. - Startup file regenerated by CubeMX: it rewrites the linker script and drops
.noinit. Detect in CI by asserting the symbol address is outside_sbss.._ebss. - Backup SRAM not enabled before the fault: writes are dropped. Detect by reading back a known pattern at boot.
Verification
Force a HardFault (dereference a bad pointer such as *(volatile uint32_t *)0xFFFFFFFF = 0;), let IWDG reset the part, and on the next boot print the stored PC and check it is in the 0x08000000 flash window. 10 of 10.
Curated: · Written: · Reviewed:
Q&A-73GDB says the PC is in HAL_Delay. The part is looping in your HardFault. What file did you load?
Short answer: a stale ELF. The file loaded into GDB is not the image running on the part. GDB resolves the PC through the symbol table of the ELF you handed it, not through anything on the chip. If that ELF is from a different build, the same address resolves to a different function: 0x08004A10 is HAL_Delay in yesterday's map and the HardFault vector or a null call site in today's. You then "fix" a delay that isn't executing.
Mechanism: the debugger reads flash for instructions but reads the ELF for names. Symbol resolution is a lookup in the ELF's .symtab / .debug_info. Nothing in that path checks that the ELF's loadable sections match what is in flash. A mismatched pair therefore produces a confident, wrong backtrace, and the LED or printf you are trusting is driven by the same wrong map.
Confirm it in the session before touching code:
(gdb) info files
Local exec file:
`/build/fw.elf', file type elf32-littlearm.
Entry point: 0x080001c1
(gdb) compare-sections
compare-sections reads target memory and diffs it against the ELF's loadable sections, flagging each section that differs. A mismatch on .text means the ELF is not the flashed image. That is the cheapest check and it needs no extra tooling.
Then the alternatives, and when each is worth it:
| Check | Cost | Catches |
|---|---|---|
compare-sections in GDB | one command, live target | any byte difference in loadable sections |
| CRC flash range vs CRC of ELF load segments | programmer plus an objcopy/readelf script | same, works headless in CI |
| Build-id stamped at a known flash address | build step plus one SWD read | mismatch before you even attach |
When the ceremony isn't worth it: single-developer bench, you flashed the image yourself seconds ago from the same build directory, no second bank, no bootloader. Then compare-sections is enough and a build-id scheme is overhead. It earns its keep when there are two images (bootloader plus app, bank A/B), a CI artifact you didn't build, or a board someone else flashed.
Other failure modes that look identical: a wrong linker script so the ELF's load address is off by a bank; a partial flash where erase succeeded and program failed; a bootloader jumping to bank A while you debug bank B; GDB picking up a cached ELF from a stale path. All of them present as "PC in a function that isn't running."
Settle it with evidence: matching build-id or a clean compare-sections, then a PC that lands in the HardFault handler's file and line.
Curated: · Written: · Reviewed:
Q&A-77printf goes through SYS_WRITE. There is no debugger. The core sits on BKPT. What library did you link?
newlib's semihosting library: librdimon.a, pulled in by --specs=rdimon.specs, and also by the stock arm-none-eabi-gcc link when nobody overrode the specs. Everything you are seeing follows from that one line.
The chain is: printf formats into the FILE buffer, the flush calls _write(fd, buf, len), and rdimon's _write is not a memory write at all. It is a semihosting request. r0 takes the operation number 0x05 (SYS_WRITE), r1 points at a three-word parameter block holding the handle, the buffer and the length, and the core executes BKPT 0xAB. That is the Thumb semihosting entry point, halfword 0xBEAB, which is the two bytes AB BE in a little-endian image.
The "no debugger" part is what makes it fatal rather than merely odd. On ARMv7-M a BKPT with the debugger disabled (DHCSR.C_DEBUGEN clear) is not a breakpoint the core can stop on; it escalates to HardFault. So the PC you are staring at is the semihosting instruction, parked in the fault handler. The same image on the bench, probe attached, prints to the IDE console as if nothing were wrong. That asymmetry is the bug: you cannot reproduce it in the configuration you test in.
Confirm it on the ELF, not on the board:
arm-none-eabi-objdump -d build/fw.elf | grep -n bkpt # look for: bkpt 0x00ab
grep -o librdimon.a build/fw.map # needs -Wl,-Map=build/fw.map
Any bkpt 0x00ab outside a deliberate debug stub is semihosting. You can make the field failure self-diagnosing too: in the fault handler dump SCB->CFSR and the stacked PC from the exception frame, and symbolise it against the map. It lands in _write.
The link options are not interchangeable:
| Specs you pass | Syscall backend | Where output goes |
|---|---|---|
--specs=rdimon.specs (and the default link) | libgloss librdimon.a, semihosting | Debugger console; HardFault with no probe |
--specs=nosys.specs | libnosys.a stubs | _write returns -1 with errno ENOSYS; output discarded |
--specs=nano.specs | newlib-nano, same callbacks | Unchanged: a size change, not a backend change |
--specs=nosys.specs plus your own _write | yours | UART, ITM/SWO or RTT |
Row three catches people: nano.specs alone fixes nothing, because it swaps the C library, not the syscall implementation.
The fix is to own _write. A strong definition in one of your own object files wins over the archive member, so rdimon's _write never gets pulled in:
/* arm-none-eabi-gcc --specs=nosys.specs ... plus this translation unit */
#include <errno.h>
#include <unistd.h>
#include <stdint.h>
int _write(int fd, char *buf, int len)
{
if (fd != 1 && fd != 2) { errno = EBADF; return -1; }
for (int i = 0; i < len; i++) {
while (!(USART2->SR & USART_SR_TXE)) { }
USART2->DR = (uint8_t)buf[i];
}
return len;
}
Return len. A short return makes libc think the write failed and retry; -1 with errno silently drops the output.
Two things bite after the swap. nosys also stubs _sbrk to fail, so any printf path that allocates (%f, setvbuf, a big %s) breaks with no message; give _sbrk a real heap. And under nano.specs, float formatting is only linked if you pass -u _printf_float.
Gate it in CI: a bkpt in the disassembly should fail the build the way a forbidden symbol does. Then the detached run, no probe, 60 s, current at the idle figure rather than the run figure. Semihosting also costs a debug round trip per flush, so keep the comparison in your pocket: a 115200 8N1 UART is 86.8 us per character (10 bits at 8.68 us per bit).
On Arm Compiler rather than arm-none-eabi the same default exists: the standard library routes through semihosting until you define __use_no_semihosting and retarget.
Curated: · Written: · Reviewed:
Q&A-20crc32() calls itself on 512-byte chunks. The task stack is 1,024 bytes. When does it die?
It dies at depth 15, a payload of about 8 MiB, if the caller is holding 400 bytes of the 1,024-byte stack. If the whole 1 KB is free to the CRC, it survives to depth 23 and dies at depth 24, roughly a 4 GiB payload. Both numbers assume a 44-byte frame, which is the one thing you must measure on your build, not guess.
Why depth is the whole story
Splitting in half means the recursion depth is logarithmic in the payload, not linear. Each level consumes one frame and hands the halves down:
depth = ceil(log2(payload / 512)) + 1
The +1 is the base case: a payload of 512 bytes or less never recurses, so it costs exactly one frame. Stack used is depth × frame. With a 44-byte frame:
| Payload | depth | Stack used | Fits 1,024 B alone? | Fits with 400 B caller? |
|---|---|---|---|---|
| 512 B | 1 | 44 B | yes | yes |
| 32 KiB | 7 | 308 B | yes | yes |
| 1 MiB | 12 | 528 B | yes | yes |
| 4 MiB | 14 | 616 B | yes | yes |
| 8 MiB | 15 | 660 B | yes | no: overflow |
| 16 MiB | 16 | 704 B | yes | no |
| 4 GiB | 24 | 1,056 B | no: overflow | no |
So the answer to "when does it die" is not a payload size in the abstract: it is a depth, and the payload that reaches that depth depends on how much of the stack the caller has already spent. The 400-byte caller is what moves the cliff from 4 GiB down to 8 MiB. That is a factor of 512 in payload for a fixed 400 bytes of caller frame, because depth only grows by one per doubling.
What the failure looks like
A stack overflow on a Cortex-M with no MPU guard region does not fault cleanly. The recursion walks the stack pointer down past the end of the task stack into whatever the linker placed below it, often the heap or another task's stack, and corrupts it silently. You get a HardFault later, at an address unrelated to the CRC, or you get a wrong checksum and no fault at all. If you have an MPU region or a stack-limit register armed, you get an immediate MemManage/HardFault at the offending store, which is the only version of this you can debug quickly.
How to know your number instead of mine
-fstack-usage(GCC) emits a.sufile with the exact frame size per function. That 44 is a placeholder until you read yours.- Fill the stack with a known pattern at task start and scan for the high-water mark after a worst-case CRC. The gap between the watermark and the stack limit is your real headroom; keep it above 64 bytes.
- Assert
depth < MAX_DEPTHinside the recursive function. A depth counter costs one register and turns a silent corruption into a trap.
The fix
Recursion buys nothing here. A CRC is a fold over the buffer; write it as a loop and depth is 1 regardless of payload. If you must keep the recursive shape, note that tail-call optimisation does not save you: only the second half is in tail position, the first-half call still nests, so depth stays log2. The loop is the answer.
One caveat on the arithmetic: if your frame is not 44 bytes, recompute. A 64-byte frame drops the with-caller limit to depth 9 (576 B), which is a 2 MiB payload: the cliff moves by another factor of 4.
Curated: · Written: · Reviewed:
Q&A-6The process stack is 2,048 bytes. How do you make a 64-byte overrun a MemManage, not silent corruption of the TCB?
Core answer (first 90 seconds)
Assume a Cortex-M with an MPU (ARMv7-M or ARMv8-M), FreeRTOS, a full-descending stack, and the TCB laid out in RAM directly below the task stack. The fix is one no-access MPU region sitting between the bottom of the usable stack and the TCB.
- Size the guard at least as large as the largest single stack frame the task can allocate, 64 bytes here, and align its base to its size (MPU regions are power-of-two and must be aligned to their size, so a 64-byte guard is 64-byte aligned).
- Program it as AP=no-access, XN=1, ENABLE=1.
- Enable the MPU and the MemManage fault (MEMFAULTENA in SHCSR).
Now the first store that crosses the stack bottom lands in the guard. The MPU checks every data access, so that store raises a MemManage fault (DACCVIOL) synchronously, before the write retires. The TCB is never touched.
Why 64 bytes must fit inside the guard
The compiler allocates a frame with a single sub sp, sp, #64 at function entry and then writes. The first store lands at SP-64. If the guard is only 32 bytes, SP-64 is below the guard, in the TCB: silent corruption, exactly what you are trying to avoid. The guard must be at least as large as the largest single downward SP adjustment, so the first store after it still lands inside the guard. A 64-byte frame needs a guard of 64 bytes or more.
Arithmetic
2048-byte stack, 64-byte guard. Either keep 2048 usable and place the guard below it (needs 64 bytes of RAM between stack and TCB), or carve the guard out of the 2048, leaving 1984 usable. Carving is free but shrinks the stack; adding keeps the stack and costs RAM.
Setup
// Cortex-M4, ARMv7-M MPU. 64-byte no-access guard, 64-byte aligned.
#define GUARD_BASE 0x2000FFC0u // bottom of task stack, 64-byte aligned
MPU->RBAR = GUARD_BASE | (1u << 4); // VALID, region 0
MPU->RASR = (1u << 28) // XN
| (0u << 24) // AP = no access
| (5u << 1) // SIZE: 2^(5+1) = 64 B
| (1u << 0); // ENABLE
SCB->SHCSR |= (1u << 16); // MEMFAULTENA
Handler
void MemManage_Handler(void) {
uint32_t mmfsr = SCB->CFSR & 0xFFu;
if (mmfsr & (1u << 1)) { // DACCVIOL
uint32_t addr = SCB->MMFAR; // valid when MMARVALID (bit 7) set
// addr inside the guard -> overflow in the task that owns that stack
}
for (;;);
}
Alternatives
- ARMv8-M PSPLIM: set PSPLIM to the stack limit; any access below faults. No MPU region consumed, and it is per-thread. Preferred on M23/M33/M35P.
- FreeRTOS configCHECK_FOR_STACK_OVERFLOW: a canary checked at context switch. It detects after the corruption has happened, so it is a backstop, not a guard.
- MPU region budget: M3/M4 have 8 regions. One guard per task eats a slot; with many tasks you cannot guard them all. PSPLIM or a shared guard scheme scales better.
Failure modes
- Guard smaller than the largest frame: the overrun skips it.
- Guard base not aligned to its size: the MPU rejects the config or covers the wrong range.
- MemManage not enabled: the fault escalates to HardFault and MMFAR may be stale unless you read it in the handler.
- MPU disabled in some path (bootloader, some RTOS critical sections): the guard is inactive.
Verification
Force a 64-byte local in the task, require a MemManage with MMARVALID set and MMFAR inside the guard, and confirm the TCB canary is unchanged.
Curated: · Written: · Reviewed:
Q&A-12The UART ISR does pvPortMalloc(64) to stash a line. Why is that a field-reset even if it usually works?
The trade-off in malloc from a UART ISR is which failure I am willing to ship, and I will not ship an unmeasured one.
I never allocate from an ISR. FreeRTOS heap_4 takes the scheduler lock or a critical section, not a task mutex. FromISR malloc can deadlock a task that already suspended the scheduler, or it can NULL-deref.
Concretely, i use a static pool or a FromISR queue of pointers into a preallocated ring, sized to the burst I measured, and I count drops rather than growing.
The reason for that specificity is a failure I have seen: At 115,200 baud a 64-byte line every 6 ms is 10,667 bytes/s. The ISR called pvPortMalloc. After 40 minutes the heap had 3 free blocks of 32 bytes and malloc returned NULL. The ISR wrote to 0. HardFault. A second crash was a task in vTaskSuspendAll around malloc when the ISR also entered the heap critical section. The LED had been green in the 5-minute demo.
64-byte lines malloc'd in the USART ISR.
| Item | Value |
|---|---|
| baud | 115,200 |
| line every | 6 ms |
| bytes/s | 10,667 |
| time to heap stall | 40 minutes |
| demo that passed | 5 minutes |
I would not consider it settled without evidence: I would run a 1-hour soak with heap tracing disabled in the ISR and a watermark on the static pool, requiring zero ISR allocations in the map file and zero NULL paths.
Heap is a scheduler lock. The ISR is not a task.
Curated: · Written: · Reviewed:
Q&A-15now is 2,147,483,647 ticks. deadline is now + 200. The wait returns immediately. What rule did you break?
The rule: a timeout is the difference between two tick readings, never an absolute deadline compared against now.
You computed deadline = now + dt and then tested now >= deadline. On a fixed-width counter that wraps, that test is wrong the moment now + dt overflows. The correct form compares the elapsed difference, with the subtraction done in unsigned arithmetic so the wrap is defined:
int32_t start = now(); // ticks are int32_t, 1 kHz
while ((int32_t)((uint32_t)now() - (uint32_t)start) < dt) { /* waiting */ }
The subtraction is allowed to wrap; the cast back to signed makes the difference correct for any elapsed interval shorter than 2^31 ticks.
Why your case returns immediately. With now = 2,147,483,647 (INT32_MAX) and dt = 200:
| step | value |
|---|---|
now + dt in int32 | 2,147,483,847 overflows; in practice wraps to -2,147,483,449 |
test now >= deadline | 2,147,483,647 >= -2,147,483,449 → true |
| result | wait returns at once, 0 ticks elapsed |
(The addition itself is signed overflow: undefined behaviour. The wrap shown is what the hardware does, not what the standard promises.)
The wrap-safe version on the same numbers:
| step | value |
|---|---|
at start: (uint32_t)now() - (uint32_t)start | 0 → 0 < 200, keep waiting |
after 200 ticks: now() returns -2,147,483,449 | (uint32_t) is 2,147,483,847; minus 2,147,483,647 = 200 → 200 < 200 false, return |
It returns after exactly 200 ticks, across the wrap.
The companion rule you also broke: keep dt below half the counter range. The signed-difference idiom is unambiguous only while the true elapsed interval is under 2^31 ticks: 24.8 days at 1 kHz. The unsigned form pushes that to 2^32 ticks (~49.7 days), but the same "less than one wrap" assumption applies. If a timeout can exceed the range, the counter width is the bug, not the comparison.
What breaking it looks like. Hypothetical, but the shape is standard: a 200 ms debounce on a mechanical contact becomes a 0 ms debounce. The bounce, say 20 ms of chatter, passes straight through, the relay coil is driven continuously instead of pulsed, and you get chatter and heat instead of one clean actuation. The bug is invisible in every test that runs away from the wrap point.
How to catch it.
- Unit-test the wait with
startatINT32_MAX - 100,INT32_MAX, andINT32_MAX + 100(as the wrapped value), asserting the elapsed tick count, not just that it returned. - On target, set the tick counter near
INT32_MAXunder a debugger and measure the output pulse width on a scope. A 200 ms pulse that measures 0 ms is the failure. - Grep for
now + dt,deadline, and>comparisons against tick values; the wrap-safe idiom never needs an absolute deadline.
The rule in one line: compare elapsed differences, not absolute deadlines, and keep the timeout under half the tick range.
Curated: · Written: · Reviewed:
Q&A-44configCHECK_FOR_STACK_OVERFLOW is 0. A task returns. Later the idle task HardFaults. What did you skip?
What you skipped
Two things, and they are different bugs:
configCHECK_FOR_STACK_OVERFLOWis 0, so nothing inspects the task's stack at context switch. The overflow is silent.- The task function returned. In FreeRTOS a task must end with
vTaskDelete(NULL); returning is undefined behaviour. The port's task trampoline plants a return address that leads toprvTaskExitError, but that only helps if the frame is still intact.
The return is the trigger. The zero config is why you find out seconds later in the idle task instead of at the instruction that did it.
Why the fault lands in idle
A task's stack is a block carved from the FreeRTOS heap, and the TCBs come from the same heap. So the memory immediately above a task's stack is frequently the next TCB: often the idle task's, since idle is created first.
When the task returns, SP walks past the top of its stack region and the epilogue's pops and the next pushes write into that neighbour. Nothing faults: the write is to valid RAM. The corruption just sits there.
Idle is the lowest-priority task. It runs whenever every other task is blocked, so it is the first thing to touch the corrupted structure: either its own TCB, or a TCB the scheduler reads when it switches to idle. The HardFault is the first use of the smashed data, not the smash.
The victim is not the smasher.
Mode 1 vs mode 2
| Mode 1 | Mode 2 | |
|---|---|---|
| What it checks | current SP against the task's stack limit, at each context switch | last 16 bytes of the stack, filled with 0xa5a5a5a5 at task creation, compared at each context switch |
| Catches | overflow where SP is still past the limit at switch time | any write into the top 16 bytes, even if SP came back |
| Misses | a task that overflowed and returned: SP is back inside the region | overflow that stops below the last 16 bytes |
| Cost | one pointer compare per switch | 16 bytes RAM per task + a 16-byte compare per switch |
Mode 2 is the one that catches this case. Mode 1 would not: by the time the scheduler runs, the returning task's SP is back inside its region.
The hook
With mode 2 set, vApplicationStackOverflowHook runs in the offending task's context. You cannot safely allocate or log much there: copy the task name into a fixed buffer and reset.
When checking is not enough
Runtime checking is a canary: it tells you after the fact, and only if the write lands in the last 16 bytes. If you need the fault at the offending store, use FreeRTOS-MPU: the kernel runs privileged, tasks unprivileged, each task gets its own MPU region, and a write outside it faults immediately. The cost is per-task MPU regions and overhead on every API call that crosses the privilege boundary. Worth it when a delayed fault in another task is unacceptable.
Sizing
uxTaskGetStackHighWaterMark reports the minimum free stack a task ever had. Run it under worst-case load, then add margin. A task that returns is a bug regardless of size; a task that overflows is a sizing bug plus a missing check.
Curated: · Written: · Reviewed:
Q&A-30EXTI0 preempts EXTI1. EXTI0 calls pvPortMalloc. The heap looks fine from a task. Why do you still die?
Core answer
pvPortMalloc is not ISR-safe, and FreeRTOS has no pvPortMallocFromISR. The heap's mutual exclusion is scheduler suspension, not interrupt masking. heap_1, heap_2, heap_4 and heap_5 wrap the free-list walk in vTaskSuspendAll()/xTaskResumeAll(); heap_3 wraps malloc/free the same way. vTaskSuspendAll stops the scheduler from switching tasks: it does not stop an interrupt. EXTI0 outranks EXTI1 and preempts whatever the CPU was doing, including a task halfway through pvPortMalloc, so the ISR re-enters the free-list walk.
That is also why the heap looks fine from a task. xPortGetFreeHeapSize() returns xFreeBytesRemaining, a counter, not a traversal. A task's next pvPortMalloc walks from xStart and normally finds a block before it reaches the corrupted link, so it returns a valid pointer. The damage lives in the free-list pointers and only faults when something later dereferences the bad link: a later malloc/free, or vTaskSwitchContext reading a corrupted ready list. Hence a HardFault hundreds of milliseconds after the ISR, with the LED still blinking.
Worked trace (heap_4, 32-byte ISR alloc)
- Task A calls pvPortMalloc(64). vTaskSuspendAll() → uxSchedulerSuspended = 1. It walks the list and caches pxPreviousBlock = 0x20001800, pxBlock = 0x20001A00. It has not yet written the link.
- EXTI0 fires. Interrupts are not masked by vTaskSuspendAll. The ISR calls pvPortMalloc(32). vTaskSuspendAll() → uxSchedulerSuspended = 2. It walks the same list from xStart, reaches 0x20001A00, splits it, and writes the new linkage.
- ISR returns. xTaskResumeAll() → 2→1, no switch.
- Task A resumes and executes pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock using its stale cached values, overwriting the ISR's linkage. The free list now points into a block that has already been handed out.
- A later malloc returns overlapping memory; a later free or vTaskSwitchContext walks off the end of the list → HardFault.
Second, independent bug: if the ISR's malloc is the outermost call (the task was not in malloc), xTaskResumeAll goes 1→0, calls xTaskIncrementTick and can call vTaskSwitchContext from interrupt context without portYIELD_FROM_ISR.
Alternatives and when each applies
- Defer to a task (default): the ISR does xQueueSendFromISR or xStreamBufferSendFromISR with a small request; a worker task calls pvPortMalloc. Costs one queue copy and a task wakeup. Use unless the ISR must have memory before it returns.
- Pre-allocated pool: size a fixed block pool at init; the ISR takes a block via an atomic index or a short portSET_INTERRUPT_MASK_FROM_ISR section. No allocation in the ISR. Use when the ISR needs memory immediately and the block size is bounded.
- heap_3: wraps malloc/free with vTaskSuspendAll. Same non-ISR-safe property, so it does not fix this.
- heap_1: allocate-only, never frees, but still calls vTaskSuspendAll. Still not ISR-safe.
- Custom ISR allocator: only if you truly need allocation in interrupt context and can bound it; you own the correctness.
Detection
- objdump the ISR vector objects for
bl pvPortMalloc; grep the IRQ sources for malloc/free. - Build with configASSERT on (heap_4 asserts on block and end-pointer sanity) and heap fill patterns; run a preempt soak with EXTI0 at its real rate.
Curated: · Written: · Reviewed:
Q&A-22Both IRQs are priority 5. You expected the 20 kHz loop to preempt the 1 kHz log. Why does grouping stop that?
The 60-second answer. The NVIC splits each priority into a preemption field and a subpriority field, and that split is global: it comes from PRIGROUP in SCB->AIRCR, not from the number you pass per IRQ. Two interrupts with the same preemption value are in the same group, and the NVIC never preempts within a group. Subpriority only decides which of two interrupts pending at the same instant gets taken first; it never lets one interrupt interrupt another. So with grouping set to 0 preemption bits, "priority 5" and "priority 5" are the same group, and the 20 kHz loop waits for the 1 kHz log ISR to return. It is tail-chained, not preempted.
Why the numbers looked different. With 4 implemented priority bits and NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_0) (AIRCR.PRIGROUP = 0b111), the field is 0 preemption bits / 4 subpriority bits. Both IRQs encode to preempt = 0, subpriority = 5. Same group, and even the tie-break is a tie: with identical preemption and subpriority the NVIC falls back to the exception number, so the lower IRQ number wins. That is a coin flip you did not choose.
NVIC_SetPriorityGrouping arg | AIRCR.PRIGROUP | Preempt bits | Subpriority bits |
|---|---|---|---|
NVIC_PRIORITYGROUP_0 (0x7) | 0b111 | 0 | 4 |
NVIC_PRIORITYGROUP_1 (0x6) | 0b110 | 1 | 3 |
NVIC_PRIORITYGROUP_2 (0x5) | 0b101 | 2 | 2 |
NVIC_PRIORITYGROUP_3 (0x4) | 0b100 | 3 | 1 |
NVIC_PRIORITYGROUP_4 (0x3) | 0b011 | 4 | 0 |
(4 implemented bits, STM32F4-class. Read the count back rather than trusting the header: write 0xFF to a byte of NVIC->IP[] and count the leading ones that survive. Cortex-M0/M0+ have no PRIGROUP at all: 2 bits, all preemption.)
The fix.
/* Cortex-M4, 4 implemented priority bits. */
NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); /* 4 preempt bits, 0 subpriority */
NVIC_SetPriority(LOG_IRQn, NVIC_EncodePriority(NVIC_PRIORITYGROUP_4, 6, 0));
NVIC_SetPriority(LOOP_IRQn, NVIC_EncodePriority(NVIC_PRIORITYGROUP_4, 5, 0));
Lower value = higher urgency, so the loop now preempts the log. PRIGROUP is global: changing it re-interprets every priority already programmed, so re-encode all of them, and re-read SCB->AIRCR at runtime. An RTOS port or vendor HAL init can set it after your boot code.
Trace of the failure (representative bench numbers, 4-bit part, 120 MHz):
t=0 log ISR entered (preempt field 0)
t=20,70,120,170 loop IRQ pends (20 kHz = 50 us period); no preemption
t=180 log ISR returns; tail-chains into loop ISR (no unstack/restack)
t=180..192 loop ISR runs
The loop's first pending edge starts up to 180 µs late, one full log ISR, and four pending edges collapse into one service. Control error roughly doubled on the bench.
Alternatives, and when more preemption is the wrong answer.
- Split the group field (above). Cost: you lose subpriority tie-breaks, every distinct value becomes a preemption level, and nesting grows the stack. Each preemption pushes 8 registers, plus 17 more words if the FPU is lazily stacked. Only do this if the loop genuinely must run inside the log ISR's window.
- Shorten the log ISR. If the 180 µs is formatting and a UART write, push a timestamped record into a ring buffer and return in a few µs; a low-priority task drains it. Grouping then stops mattering. Cost: buffer sizing and an explicit drop policy.
- Take the CPU out of it. DMA the log ring buffer to the UART, or use ITM/DWT trace. Cost: hardware support and trace bandwidth limits.
Heavy preemption grouping is the wrong choice when the "high-rate" ISR is not actually latency-critical, if the 20 kHz loop only samples and the control law runs in a task, giving it preemption rights over everything buys nothing and adds reentrancy risk on any shared state. It is also constrained on parts with 2 implemented priority bits, where you have four preemption levels total.
Detection. Toggle a GPIO at the top of each ISR and capture both on a logic analyzer; require the loop's edge to appear inside the log ISR's high time. A debugger halt in the log ISR proves nothing: halt freezes the timeline for both, so the loop looks like it still ran.
Curated: · Written: · Reviewed:
Q&A-29USART1 stays pending while its handler prints. USART2 at a lower group never runs. What Cortex-M rule did you miss?
The rule: a Cortex-M exception cannot preempt itself.
When USART1's handler is active and RXNE asserts again, the NVIC sets the pending bit for that exception number, but the processor will not re-enter the handler on top of itself. On return it tail-chains, 6 cycles on Cortex-M3/M4 against 12 for a full exception entry, straight back into the same handler, reusing the stack frame already sitting on MSP. The CPU never returns to thread mode, so nothing of lower preemption priority, USART2 included, gets a slot.
The second half of the rule is priority grouping. Only the preemption (group) priority bits in NVIC_IPR decide nesting; the subpriority bits only break ties between exceptions that are both pending and neither active. USART2 sitting at a lower group priority cannot preempt USART1 however long USART1 runs. Subpriority is not a lever here.
What that looks like at 115200 8N1
| Item | Value |
|---|---|
| bit time | 8.68 µs |
| byte time (10 bits: start + 8 data + stop) | 86.8 µs |
| printf inside the USART1 ISR | 400 µs |
| bytes arriving during one handler run | ~4.6 |
| tail-chains per handler run | 4–5 |
| MSP growth per tail-chain | 0: the frame is reused |
| USART2 entries while USART1 stays pending | 0 |
Run the numbers and the ISR is exactly saturated: 4.6 bytes drained per 400 µs is 11.5 kB/s, which is line rate. The handler consumes 100% of the CPU and still keeps up, so USART2 never sees an idle slot. If you had sized MSP for 22 nested frames of 96 bytes (2,112 bytes) on the assumption that the same IRQ nests, you sized for something the architecture forbids: depth stays 1.
The fix, in order of preference
- Clear the source before doing anything long. On STM32, read SR then DR: that clears RXNE and ORE together. A flag left set through a 400 µs printf is what re-pends the exception.
- Get the work out of the ISR. Push the byte into a ring buffer and let the main loop or a DMA-driven path do the formatting.
void USART1_IRQHandler(void) {
(void)USART1->SR; /* read SR ... */
uint8_t b = USART1->DR; /* ... then DR clears RXNE and ORE */
ring_push(&rx, b); /* bounded; no printf here */
}
- If USART2 genuinely must preempt USART1, raise its preemption priority above USART1's in
NVIC_IPRand setSCB->AIRCR.PRIGROUPso enough bits are preemption bits. That is the only mechanism that grants nesting.
Confirming it
Toggle a GPIO on ISR entry and exit and count depth on a scope, or keep a counter and assert it never exceeds 1 for USART1. Then flood USART1 for one second at 115200 and count USART2 entries; with the flag cleared first, USART2 should get in. If depth is still climbing, the peripheral flag is being re-asserted after the NVIC pending bit was cleared: clear the source as the first instruction, and drop any stale pending bit with NVIC_ICPR if a race left one set.
The same rule bites SysTick against a peripheral, and any two handlers that share an exception number. Self-preemption is not a priority problem you can tune away; it is not available at all.
Curated: · Written: · Reviewed:
Q&A-24On STM32F407, TIM1_BRK_TIM9 is one vector. You clear TIM1 break and return. TIM9 still reenters. Why?
The trade-off in shared IRQ line for TIM1_BRK and TIM9 is which failure I am willing to ship, and I will not ship an unmeasured one.
I treat a shared vector as a list of sources. Clearing the one I stepped in the debugger leaves the other pending, which looks like a "spurious" storm. EXTI9_5 is a different STM32F407 vector; it is not TIM1_BRK.
Concretely, i read every status bit that can raise TIM1_BRK_TIM9, clear only those I handle, and I have a default path that logs an unexpected source instead of returning.
The reason for that specificity is a failure I have seen: I cleared TIM1_SR BIF. TIM9 UIF stayed set. Vector reentered at the 20 kHz TIM9 rate. CPU 100 percent. UART printf still flushed one line so the console looked alive. Current 28 mA versus 6 mA in the idle budget.
STM32F407 TIM1_BRK_TIM9 shared vector.
| Source | Rate | Cleared |
|---|---|---|
| TIM1_BRK | 100 Hz | yes |
| TIM9 update | 20 kHz | no |
| CPU | 100% | 28 mA vs 6 mA |
I would not consider it settled without evidence: I would dump TIM1 SR and TIM9 SR at ISR entry for 1,000 entries and require a named source each time, plus a GPIO count matching the expected break rate not the TIM9 rate.
One vector is not one peripheral.
Curated: · Written: · Reviewed:
Q&A-23Two IRQs tail-chain. The second always meets its "entry" timestamp. Who is late?
Short answer: the second handler is late. At completion, not at entry. Its entry timestamp is taken after the first handler has already finished, because that is exactly what tail-chaining skips. The first handler is the one that overran its budget; the second inherits the delay.
Assumptions that decide it: single core, fixed priorities, the second IRQ is already pending when the first handler ends, and the deadline is defined from the hardware event that raised the second IRQ, not from the first instruction of its ISR.
Why the entry timestamp cannot see it. Tail-chaining is a return-path optimisation. When an exception is pending as the current handler finishes, the core skips the unstack of the current context and the stack of the next, and vectors straight in. On Cortex-M3/M4 that costs 6 cycles, against 12 (return) + 12 (entry) = 24 for a full round trip (ARM's TRM for those cores; figures assume zero-wait-state memory and no FPU context stacking). So the second handler's first instruction, where entry timestamps are usually taken, executes after the first handler has run to completion. The timestamp answers "when did the second handler start", not "when was its event due".
Trace. Cortex-M4 at 168 MHz, control loop period 50 µs. IRQ A (ADC end-of-conversion, higher priority) has a 20 µs budget; IRQ B (PWM update, lower priority) has a 10 µs budget and a hard deadline of 50 µs from the timer event. Both are raised by the same timer event at t = 0.
| t (µs) | Event |
|---|---|
| 0 | timer event; A and B both pending; A enters |
| 45 | A's last instruction (budget was 20 µs: overran by 25 µs) |
| 45.036 | tail-chain: 6 cycles at 168 MHz = 35.7 ns; B's first instruction |
| 55.036 | B completes (10 µs of work, exactly on budget) |
B's entry timestamp reads 45.036 µs, comfortably inside the 50 µs deadline, so an entry-based check passes. B completes at 55.036 µs: 5.036 µs late. B did nothing wrong; A's overrun pushed it past the deadline. That is the whole failure: the check certifies the handler that is late.
What to measure instead. Latch the trigger instant in hardware and compare completion against it.
/* Cortex-M4 @168 MHz. TIM2: 1 MHz free-running counter, 1 tick = 1 us.
TIM2 CH1 input capture is wired to the same event that raises IRQ B. */
#define B_DEADLINE_US 50u
#define A_BUDGET_US 20u
void B_IRQHandler(void) {
uint32_t trig = TIM2->CCR1; /* latched by hardware at the event */
uint32_t entry = TIM2->CNT; /* first instruction of B */
/* ... work ... */
uint32_t done = TIM2->CNT;
uint32_t start_delay = entry - trig; /* time A held B off */
uint32_t total = done - trig; /* what the deadline is measured against */
if (total > B_DEADLINE_US) { /* B is late */ }
if (start_delay > A_BUDGET_US) { /* A overran and ate B's margin */ }
}
Unsigned subtraction handles the 32-bit counter wrap.
Failure modes, and when entry is the right point.
- Timestamp taken in the ISR body: blind to the first handler's overrun by construction.
- Timestamp taken at pending assertion but compared against a deadline defined from entry: off by the tail-chain gap. Small, but not zero.
- If B has higher priority than A, B preempts and there is no tail-chain at all; the entry check never fires, and the same overrun surfaces as A being late instead.
- If the deadline genuinely is defined from ISR entry (a software-triggered handler, say), entry is the correct point and this check is the wrong one.
Budget the sum of chained handlers against the period, not each entry in isolation.
Curated: · Written: · Reviewed:
Q&A-28A 1.2 µs encoder index pulse arrives while you are in a 6 µs GPIO ISR on the same EXTI. You never see the index. Why?
The pending bit is one bit, not a queue. EXTI latches an edge into a single pending bit per line. Your index edge arrives while that line's PR is already set from the edge that started the ISR. Setting an already-set bit is a no-op, so no second event is recorded. When the ISR clears PR on the way out, it clears the index edge with it. The pulse was detected; the record of it was overwritten.
Assumptions: STM32-class EXTI, PR cleared at the end of the ISR, index sharing an EXTI line with the encoder or another GPIO. If PR is cleared at the start of the ISR instead, a new edge during the ISR re-sets PR and the NVIC re-enters on exit: that variant does not lose the edge, which is why the clear-at-end pattern is the one to suspect.
Mechanism: the edge detector is a latch clocked by the peripheral bus. A 1.2 µs pulse is many bus cycles wide, so it is sampled and does set the latch. The loss is not detection, it is storage: one bit cannot hold two events.
Two fixes:
- Clear PR at the start of the ISR, then re-read the pin (or re-check PR) before returning and loop until idle. Cheap, but still software-timed: a pulse that arrives and is cleared inside the same window can still be lost.
- Move the index to a timer input-capture channel. The capture register latches the counter on the hardware edge, independent of software clearing PR. This is the robust answer for an index that must not be missed.
Failure mode I've seen: index pulse 1.2 µs, GPIO ISR 6 µs, encoder 4096 CPR at 3000 rpm = 204,800 counts/s, 4.88 µs apart. Index coincided with a GPIO ISR. Missed. Commutation offset wrong by one mechanical turn. Phase current 1.8 A RMS versus 0.4 A.
| Item | Value |
|---|---|
| index width | 1.2 µs |
| GPIO ISR | 6 µs |
| 4096 CPR at 3000 rpm | 204,800 Hz, 4.88 µs |
| missed index | 1 mechanical turn |
| RMS current | 1.8 A vs 0.4 A |
Verification: inject a 1.2 µs pulse during a forced 6 µs ISR on a signal generator and require the capture counter to increment, not an EXTI count. If the capture counter moves, the hardware path is sound; if only the EXTI count moves, you are still relying on the one-bit latch.
Curated: · Written: · Reviewed:
Q&A-27You CPSID I around a 2 µs SRAM copy. A 20 kHz PWM ISR is 12 µs late. What should you have raised instead?
Raise BASEPRI to the UART copy's priority, not PRIMASK.
CPSID I writes PRIMASK, which masks every configurable-priority exception on the core: the 20 kHz PWM ISR included. BASEPRI masks only exceptions whose priority number is greater than or equal to the value you write. On Cortex-M a numerically lower priority number is more urgent, so if the PWM ISR sits above the UART copy, writing BASEPRI to the UART's level leaves the PWM free to preempt.
#define UART_PRIO 0x40u /* NVIC priority field value for the UART copy */
uint32_t saved = __get_BASEPRI();
__set_BASEPRI(UART_PRIO); /* UART and below masked; PWM (0x20) still preempts */
memcpy(dst, src, 64); /* 2 us of SRAM, no flash access inside */
__set_BASEPRI(saved); /* restore; writing 0 would disable masking entirely */
Two conditions have to hold. The PWM ISR must have a strictly lower priority number than the UART copy, if they share a level, BASEPRI cannot separate them and you have to re-prioritize the PWM ISR first. And the critical section must stay short; BASEPRI buys preemption, not time.
The second condition is where the original went wrong. Hypothetical bench numbers: 2 µs at 80 MHz is 160 cycles, which is fine. A flash access pulled inside the same lock cost 40 µs. The PWM period is 50 µs, so the ISR was held past the compare reload, one compare event was missed, and the output held its last state, duty 0 on that bench, for a full period. Phase current 3.1 A. The debugger made it look healthy because a halt freezes TIM, so the timer never advanced while you were stopped.
Failure modes worth checking:
- BASEPRI written too high (numerically) masks the PWM too: same bug, different register.
- BASEPRI never restored leaves every lower-priority interrupt masked for the rest of the run.
- A shared flag or buffer between the copy and the PWM ISR reintroduces the race BASEPRI was meant to remove; a single-word store or a double buffer avoids masking altogether.
Verify with a GPIO toggled around the critical section, scoped against the PWM gate drive, and confirm the PWM ISR still enters while BASEPRI is set. A DWT cycle counter around the section bounds it without a scope.
Curated: · Written: · Reviewed:
Q&A-46The ISR queues a sample and returns. The consumer task wakes 1 ms later. What flag did you not set?
The flag is pxHigherPriorityTaskWoken: in FreeRTOS, xHigherPriorityTaskWoken, a BaseType_t you initialise to pdFALSE and pass to xQueueSendFromISR. The send sets it to pdTRUE when the unblocked consumer's priority is higher than the task the ISR interrupted. You then hand it to portYIELD_FROM_ISR. Pass NULL, or ignore the value, and the item still lands in the queue and the consumer still moves to the ready list, but no context switch happens on ISR exit. The switch waits for the next tick, which at configTICK_RATE_HZ = 1000 is up to 1 ms plus the remainder of the current tick.
The flag and the yield are two halves of one thing: the send sets the flag, portYIELD_FROM_ISR pends PendSV on Cortex-M and performs the switch. Setting the flag without yielding does nothing.
/* FreeRTOS 10.5.x, Cortex-M4, configTICK_RATE_HZ = 1000 */
static QueueHandle_t adc_q;
void ADC_IRQHandler(void)
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
uint16_t sample = ADC1->DR;
if (xQueueSendFromISR(adc_q, &sample, &xHigherPriorityTaskWoken) != pdPASS) {
g_adc_dropped++; /* errQUEUE_FULL — sample lost, count it */
}
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
Trace it. ADC at 20 kHz → one sample every 50 µs. Consumer priority 3, drains the queue in a loop each time it runs, so it removes at most 8 per wake (queue depth 8). Without the yield the consumer runs once per tick:
- per ms: 20 samples arrive, 8 drained, 12 dropped → 60% loss
- with the yield: consumer wakes ~2-5 µs after each ISR (PendSV latency at 80 MHz), drains each sample as it lands, 0 dropped
The loss is invisible unless you count errQUEUE_FULL; the send path in the ISR still returns and the LED still toggles.
Trade-offs: the yield is necessary but not the only lever:
| Option | Effect on wake latency | Buffering | When it applies |
|---|---|---|---|
| Queue + yield | ISR→task ~2-5 µs | depth × item size | default; multiple samples in flight |
Direct task notification (xTaskNotifyFromISR) | same, fewer cycles: FreeRTOS's task-notification docs cite up to 45% faster unblocking than an intermediary object such as a semaphore | one value, one waiter | consumer only needs "data ready"; payload lives in a shared buffer |
| Deeper queue | none: still a tick without the yield | more | burst absorption, not latency |
| Higher consumer priority | none | none | only changes whether the flag gets set; if the consumer is lower priority than the interrupted task the flag stays pdFALSE and the task correctly waits |
Failure modes to name: silent overflow (queue full, return value ignored). Detect with a dropped-sample counter read over SWO or a debug task; tick-quantised latency. Detect by scoping ISR GPIO to task GPIO and requiring ≤ 15 µs at 80 MHz, not 1 ms; and the false fix of a deeper queue, which hides the missing yield until the burst exceeds the new depth.
Curated: · Written: · Reviewed:
Q&A-10A naked 10 kHz ISR uses the FPU. After it returns, a task's S16 value is garbage. What did the naked ISR not save?
The naked ISR didn't save S16–S31.
On Cortex-M4F/M7, exception entry with the FPU active stacks only the caller-saved FP registers: S0–S15, FPSCR, and one reserved word for the lazy-stacking state. S16–S31 are callee-saved under AAPCS, so the compiler that built the task can keep a live value in S16 across the ISR: it assumes any callee preserves them. A naked ISR has no compiler-generated prologue, so nothing pushes S16–S31, and the ISR's own use of S16 overwrites the task's value.
Lazy stacking doesn't change this. LSPEN (FPCCR bit 30) only defers the S0–S15/FPSCR push until the handler executes an FP instruction; it never covers S16–S31. The bug isn't "lazy stacking is off": it's that the naked ISR skipped the callee-saved half of the FP context.
| Register | AAPCS class | Hardware saves on exception entry | Naked ISR saves |
|---|---|---|---|
| S0–S15 | caller-saved | yes (lazy or eager) | n/a |
| FPSCR | — | yes | n/a |
| S16–S31 | callee-saved | no | no → task value corrupted |
The fix is to own the callee-saved half explicitly:
__attribute__((naked)) void TIM2_IRQHandler(void) {
__asm volatile (
"vstmdb sp!, {s16-s31} \n" // hardware never does this
// ... ISR body, may use S16 ...
"vldmia sp!, {s16-s31} \n"
"bx lr \n"
);
}
vstmdb sp!, {s16-s31} costs 64 bytes of stack and about 1 + N cycles per instruction on an M4: roughly 34 cycles per ISR for the pair. At 10 kHz on a 100 MHz core that's ~0.34% CPU. The alternatives are to drop naked and let the compiler emit the save, or keep the ISR integer-only: in which case lazy stacking means the FP context isn't pushed at all and the ISR stays cheap.
Detection: dump S16–S31 at ISR entry and exit and require them unchanged across a few thousand firings. The symptom is a task float that was 1.00f returning as a denormal or garbage, because the task's filter state lived in S16.
Curated: · Written: · Reviewed:
Q&A-4The USART ISR writes SR = 0 to "clear everything." Overrun never comes back. What did that write do?
On STM32F4 (RM0090), USART_SR is not write-1-to-clear. Its latched bits are rc_w0, writing 0 clears them, and the documented clear sequences are read-based. So SR = 0 did two things, and only one was intended:
- It cleared the latched error flags, ORE included. That is why overrun "never comes back": the flag is wiped on every ISR entry, before any code can read it.
- It did not drain the receiver. RXNE is a level, not a latch: it tracks "RDR not empty." The write never touches
USART_DR, so RDR stays full and RXNE stays asserted.
The result is a re-entry loop. The handler returns with RXNE still 1, the NVIC re-enters immediately (not once per byte, but back-to-back) and each pass re-clears ORE. CPU is pinned in the ISR, the main loop stops, and the overrun condition never goes away but you never see it.
The buggy handler
void USART1_IRQHandler(void) {
USART1->SR = 0; /* "clear everything" */
/* application work; DR is never read */
}
What it should be
void USART1_IRQHandler(void) {
uint32_t sr = USART1->SR; /* snapshot first */
if (sr & USART_SR_RXNE) {
uint8_t b = USART1->DR; /* read DR clears RXNE, and ORE/NE/FE/PE */
ring_push(&rx, b);
}
if (sr & USART_SR_ORE) {
overrun_count++; /* observe before the DR read wipes it */
}
}
The snapshot matters: on F4 the sequence "read SR, then read DR" clears RXNE and the error flags together, so reading DR first loses the ORE you wanted to count.
Clear sequences on STM32F4
| Sequence | RXNE | ORE | Result |
|---|---|---|---|
SR = 0 | still asserted | cleared | ISR re-enters; overrun invisible |
SR = 0xFFFFFFFF | still asserted | still set | no-op: writing 1 to rc_w0 bits changes nothing |
| read SR, then read DR | 0 | 0 | one entry per byte |
The 0xFFFFFFFF row is the next trap: on an rc_w0 register, writing 1s is a no-op, so it fixes nothing and hides nothing.
Where the W1C habit comes from. On STM32F0/F3/F7/L4/H7 the flags moved to a separate USART_ICR register, which is write-1-to-clear (USART_ICR_ORECF, USART_ICR_TCCF, USART_ICR_IDLECF). RXNE is still cleared by reading DR there. So "write 1 to clear" is right on ICR and wrong on F4's SR: check the register, not the habit.
How I'd confirm it. GPIO-toggle a pin at ISR entry and count edges over 1 ms of idle line: correct code gives 0 edges after the last byte drains, the SR = 0 version gives a continuous square wave. Then single-step: after SR = 0, RXNE in the debugger is still 1; after the DR read it drops to 0.
Curated: · Written: · Reviewed:
Q&A-21USART ISR runs 140 µs. Bytes arrive every 86.8 µs at 115,200. What do you measure before you "optimize later"?
Before I optimize anything, I measure two numbers: how long the ISR actually holds the CPU, and whether bytes are being lost. The 140 µs is a claim until I've scoped it.
The budget. At 115,200 8N1 a byte takes 86.8 µs to arrive. A handler that runs 140 µs is longer than the gap between bytes, so the next byte finishes shifting in while I'm still inside the handler. If the handler hasn't read the data register by then, the overrun flag sets and that byte is gone. So 140 µs isn't the problem by itself: 140 µs against 86.8 µs is.
I hold the handler to 50% of byte time, 43 µs, so a higher-priority interrupt can preempt it and it still drains the data register before the next byte lands. That's a rule of thumb, not a spec; the real ceiling is whatever leaves margin for the rest of the system.
| Item | Value |
|---|---|
| bit time | 8.68 µs |
| byte, 8N1 | 86.8 µs |
| ISR high time | 140 µs |
| cycles at 72 MHz | 10,080 |
| goodput | 5,760 B/s of 11,520 |
How I measure it. Toggle a GPIO on ISR entry and exit, scope the high time on the same timebase as the RX line. Two things to get right: measure with interrupts at their real priorities and the debugger detached. A halted core or a breakpoint in the handler gives you a number that means nothing. And toggle at the actual entry and exit, not at the end of the happy path; if the handler has early returns, an LED at the bottom measures the wrong window.
The failure I've seen. A handler that CRC'd 64 bytes took 140 µs at 72 MHz: 10,080 cycles. Overrun set every other byte, so goodput fell to 5,760 B/s from 11,520. The printf of the last good line looked perfectly fine; the terminal doesn't tell you bytes are missing. That's why I count received bytes against sent bytes over a fixed window rather than trusting the output.
What I'd change. The ISR moves bytes into a ring buffer and returns; the CRC runs in a task. Then re-scope: the handler should be a few microseconds, and the overrun flag should stay clear under full-rate traffic.
Failure modes to watch. Overrun (ORE) is the one that bites here, but check framing (FE) and noise (NE) too: a bad baud divisor or a floating RX pin shows up as FE/NE, not ORE, and moving work to a task won't fix it. On the STM32-style USARTs I've used, ORE is cleared by reading SR then DR; if you only read DR, the flag stays set and you can't tell whether you're still dropping. And a handler that's fast but blocks on a mutex or a full ring buffer is just as bad as a slow one: measure the worst case, not the average.
Curated: · Written: · Reviewed:
Q&A-9The errata says USART RX overrun on rev Y when BRR is odd. You apply it on rev X. What did you just break?
The 60-second answer
You broke the baud rate. A BRR-odd overrun errata is fixed by forcing the baud-rate divider to an even value: you round BRR so its low bit is 0. On rev Y that removes the overrun. On rev X, where the overrun doesn't exist, the only thing the workaround still does is change BRR, so you've traded a bug you didn't have for a baud-rate error you now do. Whether that error matters depends entirely on USARTDIV: at low baud it's a fraction of a percent and you'll never notice; at high baud it can exceed the UART's tolerance and you get framing errors instead of overruns.
Assumption I'd state up front: I don't know rev X's BRR behavior, and I don't know what the workaround actually writes. If it's gated on the revision, nothing breaks. If it unconditionally rewrites BRR, the analysis below applies.
Why the size of the breakage is USARTDIV, not the baud number
BRR encodes USARTDIV = fCK/(16 × baud) with four fractional bits, so one LSB of BRR is 1/16 of USARTDIV. Forcing the value even moves it by at most one LSB, and the relative baud error that causes is (1/16)/USARTDIV. USARTDIV shrinks as baud rises, so the same "round to even" costs more at the top of the range.
Hypothetical, fCK = 16 MHz, oversampling by 16:
| baud | USARTDIV | BRR (round) | forced even | actual baud | error |
|---|---|---|---|---|---|
| 115200 | 8.6806 | 139 | 138 | 115942 | +0.64% |
| 921600 | 1.0851 | 17 | 16 | 1000000 | +8.5% |
At 115200 the 0.64% sits inside the ~2% budget a 10-bit frame tolerates and the link works. At 921600 the 8.5% is far outside it: the receiver samples the stop bit in the wrong place, sets the framing-error flag, and drops or corrupts frames. You didn't get an overrun: you got a dead link, which is worse because it looks like a wiring problem.
What actually breaks, and how you'd see it
- Baud accuracy: the concrete breakage. Detect by reading the status register's framing-error (FE) and noise-error (NE) flags, or by scoping the line and measuring the bit period against nominal.
- Nothing, if the workaround is a no-op on rev X. The only workaround genuinely safe to port is one that checks the revision first, or one that only rewrites BRR when the value is already odd and the rewrite is exact. An unconditional rewrite is not a no-op: rev X hits it whenever BRR happens to be odd.
- Your own confidence: you changed a working configuration with no failing test on that die, so you can't tell whether you broke anything. That's the real defect.
When to port it
Port only if the workaround is gated on the affected revision, or you can show it's a no-op on the unaffected one. Otherwise you're trading a known bug for an unknown one. The test is the same RX run on rev X with and without the workaround: if the with-workaround run shows baud error or FE/NE, don't port it. Errata are per die, and the workaround's side effect is part of the errata.
Curated: · Written: · Reviewed:
Q&A-26The current-loop ISR uses VLDR. CPACR left CP10/CP11 disabled. The hard-fault CFSR says NOCP. What mismatched?
The mismatch is between the instruction the ISR executes and the coprocessor enable state, not between two source files.
VLDR is an FPU instruction. It only executes when CP10/CP11 are enabled in CPACR. At reset CPACR is 0x00000000, so the FPU is off and the core takes a No Coprocessor fault: CFSR bit 19 (UFSR.NOCP), i.e. CFSR == 0x00080000 when nothing else is set. The ISR object was built with an FP ABI (-mfloat-abi=hard, or softfp, or hand-written asm) while startup never enabled the FPU. A translation unit compiled -mfloat-abi=soft cannot emit VLDR: the compiler has no FP registers to name. So the object that faulted is not the soft-float one.
Confirm it in this order:
- Read the stacked PC out of the exception frame (whichever of MSP/PSP was active) and disassemble at that address.
VLDR,VSTR,VMOV,VADD: the fault is exactly this. - Read
CPACRat0xE000ED88. Bits 20-21 are CP10, bits 22-23 are CP11.0x00F00000means both enabled;0x00000000means never enabled. readelf -Aon the offending object showsTag_ABI_VFP_args: VFP registers. The linker warns when a VFP-register-args object is linked against base-args objects.
| Observation | What it establishes |
|---|---|
CFSR == 0x00080000 | NOCP: FP instruction with CP10/CP11 off |
CPACR == 0x00000000 | FPU never enabled |
stacked PC disassembles to VLDR | the faulting instruction is FP |
readelf -A shows VFP registers | object built with an FP ABI |
The fix is ordering, not just a register write:
SCB->CPACR |= (0xFUL << 20); /* CP10 and CP11 full access */
__DSB();
__ISB();
The DSB/ISB are load-bearing: without them the enable may not be visible to the pipeline before the next FP instruction. And the enable has to happen before the timer that drives the ISR is started. Enabling the FPU after the timer is running leaves a window where the first ISR fires into a disabled FPU.
Failure modes worth knowing:
- If
SHCSR.USGFAULTENAis clear, NOCP escalates to HardFault. That is why the report shows a HardFault with a NOCPCFSRrather than a UsageFault. - The fault is taken at the
VLDR, so integer work earlier in the ISR has already run. If the ISR toggles a GPIO before the FP load, the pin still moves and the board looks alive while the control loop never completes. That symptom is what hides this class of bug. - Enabling the FPU is not free. With FP context active, exception entry reserves 18 words (72 bytes) of stack for lazy stacking of S0-S15, FPSCR and one alignment word. Lazy stacking means the space is reserved but only written if the handler actually touches FP state, so a small stack with nested interrupts can overflow on the reservation alone.
The mismatch is ABI versus enable state. Enable CP10/CP11 at reset with DSB/ISB before any ISR source can fire, and keep one FP ABI across the image.
Curated: · Written: · Reviewed:
Q&A-17A library throws std::bad_alloc. The image was built -fno-exceptions. What runs?
What runs
__cxa_throw, then the unwinder, then std::terminate. -fno-exceptions only affects code you compile: a prebuilt library compiled with exceptions still contains a call to __cxa_throw, and that call is just a symbol resolved at link time.
The sequence:
- The library's
operator new(or its allocation wrapper) fails and executesthrow std::bad_alloc(). - That compiles to
__cxa_throw(&exc, &typeinfo, &dtor). __cxa_throwcalls_Unwind_RaiseException, which walks the stack frame by frame.- Each frame is checked for a landing pad in its
.gcc_except_table(LSDA). Your frames, compiled-fno-exceptions, have no LSDA. The unwinder treats them as "no handler here" and keeps going. - If the library catches
bad_allocinside its own frame, the unwinder finds that landing pad and the catch runs: you never see anything. A library that catches its own allocation failure is fine. - If the exception propagates out of the library, the unwinder reaches the top of the stack,
_Unwind_RaiseExceptionreturns_URC_END_OF_STACK, and__cxa_throwcallsstd::terminate. std::terminatecalls the installed terminate handler; the default callsabort(). On bare metalabort()is whatever your runtime defines: newlib'sraise(SIGABRT)stub, aBKPT, or an infinite loop.
What decides it: link time or run time
Two outcomes, and you can tell which one you have before you flash:
| Check | Result | Meaning |
|---|---|---|
nm -u image.elf | grep __cxa_throw | undefined | link would have failed; you never got here |
nm image.elf | grep __cxa_throw | defined | the throw is in the image; terminate is reachable |
nm image.elf | grep _Unwind_RaiseException | defined | unwinder linked in |
If the library is a static archive and the object containing the throw is pulled in, you get an undefined reference to __cxa_throw at link time: that is the good failure, because it stops the build. If the symbol is present (shared library, or libstdc++ linked with exceptions), you link and get terminate at runtime.
Alternatives, and when to pick each
- Static allocation / fixed pool. No throw path at all. Pick when the worst-case footprint is known and the product can't tolerate a reset.
- Error-code API. Rewrite the library's allocation entry point to return a status. Pick when you control the library source.
- Rebuild the library
-fno-exceptions. Removes the throw entirely. Pick when you have the source and the build. - Custom terminate handler.
std::set_terminateto log and reset. Pick when you can't change the library but can change the runtime; it turns a silent spin into a diagnosable reset. - Stub
__cxa_throw. Define your own that logs and resets. Same trade-off as above, but it also catches throws from any other prebuilt object.
Failure modes
- Silent spin at full clock: no log, no reset, watchdog may or may not fire.
- Destructors in your frames never run: moot once terminate fires, but it means no cleanup ordering to rely on.
noexcepton your own functions is a promise the compiler may use to delete code paths; a throw crossing it is terminate even if you later add exceptions.
Artefacts
Trace of the unwind for a 256-byte request on a 96 KB heap with 80 KB used:
operator new(256) -> malloc fails -> throw bad_alloc
__cxa_throw
_Unwind_RaiseException
frame: lib_alloc.cpp LSDA present -> no handler for bad_alloc -> continue
frame: app_task.cpp no LSDA (-fno-exceptions) -> continue
frame: main.cpp no LSDA -> continue
_URC_END_OF_STACK
std::terminate
abort() -> BKPT / spin
Check before flashing:
arm-none-eabi-nm -C image.elf | grep -E '__cxa_throw|_Unwind_RaiseException|std::terminate'
If __cxa_throw is defined and std::terminate is reachable, the field failure is a reset loop, not a caught error.
Curated: · Written: · Reviewed:
Q&A-92Rev Y DMA FIFO drops the last beat. You workaround on the app core. The bootloader still uses DMA. Who still drops?
Short answer
The bootloader still drops the last beat. The errata lives in the rev Y DMA FIFO, so the workaround lives in each DMA client, not in the chip. You fixed one client: the app. The bootloader is a separate image with its own transfer setup, its own build, and usually its own owning team, and it runs before the app exists on the part. Same silicon, same rev, same tail loss: the last 4-byte beat of the bootloader's DMA transfer never lands in memory.
The pushback I would expect: so patch everything? Not reflexively. The drop only matters where the truncated transfer is trusted. If the bootloader DMA-writes an image it then CRC-checks, and the part has an A/B slot plus a ROM fallback, a dropped beat turns an update into a rollback rather than a brick. If the bootloader executes or commits bytes it never verified, the dropped beat is silent corruption that still boots: worse than the brick. Fix it there, always.
Why the app workaround does not travel
A FIFO flush sits in the transfer setup of whoever programs the DMA: source, destination, length, FIFO threshold, and the drain at the end. The app's HAL does that for the app's transfers. The bootloader has its own copy loop, often a stripped-down HAL because boot flash is tight, and it does not call the app's.
Two paths, one part:
| Path | Flush on rev Y | Last 4-byte beat |
|---|---|---|
| App DMA | present | lands |
| Bootloader DMA | missing | dropped |
What that costs on an image:
| Quantity | Value |
|---|---|
| Image size | 384 KB = 393,216 bytes = 96 pages of 4,096 bytes |
| Bytes lost | final 4 bytes of page 96 |
| Verification | 1 of 96 pages fails CRC, so the whole-image CRC fails |
The loss is deterministic on that path, not a race: run it again and you lose the same 4 bytes. That is why one passing bench run proves nothing about the boot path.
Options and their costs
| Option | Cost | When it is the right one |
|---|---|---|
| Port the flush into the bootloader image | rebuild and re-verify the bootloader; a handful of instructions at the end of each transfer | default: the bootloader is still under change control |
| DMA the bulk, CPU-read the tail | the tail read is polled, so boot time grows by that read only; the bulk stays at DMA speed | boot flash is tight or the bootloader must stay frozen |
| Polled (PIO) copy for the whole boot transfer | boot time scales with image size and you give up overlap | very small boot images, or a factory programming path |
| Leave it, rely on CRC and A/B rollback | no boot change; a dropped beat becomes a failed update and a rollback | only if the boot path never executes unverified bytes and the part always has a fallback slot to boot |
Gate the flush on the IDCODE read so non-affected revs do not pay for it. That read is one register access and a compare; next to moving 384 KB it is noise in the boot budget, so do not optimize it away at the price of running the wrong path on rev Y.
Failure modes and how they show up
- CRC fails on exactly the last page of the image, only on rev Y, every time. Log the failing page index and the received versus expected CRC; last-page-only failures point straight at the tail beat.
- A bootloader that XIPs or commits unverified data fails quietly: the last 4 bytes of the region hold stale or zero data, and the part boots into misbehavior instead of refusing to boot.
- A bootloader build that lost the fix (regenerated tree, stripped HAL) looks identical to a part where the errata does not apply. Check the flush symbol is in the bootloader's map file before trusting a passing run.
Evidence before calling it fixed
The blank-part case is the one that bites: no valid image in either slot, no fallback, and the dropped beat fails the factory flash. So load the 384 KB image through the bootloader DMA path on a rev Y part and require CRC pass 50 of 50, then repeat the same run on a non-affected rev to show the IDCODE gate did not break the good path.
Curated: · Written: · Reviewed:
Q&A-98CPU fills a 512-byte TX buffer. DMA reads 512 zeros. You invalidated after. What did you need before?
You needed a D-cache clean of the TX buffer before DMA start, plus a DSB. Invalidate after is the RX-side operation; on a TX buffer it does nothing useful and can discard dirty lines.
On a write-back D-cache core like Cortex-M7, CPU stores land in D-cache and leave SRAM stale. DMA is a bus master and does not snoop the D-cache. So after the CPU fills 512 bytes, SRAM still holds the old contents: in your case 512 zeros. DMA reads SRAM, so the wire gets zeros. SCB_InvalidateDCache_by_Addr after the transfer only invalidates those cache lines; the DMA already read stale memory. If the lines were dirty, invalidate can also drop the CPU's data without writing it back.
The fix before starting DMA:
#include "core_cm7.h"
#define TX_LEN 512
__attribute__((aligned(32))) static uint8_t tx_buf[TX_LEN];
void spi_dma_tx(void) {
fill_tx_buffer(tx_buf, TX_LEN); // CPU writes
SCB_CleanDCache_by_Addr((uint32_t *)tx_buf, TX_LEN);
__DSB(); // clean must complete before DMA
spi_start_dma_tx(tx_buf, TX_LEN); // DMA reads SRAM
}
512 bytes is 16 cache lines at 32 bytes/line. The buffer must be 32-byte aligned and the length a multiple of 32, or the clean touches adjacent lines. If you cannot align, put the buffer in a non-cacheable region instead.
| Step | SRAM before DMA | Wire |
|---|---|---|
| CPU fill, no clean | stale 0x00 | 512 × 0x00 |
| clean 16 lines, DSB | filled pattern | matches |
| invalidate after only | stale 0x00 | 512 × 0x00 |
For RX the order flips: invalidate before DMA to drop stale dirty lines, and invalidate after DMA before the CPU reads. For TX, clean before; invalidate after is unnecessary once the lines are clean.
Alternatives and when to use them:
- Non-cacheable MPU region for DMA buffers. No clean or invalidate at all. CPU writes go to SRAM (still need a DSB before DMA). Good for small control buffers and low bandwidth. Bad for high-throughput data: non-cacheable CPU writes are slower and lose write combining.
- Per-transfer clean/invalidate. Simple and correct for occasional transfers like a 512-byte SPI frame at 1 kHz. At high packet rates it hurts: every small Ethernet frame still costs at least one 32-byte line clean plus descriptor maintenance, and that can exceed the copy cost.
- Descriptor-based rings (Ethernet-style). Descriptors live in non-cacheable memory; data buffers are either non-cacheable or cleaned/invalidated at ownership changes. TX: write buffer, clean buffer, write descriptor with OWN=1, clean descriptor, DSB, doorbell. RX: invalidate descriptor before checking OWN, invalidate buffer after OWN=0. This amortizes and pipelines, but adds complexity and ownership bugs.
Avoid per-transfer cleans when the buffer is already non-cacheable, when the DMA engine is coherent (rare on Cortex-M), or when you can batch many transfers behind one clean. Do not skip the DSB: without it, the DMA start can be observed before the clean completes.
Failure modes to check: cleaning the wrong range or an unaligned buffer, so adjacent dirty lines get written; invalidating a dirty TX buffer and losing data; cache-line sharing with unrelated variables, so a clean writes more than intended. Detect by dumping SRAM with the cache off after fill+clean and requiring the 512 bytes, then matching the SPI capture. A 100% CRC failure with all-zero bytes is the signature of a missing clean.
Curated: · Written: · Reviewed:
Q&A-18DMA fills a 1,024-byte RX buffer. The CPU CRC is always stale by 32 bytes. What did you not clean?
You didn't invalidate the D-cache line holding the tail of the buffer. The CPU CRC reads cached copies of SRAM; DMA wrote SRAM directly and never touched the cache. The last 32 bytes, exactly one cache line, are the ones your invalidate range didn't cover, so the CRC mixes 992 fresh bytes with 32 stale ones.
Why exactly one line: 1,024 bytes is 32 cache lines only if the buffer starts on a 32-byte boundary. If it doesn't, the buffer spans 33 lines, and an invalidate of 1,024 bytes from the aligned-down base covers 32 of them. The line you missed is the last one. A deterministic 32-byte error is the signature of a range that stops one line short: a race would be intermittent, not always 32.
The fix: invalidate the whole span the DMA touched, rounded out to line boundaries, after the transfer completes and before any CPU read.
// buf is uint8_t[1024]; DMA wrote it; TC has fired.
uintptr_t start = (uintptr_t)buf & ~(uintptr_t)(32 - 1); // round down
uintptr_t end = ((uintptr_t)buf + sizeof(buf) + 31) & ~(uintptr_t)(32 - 1); // round up
SCB_InvalidateDCache_by_Addr((void *)start, (int32_t)(end - start));
Or place the buffer in a non-cacheable MPU region and skip the maintenance entirely: simplest, and what I'd do for a fixed DMA buffer.
Two things that bite:
- Ordering. Invalidate must come after TC and before the first CPU load. If you invalidate before the DMA's last burst lands, the line gets refetched with old data, but that's intermittent, not your always-32.
- Clean vs invalidate. For RX you invalidate. If you "clean" (write back) instead, you push stale CPU data over DMA's bytes: a different bug, and worse.
Detection: dump the last line before and after the invalidate; compare the CRC of the SRAM view against a scope decode of the 1,024 bytes; assert the buffer is 32-byte aligned at compile time (_Static_assert).
DMA complete is not CPU-visible until the cache agrees.
Curated: · Written: · Reviewed:
Q&A-91You reuse the TX buffer 2 µs after you start DMA. TC is 256 µs later. What is on the wire?
What's on the wire
A torn frame. The first bytes are the old buffer contents; the rest is the new data you wrote at 2 µs. The splice is not exactly at byte 2: it is at byte 2 plus however far the DMA has already read ahead into the SPI TX FIFO. On a part with a 16-byte TX FIFO the DMA can be 16 bytes ahead of the wire, so up to 18 bytes of the old buffer can go out before the new data appears. On a part with a single-byte buffer it is closer to 2.
Numbers: 8 MHz SPI, 8 bits per frame → 1 byte/µs. 256 bytes → 256 µs. At 2 µs, 2 bytes have been clocked out.
| Byte range on wire | Content | Why |
|---|---|---|
| 0 .. k-1 | old buffer | already clocked, or already staged in the TX FIFO |
| k .. 255 | new data | DMA read it after your write |
k = 2 + FIFO depth, and the FIFO depth is part-specific: read the reference manual, do not assume 1.
The receiver sees a frame whose header is the old payload and whose body is the new one. With a CRC or length field it fails. Without one you get silently wrong data, which is worse.
Why it is not deterministic
- Two moving cursors. The DMA read cursor and your CPU write cursor both advance. The wire is old up to the DMA cursor. Beyond it, each byte is new only if the CPU had already written it when the DMA got there. If the CPU write is slow or interrupted, the DMA can overtake it and clock old bytes in the middle of the frame: a non-monotonic tear, not a clean prefix/suffix split.
- Torn words. If the CPU writes byte-wise and the DMA reads 32-bit words, one word can hold old bytes in the low half and new bytes in the high half. The wire then carries a value that was never in either buffer.
- Cache. On Cortex-M7 with D-cache on, the DMA reads SRAM, not the cache. Your writes can still be dirty in cache and never reach memory before the DMA reads: the wire carries the old data for the whole frame even though you wrote new data. Clean before TX, invalidate after RX.
The TC trap
TC at 256 µs only says the DMA finished reading memory. It says nothing about whether the bytes on the wire were the ones you intended. A TC LED lighting is fully consistent with a corrupt frame. Do not use TC as a correctness signal.
What to do instead
- Double-buffer: two buffers, swap on half-transfer and transfer-complete interrupts. The CPU only writes the buffer the DMA is not reading.
- Or wait for TC before touching the buffer, with a
__DSB()before the write so the store is visible to the DMA. - Reading the DMA remaining-count register (NDTR on STM32) tells you how many bytes are pending: useful as a diagnostic, not as a synchronization primitive.
- Never stack-allocate a DMA buffer. If the frame is freed and the stack frame reused, the DMA reads whatever the next function left there: a stale leading byte followed by stack garbage, which is exactly the shape of an intermittent CRC failure that correlates with CPU load.
Detection
Logic-analyze the full 256 bytes and compare against a snapshot taken before the transfer started. Check the splice point against the FIFO depth you expect. If it will not reproduce on the bench, it will show up in the field as a CRC failure that tracks CPU load.
Curated: · Written: · Reviewed:
Q&A-14You DMA a packed 5-byte frame into a struct with a uint32_t field. The CRC at the end is always wrong. Why?
Assumptions: little-endian Cortex-M4, a __attribute__((packed)) struct so the uint32_t sits at offset 1, DMA writes the 5 bytes into SRAM, and the CRC is computed over the received frame.
Direct answer: The bytes in SRAM are correct. The CRC is wrong because it is computed over a different byte sequence than the one on the wire: the byte order the CRC consumes does not match the wire order. The unaligned uint32_t load is not the cause: on Cortex-M4 an unaligned LDR returns the correct bytes at that address (it faults only if CCR.UNALIGN_TRP is set), and a packed struct has no padding for the CPU to see differently from what DMA wrote.
Why the CRC diverges. Two mechanisms, both byte-order:
-
Word-oriented CRC input. If the CRC is fed the
uint32_tas a 32-bit word (a hardware CRC peripheral's data register, or a routine takinguint32_t) the peripheral or algorithm defines the order it consumes the four bytes, and that order is not necessarily the wire order. Feed the same four bytes as a word and you get a different CRC than feeding them byte-wise. -
Endianness mismatch. Wire is big-endian, MCU little-endian. Reading the field as a word and re-serializing flips the four payload bytes.
A third, if the struct were not packed: the uint32_t moves to offset 4, the struct grows to 8 bytes with 3 padding bytes, and a CRC over sizeof(struct) includes uninitialized padding.
Trace. Wire frame 01 AA BB CC DD (header 01, payload AA BB CC DD).
| Step | Bytes / value |
|---|---|
| wire | 01 AA BB CC DD |
| SRAM after DMA (packed, offsets 0..4) | 01 AA BB CC DD |
CPU reads uint32_t at offset 1 (LE) | 0xDDCCBBAA |
byte-wise CRC over &buf[1], 4 bytes | processes AA BB CC DD |
| word CRC shifting MSB-first | processes DD CC BB AA |
Same bytes in memory, two different CRC inputs.
Fixes and when each is wrong.
- Compute the CRC over the raw
uint8_tbuffer, not the struct fields. Cheapest, no layout change. Wrong if you must use the hardware CRC unit for throughput. - Match the CRC unit's byte order: assemble or byte-swap words before writing the CRC data register. Needed for hardware CRC. Wrong if the wire is already little-endian: you double-swap.
- Serialize explicitly into an aligned buffer with a defined byte order. Costs CPU cycles and a copy; right when the wire format and the in-memory format must differ.
Failure modes and detection. A byte-order bug fails 100% and deterministically, and passes on the other endianness, so it survives until you port. A padding bug is intermittent: it passes when the stack happens to be zeroed. Detect by dumping the SRAM destination as bytes next to a wire capture and computing the CRC both ways offline; check the CRC unit's documented bit and byte order before trusting it.
Curated: · Written: · Reviewed:
Q&A-60A TLV length field is 0xFFF0. The header is 256 bytes. Do you memcpy?
No. A 0xFFF0 length field is 65,520 bytes of claimed value in a 256-byte header. memcpy on that number writes past the end of the buffer, and in a bootloader that buffer is on the stack, so the overflow lands on the return address and the MSP. Reject it before the copy, not after.
The arithmetic is the whole argument. TLV header is 2 bytes of type plus 2 bytes of length, so the value starts at offset 4 and the bytes actually available for it are 256 - 4 = 252. The claimed length is 0xFFF0 = 65520. The copy would write 65520 - 252 = 65268 bytes past the end of the 256-byte buffer.
/* C11. hdr is 256 bytes read from flash; len is untrusted. */
#include <stdint.h>
#include <string.h>
int parse_tlv(const uint8_t *hdr, size_t hdr_len, uint8_t *out, size_t out_cap)
{
if (hdr_len < 4) return -1; /* need type + length */
uint16_t type = (uint16_t)(hdr[0] | (hdr[1] << 8));
uint16_t len = (uint16_t)(hdr[2] | (hdr[3] << 8));
size_t avail = hdr_len - 4; /* bytes left after the TLV header */
if (len > avail) return -2; /* length escapes the buffer */
if (len > out_cap) return -3; /* value does not fit the destination */
memcpy(out, hdr + 4, len); /* safe: len <= avail and len <= out_cap */
(void)type;
return (int)len;
}
Trace with hdr_len = 256, len = 0xFFF0: hdr_len < 4 is false; avail = 252; 65520 > 252 is true, so the function returns -2 and memcpy never executes. Trace with a benign TLV, len = 8, out_cap = 64: avail = 252, 8 > 252 false, 8 > 64 false, memcpy copies 8 bytes, returns 8. The bound check is one compare; the copy it prevents is 65,520 bytes.
| Policy | On len > avail | Cost | When it is right |
|---|---|---|---|
| Reject (fail-closed) | return error, stop parsing | one compare | bootloader, any security boundary |
| Truncate / clamp | copy avail bytes, continue | one min() | never for a boot header: silently accepts a corrupt image |
| Copy-then-validate | copy len bytes, check afterwards | full copy | only into a bounded scratch buffer you never execute from |
| Skip-and-continue | advance by len, keep walking | one add | log parsing, where one bad record should not kill the stream |
A plain memcpy after validation is fine when the length has already been proven against the destination capacity, as in the second trace above. The check is not overhead you can skip; it is the thing that makes the copy legal. What you must not do is copy first and validate the result, because by then the bytes are already on the stack.
Two failure modes worth naming. First, endianness: if the length is big-endian on the wire and you read it little-endian, 0x00F0 becomes 0xF000 and a 240-byte value looks like 61,440. Read the field the way the spec says, and fuzz both byte orders. Second, the overflow is silent until it is fatal: the bootloader MSP is smashed, the device bricks, and recovery needs SWD or JTAG. Detect it with an MPU region around the header buffer, a stack canary, and a fuzz corpus that includes 0xFFFF lengths; require zero writes outside the 256-byte buffer across the run.
TLV length is not a memcpy length. It is a claim, and the claim gets checked against the bytes you actually have.
Curated: · Written: · Reviewed:
Q&A-8M4 writes a 32-bit slot then sets a flag. M7 reads the flag then the slot. You still see torn values. Why?
Assumptions: Cortex-M4 producer, Cortex-M7 consumer, shared SRAM, M7 D-cache enabled, flag and slot are normal memory, slot is a single aligned 32-bit word. "Torn" means the flag and slot are not a consistent pair, or the slot is read while being written.
The flag is not a memory barrier and not a lock. Three independent reasons.
-
Store buffer on M4. Cortex-M4 has a write buffer. Stores can be committed to memory out of program order. The flag store can become visible to M7 before the slot store. M7 reads flag=1, then reads the slot and gets the previous value. That is a stale read, not a torn word.
-
M7 load reordering and cache. M7 reads flag then slot. The slot load is not data-dependent on the flag value, so the processor can issue it before the flag load completes. If the slot is cacheable, M7 can also hit a stale cache line for the slot while the flag read misses to memory. So even if the flag is new, the slot is old.
-
No mutual exclusion. The flag only says "a message was written", not "the slot is stable". M4 can write the slot again while M7 is reading it. If M4 writes slot n+1 before M7 finishes reading slot n, M7 can read a mix of n and n+1. That is the torn value you see. A single flag cannot prevent this; you need a handshake or a sequence number.
Tradeoffs. A DMB pair (DMB after slot store before flag on M4; DMB after flag read before slot read on M7) fixes ordering but not overwrite. It is cheap and sufficient only if the producer never writes again until the consumer acknowledges. A hardware semaphore (e.g., STM32 HSEM) provides mutual exclusion and fixes overwrite, but adds latency and can block; it is overkill for a single producer/consumer mailbox. A seqlock (sequence number) allows lock-free reads and detects overwrite; the reader retries on a torn read. Deciding criterion: if the producer can write again before the consumer reads, DMB alone is insufficient; use a seqlock or a handshake.
Failure modes: stale slot (flag seen before slot), torn across messages (producer overwrites while consumer reads), cache coherency (M7 reads stale slot from D-cache), compiler reordering (flag store moved before slot store), missed flag (compiler caches flag in register). Detect with a logic analyzer on the flag pin and a counter of mismatches.
Artefact: seqlock for a 32-bit slot. Code checked against ARMv7-M and CMSIS 5.
// Shared, non-cacheable or with cache maintenance
volatile uint32_t seq = 0;
volatile uint32_t data;
// M4 producer
void write(uint32_t v) {
seq++; // odd: writing
__DMB();
data = v;
__DMB();
seq++; // even: done
}
// M7 consumer
uint32_t read(void) {
uint32_t s0, s1, d;
do {
s0 = seq;
__DMB();
d = data;
__DMB();
s1 = seq;
} while (s0 != s1 || (s0 & 1));
return d;
}
Trace: M4 writes v=0xAAAA. seq becomes 1 (odd). DMB. data=0xAAAA. DMB. seq becomes 2 (even). M7 reads s0=2, DMB, d=0xAAAA, DMB, s1=2. s0==s1 and even, returns 0xAAAA. If M4 writes v=0xBBBB while M7 is between s0 and s1: seq becomes 3, data=0xBBBB, seq becomes 4. M7 reads s1=4, s0=2, mismatch, retries. It never returns a torn value.
This is the mechanism. A flag alone cannot do this because it does not detect the overwrite.
Curated: · Written: · Reviewed:
Q&A-99M4 and M7 both write a 64-byte log slot. You see mixed ASCII. What did you call how dual-core works?
What I'd say in the first two minutes
The question is two cores writing the same 64-byte buffer with no protocol between them. That's a data race, and the mixed ASCII is a torn write: bytes from M4's record and M7's record interleaved in one slot. On an STM32H7-class part it's worse than a plain race, because M7 has a write-back D-cache and M4 doesn't, and there is no hardware coherency between the two cores.
Assumptions: M4 and M7 both running, the 64-byte slot in shared SRAM, no MPU region marking it non-cacheable, no lock.
Mechanism
64 bytes is 16 32-bit stores. Each store is atomic on its own; the sequence isn't. M4 can land stores 1-4, M7 lands 5-16, and the slot holds half of each record. Nothing in the bus fabric serializes the two cores' store streams.
The cache makes it worse. M7's D-cache has 32-byte lines, so a 64-byte slot spans two lines. If the slot is cacheable on M7, M7's writes sit dirty in cache and get evicted later, possibly after M4 has written its own record, so M7's stale line clobbers M4's bytes. M4 also never sees M7's writes until eviction. That's the mixed ASCII that survives even when the timing looks fine.
Options and what they cost
| Approach | Cost | Use when |
|---|---|---|
| HSEM hardware semaphore around the 64 bytes | serializes writers; a few bus cycles per take; deadlock if a core halts holding it | both cores must write the same slot and ordering matters |
| Single-writer slots (one slot per core) | no lock, no contention; reader must merge and you lose global order | logging, where per-core streams are fine |
| SPSC ring + DMA/mailbox with head/tail | lock-free; needs head and tail on separate cache lines and DMB barriers; adds latency | high rate, one producer per ring |
| MPU non-cacheable region + one-word atomic record | cheapest, but only if the record fits in a word | small fixed records |
If the record must be 64 bytes and both cores write it, HSEM plus an MPU non-cacheable region is the honest answer. If you can change the format, single-writer slots remove the problem instead of managing it.
Failure modes and detection
- Torn record: detect with a per-record CRC or a magic plus sequence number; a reader that sees a bad CRC drops the record.
- Stale cache line: M4 reads a slot that never changes while M7 insists it wrote it. Detect by reading the same address from both cores and comparing.
- HSEM deadlock: a core halts while holding the semaphore. Detect with a take timeout and a recovery path that releases by master ID.
Worked example (hypothetical numbers)
Each core logs at 1 kHz, so the slot is written 2,000 times/s. Over 10 minutes that's 2,000 x 600 = 1,200,000 writes. If 7.4% come out torn, that's 88,800 corrupt records: enough to make the log useless. With HSEM held across the 64 bytes, torn records go to zero; the cost is the serialization, which at 2 kHz is nothing.
Curated: · Written: · Reviewed:
Q&A-38A task takes a SPI mutex. The ISR also bit-bangs CS on that bus. You see torn 16-bit ADC words. Why?
A mutex is a scheduler object. An ISR doesn't run under the scheduler, so it can't take one, and if the ISR bit-bangs CS on the same bus, nothing the task does with the mutex excludes it. CS is the frame delimiter for the ADC: the ISR's CS pulse lands inside the task's 16-clock frame, the ADC sees a frame boundary mid-transfer, and the task's SPI peripheral keeps clocking and latches whatever is on MISO for the remaining bits. The torn word is the back half of the frame coming from somewhere other than the ADC's conversion result.
Assumptions: single core, the ISR is a hardware interrupt rather than a high-priority task, CS is a plain GPIO the ISR drives, and the task's SPI is a hardware peripheral that doesn't abort the frame on its own.
Why the mutex can't help. The task takes the mutex and holds it for the whole transaction. The ISR never calls take, so it never blocks, so the mutex is uncontended: a no-op. The tell is that the "mutex taken" LED still toggles at the expected rate: the task never waits. A lock only excludes parties that both use it.
Worked trace. SPI at 1 MHz, so a 16-bit ADC read is 16 µs of SCLK. The task asserts CS, waits 2 µs setup, clocks 16 µs, holds 2 µs: CS low for 20 µs. A 10 kHz timer ISR bit-bangs a 2-byte status word, 16 µs at 1 MHz.
| Event | Duration | Effect |
|---|---|---|
| Task CS low | 20 µs | frame in progress |
| Task SCLK window | 16 µs | 16 bits shifted |
| ISR period | 100 µs | fires every 100 µs |
| ISR lands in the task's clock window | 16/100 = 16% | frame torn |
In one capture the ISR landed during the second byte: the high byte 0x03 was already latched, the low byte came back as the ISR's status byte 0x11, so 0x03E8 (1000 counts) read as 0x0311 (785). Torn samples measured 16%, matching the 16 µs window against the 100 µs period. Landing in the first byte instead corrupts the high byte: the tear is always at a byte boundary, never a single flipped bit.
What to do instead.
- Defer the ISR's bus work. The ISR posts to a queue or gives a task notification; a bus-owner task does the status read. The ISR returns without touching the bus, and the status read waits behind the ADC transaction. Cost: the status read is now bounded by task scheduling latency rather than by the ISR.
- Mask that one IRQ line around the transaction (NVIC disable/enable, or a critical section). Keep it to one frame: 20 µs here. On Cortex-M, taskENTER_CRITICAL raises BASEPRI to configMAX_SYSCALL_INTERRUPT_PRIORITY, so it masks only interrupts at or below that priority; an ISR with a numerically lower priority value still preempts and still steals CS. Disable the specific line if you need certainty.
- xSemaphoreTakeFromISR doesn't fix this. It can't block, so it returns pdFALSE when the bus is busy and the ISR has to do something else anyway.
Detection. Logic-analyzer CS against SCLK, triggering on two CS assertions inside one frame or on CS edges closer together than a frame period. In firmware, a status or CRC bit on the ADC word catches it without a probe.
Curated: · Written: · Reviewed:
Q&A-43Two tasks "take" a counting semaphore around a UART. Bytes interleave. Why was a mutex the right object?
Short answer. A counting semaphore is a counter, not a lock. xSemaphoreCreateCounting(2, 2) starts at two, so both tasks' xSemaphoreTake calls succeed and neither blocks: you get two writers on one UART, which is the interleaving you saw. A mutex has an owner: only the task that took it can give it back, and the kernel boosts that owner's priority while a higher-priority task waits. Ownership is the property the UART needs, and the count of two is what removed it.
Assumptions: FreeRTOS 10.x/11.x API, both senders are tasks (not ISRs), and a frame has to leave the UART as an unbroken byte sequence.
What take means for each object. For a counting semaphore, xSemaphoreTake decrements a counter if it is non-zero. Nothing records who decremented it, so a second task can decrement again, and any task, or an ISR via xSemaphoreGiveFromISR, can increment it back. For a mutex, xSemaphoreTake succeeds only if the count is 1, sets the count to 0, and records the calling task as holder. A second task blocks. xSemaphoreGive from a non-holder is a bug the kernel can catch, and a mutex must not be given from an ISR at all.
Trace of the failure. Two tasks, A sends 41 42, B sends 31 32, semaphore created (2, 2):
- count = 2. A takes → count 1. B takes → count 0. Both proceed; neither blocks.
- A writes
41. - A is preempted before its next byte.
- B writes
31. - A writes
42. - B writes
32.
Wire: 41 31 42 32. The receiver sees 41 then 31 and the frame check fails. With a mutex: A takes (count 1→0, A is holder), B calls take and blocks, A writes 41 42, gives, B wakes and writes 31 32. Wire: 41 42 31 32.
static SemaphoreHandle_t uart_lock; /* one per UART */
void uart_init(void) {
uart_lock = xSemaphoreCreateMutex();
configASSERT(uart_lock != NULL);
}
/* Task context only. false = lock busy past timeout. */
bool uart_send_frame(const uint8_t *buf, size_t len, TickType_t timeout) {
if (xSemaphoreTake(uart_lock, timeout) != pdTRUE) return false;
for (size_t i = 0; i < len; i++) uart_write_byte_blocking(buf[i]);
xSemaphoreGive(uart_lock);
return true;
}
When something else is the right object.
| Object | Owner | Priority inheritance | Give from ISR | UART TX mutual exclusion |
|---|---|---|---|---|
| Mutex | Yes | Yes | No | Yes, when a task holds across the frame |
| Binary semaphore | No | No | Yes | No: it is a signal, not a lock |
| Counting semaphore, max 1 | No | No | Yes | Only by convention; a stray give unlocks it |
| Counting semaphore, max N | No | No | Yes | No: N concurrent writers |
taskENTER_CRITICAL | n/a | n/a | n/a | Only for a few bytes; masks interrupts |
| Single writer task + queue | n/a | n/a | n/a | Best when frames are queued anyway |
Use a binary semaphore when the UART ISR is signalling a task that TX space is free: that is a signal, and it must come from an ISR, which a mutex cannot. Use a critical section only if the whole frame is a couple of bytes: at 115200 baud, 8N1 is about 0.69 ms for eight bytes, and masking interrupts for that long is worse than a context switch. If frames are already queued, drop the lock entirely: one TX task owns the UART and drains a queue of frame buffers, so there is nothing to interleave.
Failure modes to watch. Priority inversion: a low-priority holder preempted by a medium task blocks a high-priority waiter; the mutex's inheritance bounds this, a counting semaphore does not. Self-deadlock: a task that takes a plain mutex it already holds blocks forever. Use xSemaphoreCreateRecursiveMutex if re-entry is real. A blocking write under the lock with no timeout stalls every sender behind it, so pass a timeout and handle pdFALSE. And a give from an ISR on a mutex trips an assert; route ISR signalling through a binary semaphore instead. The kernel records the holder because inheritance needs it, so a debugger or trace shows who holds the lock when a sender is stuck.
Curated: · Written: · Reviewed:
Q&A-41A low-priority log task holds SPI. A high-priority control task blocks 8 ms. What RTOS feature did you not enable?
Priority inheritance on the mutex that guards the SPI bus. The log task's lock is a plain mutex (or a binary semaphore used as one) with no inheritance, so when the control task blocks on it the kernel never raises the holder's priority. The low-priority task keeps running at its own priority, and every medium-priority task that becomes ready preempts it. That is unbounded priority inversion, and it is the feature you left off.
What inheritance actually does
When control (prio 8) blocks on the mutex, the kernel boosts the holder (log, prio 1) to 8 for the duration of the hold. The medium-priority GUI task can no longer preempt it, so the holder finishes its critical section at full speed and releases. Control then runs. Inheritance removes the interference; it does not shorten the hold. That distinction is the whole answer.
Trace (hypothetical, 1 ms control loop)
Log acquires the SPI mutex at t=0 and holds it for an 8 ms printf. Control posts at t=0.1 ms. GUI (prio 4) becomes ready at t=0.1 ms.
| Scenario | Log releases | Control starts | Control jitter |
|---|---|---|---|
| No inheritance | 15.9 ms | 15.9 ms | 15.8 ms |
| Inheritance on | 8.0 ms | 8.0 ms | 7.9 ms |
| Inheritance + 42 µs hold | 0.14 ms | 0.14 ms | 0.04 ms |
Row 1: GUI preempts log at 0.1 ms and runs 7.9 ms; log resumes and needs its remaining 7.9 ms. Row 2: log is boosted to 8, GUI cannot preempt, log finishes its 8 ms uninterrupted. Row 3: the printf is formatted into a buffer outside the lock and only the 42 µs SPI transfer is held. Inheritance alone still blows a 1 ms loop: the 8 ms hold is a second, independent bug.
Alternatives and when inheritance is not enough
- Priority ceiling (immediate ceiling protocol). The holder is boosted to a fixed ceiling on acquisition, not on contention. It bounds blocking to at most one critical section per task and prevents deadlock, but you must know the ceiling statically. POSIX exposes it as
PTHREAD_PRIO_PROTECT; FreeRTOS does not offer it. - Split the lock. Format the log line outside the critical section, hold the bus only for the transfer. This is the fix that actually meets the deadline.
- Deferred logging. The log task writes to a ring buffer; a separate low-priority writer drains it to SPI. The bus is never held by a task that can block on I/O.
- Inheritance is insufficient when: the hold is long (it only removes interference), when blocking chains across two nested mutexes (inheritance does not bound chained blocking), when lock ordering differs between tasks (deadlock), or when an ISR needs the same bus. An ISR cannot inherit a priority.
Detection
Toggle a GPIO on mutex acquire and release and capture it against a GPIO set when control posts. On FreeRTOS, confirm configUSE_MUTEXES is 1 and that the lock is xSemaphoreCreateMutex(), not xSemaphoreCreateBinary(): the binary semaphore silently has no inheritance. Zephyr's k_mutex inherits; k_sem does not. CMSIS-RTOS2 needs osMutexPrioInherit in the attribute struct. A Percepio Tracealyzer or SystemView capture shows the ready-time gap directly.
Acceptance: control starts within 50 µs of posting, with inheritance enabled and the printf outside the lock.
Curated: · Written: · Reviewed:
Q&A-42The loop does work then vTaskDelay(1). The phase wanders versus the tick. Which API did you want?
The firmware question under vTaskDelay versus vTaskDelayUntil on a 1 kHz loop is which path still races after the path I just stepped through.
I treat vTaskDelay as relative to the current tick count. vTaskDelay(1) unblocks on the next tick, about 1 ms at 1 kHz from the tick boundary, not work-time plus 1 ms. vTaskDelayUntil is absolute from a stored wake tick so the loop keeps phase.
Concretely, i capture last_wake, I DelayUntil 1 tick at a 1 kHz tick, and I measure period and phase on a GPIO versus SysTick.
The reason for that specificity is a failure I have seen: Work was 400 µs. Delay(1) fired on the next tick (~1.0 ms from the previous tick, ~600 µs after the call), so period stayed near 1 ms but started 400 µs late relative to the plant's sample instant. Integrator of a 1 kHz plant saw a moving phase. Overshoot 22 percent. DelayUntil kept the 1.000 ms grid. A debugger halt made both look like 1 ms because halt stops the tick.
1 kHz loop with 400 µs work.
| API | Work | Period | Phase vs tick |
|---|---|---|---|
| vTaskDelay(1) | 400 µs | ~1.0 ms (next tick) | +400 µs slip |
| vTaskDelayUntil | 400 µs | 1.0 ms | locked |
| overshoot | — | — | 22% with Delay |
I would not consider it settled without evidence: I would scope the loop GPIO versus the tick for 10 s and require mean period 1.000 ms ± 50 µs and phase locked with DelayUntil, not Delay.
Delay waits until the next tick. DelayUntil keeps phase.
Curated: · Written: · Reviewed:
Q&A-50Two tasks at priority 3. One hogs 3 ms of CPU. The other needs 200 µs every 1 ms. Time slicing is off. Who never runs?
The 200 µs task never runs: provided the hog never blocks.
Assumptions that decide it: a preemptive priority scheduler (FreeRTOS-style), both tasks at priority 3, time slicing disabled (configUSE_TIME_SLICING 0), and the hog is a pure compute loop with no blocking call, yield, or higher-priority preemption. Change any of those and the answer changes.
Mechanism: the scheduler only switches tasks at three points. A blocking call, an explicit yield, or a preemption by a strictly higher priority. A task that becomes ready at the same priority as the running task does not preempt it. So when the 1 ms tick releases the peer, the kernel marks it ready, sees no higher-priority task, and returns to the hog.
Trace, 1 ms tick, peer released every tick:
| t | event | ready tasks | running |
|---|---|---|---|
| 0 | hog starts | hog | hog |
| 1 ms | tick; peer released | hog, peer | hog |
| 2 ms | tick; peer already ready | hog, peer | hog |
| 3 ms | tick | hog, peer | hog |
The peer's first 200 µs window closes at 1.2 ms with the peer still in the ready queue. Every window after that is missed the same way.
The 3 ms figure only matters if it means the hog blocks after 3 ms. If it's a 3 ms burst then a vTaskDelay or a semaphore wait, the peer runs in the gap, but only once per 3 ms, so it still misses two of every three deadlines. If the hog is a continuous loop, the peer never runs at all.
Fixes, in the order I'd try them:
- Raise the peer above the hog. A strictly higher priority preempts on release, so the peer's 200 µs starts within microseconds of the tick. Cleanest for a hard deadline. Cost: the hog's throughput drops by the peer's 20% duty cycle.
- Enable time slicing. With two equal-priority ready tasks the kernel alternates each tick: hog 1 ms, peer 1 ms. The peer's 200 µs fits inside its slice. Cost: a context switch every tick, and up to 1 ms of release jitter. Fine for a 200 µs job with a 1 ms period only if the deadline is the period, not tighter.
- Make the hog yield.
taskYIELD()or a shortvTaskDelay(1)each iteration hands the CPU over cooperatively. Cheapest, but it depends on the hog's author remembering to do it: fragile.
If the two share a mutex, the priority split needs priority inheritance, or the hog can invert the peer's priority and starve it anyway.
Failure modes to look for, and how to see them:
- The peer's input overflows. A UART RX FIFO or DMA ring fills because nothing drains it; the overrun bit in the peripheral status register sets, or a queue-full counter climbs. At 115,200 baud a byte lands every 86.8 µs, so an 8-deep FIFO covers 694 µs: less than one missed 1 ms window.
- The peer's watchdog fires, or its output goes stale.
- Detection: toggle a GPIO at the top of each task and scope both. The hog's pin runs continuously; the peer's stays flat. That single capture settles it.
Don't call it fixed until the peer's 200 µs appears inside every 1 ms window on the scope.
Curated: · Written: · Reviewed:
Q&A-49A 1 ms software timer runs a 400 µs SPI burst. The daemon is idle priority. The control task hogs 82 ms then delays 1 tick. What did you mis-prioritize?
I pin software timer daemon priority to a scope channel or a current shunt before I trust any LED or printf about it.
I treat timer callbacks as running in the daemon task. If the daemon is below an always-ready control task, the timer only runs in the leftover delay. That leftover is what sets the observed rate.
Concretely, i keep callbacks short, I set daemon priority above background and below control, or I move the SPI to a dedicated task signaled by the timer.
The reason for that specificity is a failure I have seen: Daemon priority 0. Control priority 5 ran 82 ms of compute then vTaskDelay(1) at 1 kHz, a 83 ms cycle. Daemon ran in that 1 ms window. One 400 µs SPI callback per 83 ms is 1/0.083 ≈ 12 Hz. SPI burst 12×400 µs = 4.8 ms/s instead of 1 kHz × 400 µs = 400 ms/s. Sensor 12 Hz versus 1 kHz. The timer-create LED still went on at init.
1 ms software timer under an 82 ms control hog.
| Item | Value |
|---|---|
| intended callback | 1 kHz, 400 µs SPI |
| daemon priority | 0 |
| control | 82 ms work + 1 ms delay = 83 ms |
| achieved callback | 1/0.083 ≈ 12 Hz |
| SPI duty | 4.8 ms/s vs 400 ms/s |
I would not consider it settled without evidence: I would GPIO the callback and require 1,000 Hz ± 1 percent, then show the daemon priority and the 82 ms hog in the report.
A timer is only as real-time as its daemon.
Curated: · Written: · Reviewed:
Q&A-11uxTaskGetStackHighWaterMark returns 12 words. Do you ship?
No. 12 words is 48 bytes on a 32-bit Cortex-M port, and one exception frame with the FP context live is 26 words, 104 bytes. The margin is smaller than the largest single push that can land on that stack.
State the assumptions before trusting the number: Cortex-M4F, StackType_t is 32-bit, INCLUDE_uxTaskGetStackHighWaterMark is 1 so FreeRTOS filled the stack with 0xa5 at creation, and the task has run its normal path but not necessarily its worst one.
What the number is. uxTaskGetStackHighWaterMark scans up from the low end of the stack for the first word that is no longer the fill byte and returns the count of untouched words. It is a running minimum since the task was created, not a current reading. 12 words means the deepest excursion so far left 48 bytes; it says nothing about the paths that have not run.
Where the frame comes from. On Cortex-M, exception entry from thread mode pushes the frame onto the stack in use, the task's PSP, and the handler then runs on MSP. Nested interrupts push onto MSP, not the task stack. So the task stack sees at most one frame, never a nest; the nest is an MSP budget problem. The frame is 8 words basic, 26 words when the FP context is active (18 extra), with lazy stacking.
The arithmetic. A 2048-byte stack is 512 words.
| Item | Words | Bytes |
|---|---|---|
| Stack size | 512 | 2048 |
| Watermark (minimum free) | 12 | 48 |
| Basic exception frame | 8 | 32 |
| Frame with FP context | 26 | 104 |
| Written past the low end if an FP frame lands at the deepest point | 14 | 56 |
An interrupt that lands at the deepest point of the call tree writes 56 bytes below the stack block. The stack is a pvPortMalloc block, so that lands in the adjacent heap block. The symptom appears later: a corrupted queue, a bad pointer, a HardFault in code that has nothing to do with this task.
The one version of this that is not an automatic no: if the task provably never touches FP and the deepest path has already run, 12 words covers an 8-word frame with 4 words left. That is still too thin for me, but it is the only case worth arguing.
What I'd do instead of shipping. Force the worst path, deepest call tree with FP active and an interrupt landing at the bottom, then re-measure. Because the watermark is a running minimum, the worst path has to have actually executed; recreate the task or re-fill the unused region yourself before the run. Require at least one full FP frame (26 words) plus headroom for the call tree you have not exercised. I use one frame plus 25% of the stack as the floor.
Backstops, not margins. configCHECK_FOR_STACK_OVERFLOW=2 checks the fill pattern at the end of the stack at context switch and calls the hook. It fires after the corruption, and only if the pattern was disturbed. A watchpoint on the last word of the stack block under a debugger catches it earlier.
Two footnotes. uxTaskGetStackHighWaterMark2 returns configSTACK_DEPTH_TYPE rather than UBaseType_t; that matters on 16-bit ports where UBaseType_t truncates, and makes no difference on Cortex-M. And the MSP budget is separate: nested EXTI plus FP frames there need their own accounting, and on the ARMv8-M ports FreeRTOS runs handlers on a dedicated ISR stack sized by configISR_STACK_SIZE_WORDS.
Curated: · Written: · Reviewed:
Q&A-47CAN FIFO is 3. You queue to a length-4 RTOS queue from ISR. You still drop. Where?
The drop is at the software queue first, then at the CAN FIFO. The sequence matters.
A CAN frame arrives and the controller puts it in its 3-deep RX FIFO. The RX interrupt fires. The ISR reads a frame from the FIFO and calls the RTOS queue send-from-ISR API, for example FreeRTOS xQueueSendFromISR. If the queue already holds 4 items, that call returns pdFALSE and the frame is dropped right there. If the ISR does not run before a fourth frame arrives, the CAN FIFO overflows instead. So you have two overflow counters to watch: the CAN controller's RX overflow status and the queue-full return from the ISR send.
The combined buffering is 3 + 4 = 7 frames only if the ISR drains the FIFO into the queue as frames arrive. If the queue is full, the ISR cannot drain, so the FIFO overflows next. The drop location depends on whether the task is slow or the ISR is late.
| Alternative | When it applies | Cost or risk |
|---|---|---|
| Deepen the software queue | Task latency is bounded and RAM is available | More RAM, longer worst-case latency; no help if the task can block indefinitely |
| Drain in ISR to a larger ring buffer | Task latency is bounded but queue depth is limited | ISR does more work, increasing interrupt latency for other IRQs |
| DMA from CAN to memory | MCU has CAN DMA and throughput is high | More complexity; overflow just moves to the DMA buffer |
| Raise the CAN task priority | The task is preempted by lower-priority work | Can starve other tasks and cause priority inversion if it shares resources |
| Increase hardware FIFO or mailboxes | The CAN controller allows it | Often fixed in silicon; may not be available |
Concrete failure modes: calling a blocking queue send from the ISR instead of the FromISR variant; queueing a pointer to a single CAN mailbox that is overwritten before the task reads it; CAN ISR priority lower than other ISRs so it is delayed; reading only one frame per interrupt and leaving the FIFO to overflow; a shared FIFO across multiple filters so one filter fills it.
Take a hypothetical 1 Mbps bus with standard 8-byte frames. With bit stuffing, a frame takes about 120 µs, so peak arrival is roughly 8.3 kHz. A 2.1 ms task stall is 2.1 ms / 120 µs = 17.5 frames. With 3 + 4 = 7 frames of buffering, you drop about 10.5 frames, or 60 percent of that burst. The queue send from ISR succeeds for the 4 that fit and fails for the rest; the CAN FIFO overflows after the queue is full.
Instrument both counters during a 2.1 ms stall and require zero. If the queue-full counter fires, size the queue to the worst-case burst, here at least 18, round to 24. If the CAN overflow counter fires, the ISR is too late: raise its priority, drain more per interrupt, or use DMA. Do not read the 3-deep CAN FIFO as if it were the only buffer.
Curated: · Written: · Reviewed:
Q&A-40You drain a 32-byte SPI FIFO in a 1 kHz task. The fill is 4 Mbps. How many bytes overflow per millisecond?
468 bytes per millisecond: 93.6% of the stream.
The arithmetic:
- 4 Mbps ÷ 8 = 500,000 B/s = 500 B/ms.
- 32 B ÷ 500 B/ms = 64 µs for the FIFO to fill from empty.
- One 1 kHz task period is 1,000 µs. The task drains 32 B; the wire delivers 500 B. 500 − 32 = 468 B lost.
The FIFO depth, not the task period, sets the deadline. 32 bytes buys 64 µs of slack; the task returns every 1,000 µs. Everything arriving after the first 64 µs of each period has nowhere to land.
What the peripheral does with it: the RX FIFO fills, the next received byte sets the overrun (OVR) flag, and the hardware discards it. The flag latches until you clear it, so one read at the end of the period tells you an overrun happened but not how many bytes went. Count received bytes over a known interval instead.
| Item | Value |
|---|---|
| Bit rate | 4 Mbps |
| Byte rate | 500,000 B/s = 500 B/ms |
| FIFO depth | 32 B = 64 µs of fill |
| Task period | 1,000 µs |
| Drained per period | 32 B |
| Lost per period | 468 B (93.6%) |
Fixes, in order of how much headroom they buy:
- DMA circular, buffer ≥ one period's burst. 500 B/ms means a 1 kB buffer gives 2 ms of slack; half- and full-transfer interrupts keep the CPU out of the per-byte path.
- Interrupt at ≤ 50 µs, not 1,000 µs. 50 µs leaves ~14 µs of margin under the 64 µs fill time for ISR latency and higher-priority interrupts.
- Lower the clock. At 1 Mbps the same FIFO holds 256 µs: still short of 1 ms, so you need DMA or a faster ISR either way.
Failure mode to watch: an activity indicator wired to FIFO-not-empty keeps blinking while data is being dropped, because the FIFO is saturated, not idle. The indicator cannot tell healthy draining from overflow. The overrun flag plus a byte count over a fixed window are the only honest signals.
Verification: scope SCLK for 1 ms, count edges, compare against 500 bytes. If the received count is short and OVR is set, the drain rate is the cause.
Curated: · Written: · Reviewed:
Q&A-95You DMA-circular 256 bytes. A 9-byte NMEA sentence waits 200 ms for the FIFO to fill. What interrupt did you not enable?
You didn't enable the USART IDLE line interrupt (or the UART receive-timeout interrupt if your peripheral has one).
Assumptions: NMEA 0183 at 4800 baud, 8N1, STM32-style USART with DMA circular RX into a 256-byte buffer. The sentence is 9 bytes and arrives every 200 ms.
DMA transfer complete (TC) fires only after 256 bytes have been transferred. At 9 bytes per 200 ms, that's 256/9 ≈ 28.4 sentences, so TC fires after ~5.7 s. Half-transfer (HT) fires at 128 bytes, ~2.8 s. Both are too slow for navigation. The IDLE interrupt fires when the RX line is idle for one full frame after the last stop bit. At 4800 baud, one frame is 10 bits / 4800 = 2.08 ms. So you get an interrupt ~2 ms after the sentence ends.
In the IDLE ISR, read the DMA remaining count (NDTR) to find how many bytes have arrived. Compute the head pointer as buffer_size - NDTR. Process the slice from your last read position to head, handling wrap-around. Pseudocode:
// USART IDLE ISR
clear_idle_flag();
uint16_t remaining = DMA_NDTR(channel);
uint16_t head = BUF_SIZE - remaining;
if (head >= last_pos) {
process(&buf[last_pos], head - last_pos);
} else {
process(&buf[last_pos], BUF_SIZE - last_pos);
process(&buf[0], head);
}
last_pos = head;
If your UART has an RX FIFO with a timeout interrupt (e.g., STM32H7 RXFIFO timeout), that also works. DMA double-buffer mode with HT/TC still gives 2.8 s or 5.7 s latency, so it doesn't solve the problem.
Failure modes:
- Only TC enabled: navigation data is 5.7 s stale. The fix is IDLE.
- Only HT enabled: 2.8 s stale.
- IDLE enabled but wrap not handled: you process stale or duplicate bytes. Check that head < last_pos triggers two process calls.
- IDLE enabled but NDTR read after clearing flag: if new bytes arrive between flag clear and NDTR read, you might process a partial new sentence. Read NDTR first, then clear flag, or disable interrupt briefly.
Detection: toggle a GPIO in the IDLE ISR and measure time from the last byte of a sentence to the GPIO edge. It should be ~2 ms at 4800 baud, not seconds. Also log NDTR at each ISR to confirm the byte count matches the sentence length.
You still need to parse NMEA sentences, validate checksums, and handle partial frames if a sentence is split across DMA reads.
Curated: · Written: · Reviewed:
Q&A-96SPI TXE fires on an STM32F407. You deassert CS 0 ns later. The last bit is still in the shift register for 125 ns. The slave drops it. Why?
Short answer: TXE is a buffer flag, not a wire flag. On the F407 the SPI has a one-byte transmit buffer feeding a separate shift register. TXE=1 means the buffer has handed its byte to the shift register and can accept the next one: the shift register is now clocking that byte out, one bit per SCLK period. Raise CS at that instant and NSS goes high while the shift register is still driving the last bit. The slave sees the frame end mid-byte and discards it.
Mechanism. Write to SPI_DR: the byte lands in the TX buffer and TXE clears. When the shift register is free, the byte moves across and TXE sets again. So TXE asserts at the start of a byte's transmission, not the end. At 8 MHz SCLK one bit is 125 ns, so up to 8 × 125 ns = 1 µs of shifting can remain when TXE goes high. The 125 ns in the question is the tail: the last bit still needs one bit period on the wire.
TC is the flag that means "last bit shifted out." BSY means the SPI is still communicating. Neither is TXE. (The F4 has no FIFO: TXE is a single-byte buffer flag. The H7/L4+ have 16-byte FIFOs and an EOT flag; don't carry F4 assumptions onto those parts.)
Why the slave drops it. A slave needs NSS low from before the first SCLK edge to after the last one, plus a hold time t_CSH from its datasheet. Raise NSS 125 ns early and the last bit is never clocked with NSS asserted, so the slave's shift register holds a partial frame and the transaction is discarded: CRC fails, or the byte is dropped.
Correct sequence:
// STM32F407 SPI1, 8 MHz SCLK, 8-bit, software NSS
SPI1->DR = byte; // TXE clears; byte -> TX buffer
while (!(SPI1->SR & SPI_SR_TXE)) {} // buffer empty: byte now in shift register
while (!(SPI1->SR & SPI_SR_TC)) {} // last bit shifted out
while ( SPI1->SR & SPI_SR_BSY) {} // SPI fully idle
// now raise CS, after the slave's t_CSH
For multi-byte frames, write the next byte when TXE sets; only the last byte needs the TC wait before CS.
Timing at 8 MHz (125 ns/bit):
| Event | Flag | Meaning | Time left on wire |
|---|---|---|---|
| Write DR | TXE=0 | byte in TX buffer | — |
| byte → shift reg | TXE=1 | buffer free, shifting starts | up to 1 µs (8 bits) |
| last bit out | TC=1 | shift register drained | 0 |
| SPI idle | BSY=0 | safe to raise CS | 0 |
Detection. Symptom is intermittent CRC errors or a dropped last byte, worse as SCLK rises (the CS window shrinks in absolute time). Probe CS and SCLK, trigger on CS rising, and check the last SCLK edge precedes CS by at least t_CSH. If CS rises before the last edge, that is the bug.
Alternatives. Hardware NSS (SSM=0) lets the peripheral drive NSS for the frame, but you still owe the slave t_CSH, and F4 hardware NSS pulses between bytes in some modes. With DMA, wait for the DMA transfer-complete and TC/BSY: DMA finishing means the last byte left memory, not that it left the wire. On H7, EOT is the clean end-of-transfer flag; F4 has no EOT, so TC + BSY is the equivalent.
Curated: · Written: · Reviewed:
Q&A-78You ITM-printf 80-byte lines at 1 kHz. SWO is 2 MHz. You drop 40 percent of lines. What rate did you not compute?
The rate you didn't compute is the encoded on-wire rate, payload plus ITM stimulus headers plus timestamp packets plus UART framing, not the 800 kbit/s payload rate.
You computed 80 B × 1000/s = 80 kB/s = 640 kbit/s, then ×10/8 for UART 8N1 = 800 kbit/s, and compared it to 2 Mbit/s. 800/2000 = 40%, exactly the drop you saw, so it looks like the link is 40% loaded and the loss is "expected." That is the trap: 800 kbit/s is payload only, and it ignores everything ITM wraps around the payload.
What actually goes on the wire
An ITM stimulus packet carries at most 4 data bytes, each packet preceded by a 1-byte header (bit 7 = 0, bits 6:5 = size, bits 4:0 = port). An 80-byte line is therefore 20 packets, and each packet also carries a timestamp packet of 1–5 bytes when global timestamps are on. SWO is NRZ, so a 2 MHz SWO clock is a 2 Mbit/s bit rate.
| Layer | Bytes/line | Bits (8N1) | Rate at 1 kHz |
|---|---|---|---|
| Payload only | 80 | 800 | 800 kbit/s |
| + 20 stimulus headers | 100 | 1000 | 1.0 Mbit/s |
| + 1-byte timestamps | 120 | 1200 | 1.2 Mbit/s |
| + 5-byte timestamps (worst case) | 200 | 2000 | 2.0 Mbit/s |
So the encoded rate is 1.0–1.2 Mbit/s in the common case (50–60% of the link, not 40%) and reaches 2.0 Mbit/s, i.e. 100% of the link, when timestamp deltas are large. At 100% you drop lines; that is the number the 800 kbit/s figure hid.
Why the average rate alone doesn't explain the drop
A 1.2 Mbit/s average does not by itself saturate a 2 Mbit/s link. The drop is also a burst/FIFO effect: the CPU enqueues a line in microseconds while the SWO link drains it over roughly a millisecond, and the ITM FIFO is small. Back-to-back lines from several ports overflow it and the overflow flag latches. So the rate to compute is the encoded rate; the quantity to measure is the overflow flag over a fixed window.
What to do
- Compute the encoded rate, not the payload rate: bytes/line × 10 bits × lines/s, counting headers and timestamps.
- Turn timestamps off if you don't need them, or raise the timestamp prescaler so deltas stay in the 1-byte range.
- Cut the number of stimulus ports; use DWT watchpoints for PC/data instead of printf.
- If you need the bandwidth, emit shorter binary records or lower the line rate.
SWO MHz is not printf bandwidth.
What interviewers look for
- Do you spot that the 40% coincidence is a red herring, rather than accepting it as proof the link is 40% loaded?
- Do you know the ITM packet format (4-byte max payload, 1-byte header, separate timestamp packets) and that UART framing adds 2 bits per byte?
- Do you separate average rate from burst behaviour, and name the FIFO as the mechanism rather than blaming the probe?
- Do you name a measurable signal (ITM overflow flag, TPIU byte counter) instead of "add more logging"?
Weak-answer patterns
- "2 MHz is 2 Mbit/s, 800 kbit/s is 40%, so the drop is expected": accepts the coincidence and stops.
- Quoting 800 kbit/s as the wire rate, or forgetting the 10/8 framing factor entirely.
- Blaming the debug probe or the IDE without naming the FIFO or the overflow flag.
- "Reduce printf frequency" with no statement of what to count or how to verify the fix.
Follow-up questions
- What is the ITM FIFO depth, and what happens to a write when it is full?
- How do you size the timestamp prescaler so deltas stay inside one byte?
- What does the ITM overflow flag tell you that a byte counter does not?
- When would you abandon SWO for DWT watchpoints or a RAM buffer drained by DMA?
Curated: · Written: · Reviewed:
Q&A-74SEGGER_RTT_Write blocks for 40 ms. There is no debugger. Your 50 µs control loop is dead. What config did you ship?
Core answer
The config I shipped was wrong. Assumptions: the 50 µs loop is a hard real-time control loop (20 kHz), the RTT up-buffer is the default 1 KB, and production runs with no J-Link attached.
Two changes fix it:
SEGGER_RTT_MODE_DEFAULTset toSEGGER_RTT_MODE_NO_BLOCK_SKIPinSEGGER_RTT_Conf.h.- RTT calls compiled out of the control path entirely in production.
The stock SEGGER_RTT_Conf.h already defaults to NO_BLOCK_SKIP, so a 40 ms block means someone set BLOCK_IF_FIFO_FULL: that is the line to find.
Why it blocks
RTT is a target-side ring buffer. SEGGER_RTT_Write copies into the up-buffer; the J-Link drains it over SWD in the background. No host means nothing drains, so the buffer fills. In BLOCK_IF_FIFO_FULL, SEGGER_RTT_Write spins waiting for free space. With no host, that spin has no bound from the host side; in the trace it lasted 40 ms before the write returned. 40 ms / 50 µs = 800 control periods gone.
The three modes
| Mode | Behaviour when buffer full | Cost |
|---|---|---|
NO_BLOCK_SKIP | returns immediately, drops the write | 0 wait, data lost |
NO_BLOCK_TRIM | writes what fits, drops the rest | 0 wait, partial data |
BLOCK_IF_FIFO_FULL | spins until space appears | unbounded wait |
For a control loop, NO_BLOCK_SKIP is the only safe choice. NO_BLOCK_TRIM is fine for a low-rate log where a truncated line still carries information.
Config
/* SEGGER_RTT_Conf.h */
#define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP
And keep RTT off the 50 µs path:
/* control ISR, 20 kHz — no RTT here */
void control_isr(void) { /* ... */ }
/* 1 kHz task — RTT is fine here */
void log_task(void) {
#if ENABLE_RTT
SEGGER_RTT_Write(0, line, len); /* NO_BLOCK_SKIP: never waits */
#endif
}
Failure modes
- Silent drops:
NO_BLOCK_SKIPloses data with no signal.SEGGER_RTT_Writereturns the number of bytes written; fewer than requested means a drop. Count it, or checkSEGGER_RTT_GetAvailWriteSpace(0)before writing. - Host attached but slow: even with a host, a burst larger than the 1 KB buffer in one iteration fills it. Keep writes small and infrequent.
- Blocking in an ISR:
BLOCK_IF_FIFO_FULLfrom interrupt context can stall the whole system, not just the loop.
How I would verify
Unplug SWD, run the 50 µs loop, and scope a GPIO toggled at the top of the loop. The period must stay 50 µs. Then confirm the production binary has no RTT symbols via the map file or nm.
Curated: · Written: · Reviewed:
Q&A-75You set a data watchpoint on the DMA RX byte. The overrun disappears. Why?
Assumptions. STM32-class MCU; USART RX driven by DMA into a circular buffer; overrun surfaced as the ORE flag; the watchpoint is a DWT data watchpoint on the RX data register with halt-on-match, debugger attached over SWD.
Answer. The watchpoint doesn't fix the overrun: it removes the evidence. Halting the core on the first RX byte hides the bug two ways:
-
The probe's read drains the byte. To display the watched value, the debugger reads the RX data register. That read pulls the received byte out of RDR. Overrun is set precisely when a new byte arrives before the previous one is read; draining the byte removes that condition. On parts where ORE is cleared by the ISR-then-DR read sequence, the probe's read also clears the flag itself. Either way, the thing you were measuring is changed by the act of measuring it.
-
The halt changes bus timing. If the overrun came from CPU/DMA bus contention: the CPU holding the bus or sitting in a long critical section while the DMA waits to read RDR: a halted CPU stops competing, the DMA gets the bus, and it services RX in time. The overrun never forms.
The check that separates them. Freeze the DMA on halt (DBGMCU freeze bits) and repeat. If overrun now gets worse, bytes pile up in RDR while both core and DMA are stopped, the DMA was frozen and the halt is starving the consumer. If overrun still vanishes, the probe's read is what's clearing it. That single experiment tells you which mechanism you're looking at.
What to do instead. Never halt on the RX path. Use a non-halting DWT trigger routed to ITM, or toggle a GPIO in the DMA error/overrun ISR and watch it on a logic analyzer. Reproduce at full speed.
Trace. 10-second window, 115200 baud (≈11.5 kB/s), DMA circular RX:
| Setup | Core | DMA | ORE | Counted overruns |
|---|---|---|---|---|
| halt-on-match on RX DR | halted at first byte | running | cleared by probe read | 0 |
| halt-on-match, DMA frozen | halted | frozen | sets immediately | >100 (worse) |
| GPIO in error ISR | full speed | full speed | set on real overrun | 40 |
The 40/s figure is the real defect; the 0/s is the probe. Reproduce with watchpoints off and a GPIO-only count before you call it fixed.
Curated: · Written: · Reviewed:
Q&A-72The race vanishes when you halt. You conclude there is no race. What trace did you skip?
The trace you skipped is the one taken while the core is still running: an instruction trace (ETM on Cortex-M7, or ITM plus the DWT cycle counter, or a GPIO toggled at the store site). Halt-mode debug (breakpoints, single-step, halt-and-inspect) stops the core clock, and with it the timers, the DMA engine, and in halt-mode multicore debug the other core. A race whose window is created by time cannot occur while time is stopped. "No race under halt" is a claim about your debugger, not about the silicon.
Why halt hides it. On Cortex-M7 the store buffer lets a store retire out of order with respect to the bus, so a flag store can become visible to another master before the payload stores have drained. Halting drains that buffer and serializes the pipeline, so the flag-then-payload order you see on the halt LED is the order the debugger forced, not the order the hardware produces at speed. The same applies to a race that needs a timer tick or a DMA completion to interleave: stop the clock and the interleaving never happens.
What to capture instead. ETM gives full instruction trace out through the TPIU trace port; on Cortex-M7 that needs a trace port (1, 2 or 4 bits wide) and enough bandwidth at 80 MHz. ITM with the DWT cycle counter is cheaper: you instrument the flag store and the payload stores and get cycle-stamped ordering, but it only shows the points you instrumented. Four GPIOs toggled around the store cost nothing and resolve to a core cycle or two (12.5 ns at 80 MHz), but they add edge jitter and cover only four signals. Choose based on whether you need the whole pipeline or just the ordering at one site.
Failure mode I have seen: a mailbox torn at 2.1% under a 1 kHz producer. Halt-and-single-step showed the flag store always ordered before the payload. We shipped. At 1 kHz that is 600,000 messages in 10 minutes, and 2.1% of them is 12,600 torn reads.
| Method | Clock during capture | Observed tear rate |
|---|---|---|
| Halt / single-step | stopped | 0% |
| Full-speed run, 1 kHz mailbox | 80 MHz | 2.1% |
| ETM trace at full speed | 80 MHz | ordering visible |
Detection and the bar for "settled": capture ETM around the flag store and require that the payload stores are visible before the flag store in the trace, with zero tears across 600,000 messages. Anything less is a measurement of the debugger.
Trade-off: ETM costs pins and trace bandwidth and needs a trace-capable probe; ITM costs code instrumentation and only sees what you instrument; GPIO costs board pins and adds edge jitter. Halt costs nothing and tells you nothing about timing.
Curated: · Written: · Reviewed:
Q&A-31SCL and SDA use 4.7 kΩ to 3.3 V. Cbus is 200 pF. Fast-mode 400 kHz NACKs. What do you change first?
The first 60 seconds
The pull-ups are the problem, and they are the first thing I change. 4.7 kΩ into 200 pF is tau = 940 ns; the Fast-mode 30–70% rise time that falls out of it is 0.847·tau ≈ 796 ns against a 300 ns limit. I swap both resistors to 1.5 kΩ (t_r ≈ 254 ns), re-scope, and leave the driver alone. The edge is analog; no firmware change moves it.
Assumptions I state up front: Cbus = 200 pF is the total, including device pins and trace; VDD = 3.3 V; the master is running Fast-mode at 400 kHz; the NACKs are on the bus rather than one slave's address.
Why the arithmetic settles it
I2C rise time is an RC charge, not a baud rate. UM10204 defines Fast-mode t_r from 0.3·VDD to 0.7·VDD, max 300 ns. For a step into an RC load:
t_r(30–70%) = tau · ln(0.7/0.3) = 0.847·tau
| Rp | tau = RC | t_r = 0.847·tau | vs 300 ns | IOL at VOL = 0.4 V |
|---|---|---|---|---|
| 4.7 kΩ | 940 ns | 796 ns | fail, 2.7× | 0.62 mA |
| 2.2 kΩ | 440 ns | 373 ns | fail | 1.32 mA |
| 1.5 kΩ | 300 ns | 254 ns | pass | 1.93 mA |
| 1.0 kΩ | 200 ns | 169 ns | pass | 2.90 mA |
The largest resistor that passes is R_max = 300 ns / (0.847 · 200 pF) = 1.77 kΩ. I pick 1.5 kΩ rather than 1.0 kΩ to keep IOL margin: Fast-mode caps IOL at 3 mA, and 1.0 kΩ draws (3.3 − 0.4)/1000 = 2.9 mA, right on the limit. If the slave's VOL climbs past 0.4 V the bus fails a different way.
What the slow edge does to the transaction
At 400 kHz the bit period is 2.5 µs. A master running a 50% duty cycle holds SCL high for 1.25 µs (the spec minimum is 0.6 µs). With tau = 940 ns the line reaches 1 − e^(−1250/940) = 0.735·VDD by the end of that window, crossing VIH = 0.7·VDD at 1.13 µs: about 120 ns of margin. A slave sampling late in the high period sees a marginal clock and drops the ACK. That is why the failure is rate-dependent: at 100 kHz the standard-mode limit is 1000 ns and the same 796 ns edge passes.
Worked example (bench figures, not spec): 4.7 kΩ, 200 pF, 400 kHz, ~18% NACK rate on a bus that ACKs cleanly at 100 kHz. Swapping to 1.5 kΩ dropped t_r to ~250 ns and the NACKs to zero.
What I check after the swap
- Scope t_r on SCL and SDA, 30–70%, and require ≤ 300 ns.
- Confirm Cbus. If it is above 200 pF, recompute: the fix scales with C.
- Hold the line low and measure VOL; if it exceeds 0.4 V, back off to 2.2 kΩ and cut capacitance instead.
Alternatives, and when not to lower R
- Cut Cbus. For 4.7 kΩ to pass you need C ≤ 300 ns / (0.847 · 4.7 kΩ) ≈ 75 pF: shorter traces, no stubs, fewer devices. Usually not achievable.
- Drop to 100 kHz standard mode. t_r max is 1000 ns, so 796 ns passes; the cost is 4× throughput.
- Active pull-up or rise-time accelerator (PCA9600, LTC4311) when Cbus is large enough that R cannot go low without breaking IOL. Adds a part and its own failure mode.
Failure modes to watch
- R too low: IOL/VOL violation, the low level never reaches 0.4 V, and you get NACKs that look identical to the slow-edge ones. Detect by scoping VOL while a device holds the line low.
- Series protection resistors in SDA/SCL add to the effective pull-up and re-break the budget.
- Higher current through the pull-ups means more EMI and more contention current if two devices drive.
Curated: · Written: · Reviewed:
Q&A-36The sensor is 10-bit address 0x2A5. Your scanner finds nothing at 0x55. Where is the device?
The device is 10-bit address 0x2A5. It was never at 0x55, and no 7-bit scan moves it there. If anything, a 7-bit scanner surfaces it at 0x7A: the first header byte for this part is 0xF4, and 0x7A << 1 = 0xF4, which lands in the reserved 0x78-0x7F block most tools either skip or flag as a bus fault. So the honest reading of "nothing at 0x55" is "you probed the wrong address," not "the part is absent."
Why 0x55 is a dead end
0x2A5 >> 3 = 0x54, and nothing links 0x55 to 0x2A5. Probing 0x55 with a 7-bit scanner puts 0x55 << 1 = 0xAA on the wire as the address byte. A 10-bit slave ACKs only when the first byte's top five bits are 11110 and A9 A8 match; 0xAA = 1010 1010 fails on the first condition.
The byte sequence
The header is 1111 0 A9 A8 R/W, followed by A7..A0. Here 0x2A5 = 0b10 1010 0101, so A9 A8 = 10 and the low byte is 0xA5.
- hi = 0x2A5 >> 8 = 0b10
- first byte, write = 0xF0 | (hi << 1) | 0 = 0xF4
- first byte, read = 0xF0 | (hi << 1) | 1 = 0xF5
- second byte = 0x2A5 & 0xFF = 0xA5
| Transaction | Bytes on the wire | Result |
|---|---|---|
| 7-bit probe 0x55 | 0xAA | NACK |
| 7-bit probe 0x7A | 0xF4 | ACK on the header byte, then stop |
| 10-bit write 0x2A5 | 0xF4 0xA5 | ACK, ACK |
| 10-bit read 0x2A5 | 0xF4 0xA5 Sr 0xF5 | ACK, ACK, ACK, then data |
The read needs the write-direction address first (0xF4 0xA5) and then a repeated start before the read header 0xF5. A stop in between ends the transaction and you start over; the 10-bit read header alone, 0xF5, is not a complete address.
What a 7-bit scan can and cannot tell you
An ACK at 0x7A proves only that some 10-bit device with A9 A8 = 10 is on the bus. It cannot separate two parts in that range, and it hands you no read sequence. The only confirmation that this is 0x2A5 is a two-byte write with ACK on both 0xF4 and 0xA5, plus a read that returns expected data.
Failure mode to watch
A scanner that probes 0x7A and then issues a stop sees the header ACK but never confirms the low byte, so it may report a phantom device or flag the reserved 1111xxx address as a bus fault; both get misread as "no device." Declaring the part DNM off a 7-bit NACK at 0x55 loses the distinction between "not at that address" and "not on the bus."
Curated: · Written: · Reviewed:
Q&A-32A sensor stretches SCL for 900 µs. Your MCU timeout is 100 µs. Who hangs?
The master aborts; the bus hangs; the sensor is fine.
At 100 µs the MCU's SCL timeout fires 800 µs before the sensor releases SCL. The sensor is mid-conversion, doing exactly what the I2C-bus specification (NXP UM10204) permits: I2C puts no upper bound on clock stretching. The master is the one that gives up, and it gives up at the worst moment: while SCL is still held low it cannot generate a STOP, because STOP is SDA rising while SCL is high, and SCL is not high. The transfer is abandoned mid-byte.
t=0 master releases SCL after the ACK bit; sensor pulls SCL low, stretch starts
t=100µs master SCL timeout fires; driver aborts, returns a timeout error
t=100µs master tries STOP -> needs SCL high -> blocked by the sensor
t=900µs sensor finishes conversion, releases SCL
t=900µs SCL rises; sensor waits for the master to clock the rest of the byte
if the aborted bit was 0, the sensor is still holding SDA low
t>900µs SDA low, SCL high: not a legal idle bus, no master can issue START
recovery: clock SCL up to 9 times until SDA releases, then STOP
900 µs is 9× the 100 µs timeout, and 360 SCL periods at 400 kHz. A 20% margin puts the timeout at 1.08 ms. If the aborted bit happened to be a 1, SDA is released and the bus looks idle: the next START resynchronises the slave, so that case self-heals; the SDA-low case does not.
Options, and when each is wrong
| Option | Cost | When not to |
|---|---|---|
| Raise the master timeout above worst-case stretch + margin | A genuinely dead slave holds the bus for the full timeout | When that timeout is also your only stuck-bus detector, or the bus must be SMBus-compliant: SMBus 3.x caps the timeout at 25–35 ms |
| Disable the peripheral timeout, rely on a watchdog or hardware bus-timeout | Master waits indefinitely on a dead slave | When nothing else resets the bus |
| Put the stretching sensor on its own I2C bus | Extra pins and a peripheral | When pin count is fixed |
| Reject the sensor | Lose the part | When the stretch is bounded and inside budget: 900 µs is well inside SMBus's 25 ms |
A hardware I2C peripheral waits out a stretch without consuming CPU, so a generous timeout costs nothing on a healthy bus. A bit-banged master polling SCL burns CPU for the whole stretch: 900 µs per sample at 200 Hz is 18% of one core, which is the real reason to move to a peripheral rather than to shorten the timeout.
Failure modes and how to catch them
- Intermittent aborts that only show at temperature extremes. ADC conversion time grows with temperature on many parts, so a stretch that is 900 µs at 25 °C can exceed a timeout tuned at room. Detect by scoping SCL low time across the rated temperature range, not just on the bench.
- Slave never releases SCL (brown-out, dead part). With the timeout disabled the master hangs forever. Detect with a watchdog or a hardware bus-timeout that resets the peripheral.
- Bus stuck with SDA low. The next transaction returns BUSY or arbitration-lost. Detect with a recovery routine that pulses SCL up to 9 times and verifies SDA is released before issuing STOP.
What I'd ship: timeout ≥ 1.08 ms, a separate stuck-bus recovery path triggered when a transaction exceeds it, and SCL-low-time measurements over the temperature range as the bring-up gate.
Curated: · Written: · Reviewed:
Q&A-39The slave NACKs when busy. You retry immediately in a 2 µs loop. The bus never recovers. What backoff did you skip?
The backoff you skipped is the slave's busy time. On I2C a NACK is a legal answer, not a fault: it means "not now." A slave that NACKs while it is mid-conversion or mid-EEPROM-write is telling you it cannot accept a byte yet, and the correct response is to issue a STOP, wait at least the datasheet busy time (t_BUSY: 1.5 ms for a typical ADC conversion, 5 ms for an EEPROM page write), then try once more. Retrying every 2 µs does not shorten that window, because the slave's internal timer runs independently of anything on the bus.
Why the tight loop makes it worse
Each retry is a fresh START plus address phase. The slave sees that traffic while it is still busy, NACKs again, and, critically, the master never issues a STOP, so the bus is never released. If the slave is holding SDA low to signal busy, the master's next START cannot even be generated, and the loop spins on a bus it has wedged.
The 2 µs figure is also misleading. At 400 kHz one bit is 2.5 µs, so a minimal failed transaction (START, address+R/W, NACK, STOP) is about 20 bit times, roughly 50 µs. The bus, not your delay, sets the retry period: about 30 attempts inside a 1.5 ms busy window, every one of them wasted.
The fix
/* C99, Linux i2c-dev userspace. t_BUSY from the slave datasheet. */
#define T_BUSY_US 1500
#define MAX_TRIES 3
int write_reg(int fd, uint8_t addr, uint8_t reg, uint8_t val) {
for (int i = 0; i < MAX_TRIES; i++) {
if (i2c_write(fd, addr, reg, val) == 0)
return 0; /* ACKed */
if (errno != ENXIO && errno != EREMOTEIO)
return -1; /* real fault, not a busy NACK */
usleep(T_BUSY_US); /* the backoff that was skipped */
}
bus_recover(fd); /* clock SDA free, then STOP */
return -1;
}
bus_recover drives up to 9 SCL pulses with SDA released, then issues a STOP: the only way out when a slave has left SDA low.
| Policy | Attempts in 1.5 ms | Outcome |
|---|---|---|
| Retry every 2 µs | ~30 (bus-limited) | Slave still busy; 0 ACKs |
| STOP, wait t_BUSY, one retry | 1 | ACK on the first try after 1.5 ms |
Failure modes to watch
- Stuck SDA. The slave holds SDA low; the master's START never completes and the loop spins forever. Detect it by reading the SDA line state before a START: low with no transaction in flight means run recovery.
- Ignored clock stretching. If the master does not honor SCL held low, it can fire a START mid-stretch. Detect with a scope on SCL.
- Busy NACK mistaken for an absent device. Both look identical at the master. Count retries per address: a device that never ACKs after t_BUSY is absent, not busy, and retrying it forever is pure bus waste.
Trade-off
Waiting t_BUSY costs latency, and for a 5 ms EEPROM write a bounded poll (100 µs, doubling, capped at the datasheet maximum) is fine. But the datasheet busy time is the floor: polling faster than that only burns bus time and risks wedging the line.
Curated: · Written: · Reviewed:
Q&A-25The ALERT pin stays low until you read the I2C chip. You configured falling-edge EXTI. You miss the next alert. Why?
Why. EXTI latches transitions, not levels. Your ALERT is level-held: it stays low until you read the chip's status register. The second event produces no falling edge, because the line never went high in between. You service one event, the status read clears both, and the second is gone. Falling-edge EXTI on a level-held line is the bug. A held low is not a second falling edge.
Mechanism. The EXTI block sets the line's pending bit (EXTI->PR) on the high-to-low transition; the NVIC pending bit is set from it and the ISR runs. Once you are inside the handler the line is low and stays low, so nothing else can set PR until the line rises and falls again. If the sensor re-asserts while the line is already low, the event exists only in the sensor's status register, and your single read clears it along with the first.
There is a second, subtler loss, and it depends on when you clear PR. HAL_GPIO_EXTI_IRQHandler clears the line's PR bit at the top of the handler, before the callback. An edge that arrives during the callback sets PR again and re-pends the NVIC, so the ISR re-enters: that one survives. If you clear PR at the end of the handler instead, you wipe any edge that arrived while you were working. Both orderings are common; only one is safe.
What to do. Never do I2C or printf in the ISR. Wake a task, and have the task drain the source and re-check the pin level before it sleeps:
/* STM32 HAL + FreeRTOS. ALERT: active-low, open-drain, 4.7k pull-up. */
/* ISR: no I2C, no printf. Wake the task and get out. */
void HAL_GPIO_EXTI_Callback(uint16_t pin)
{
BaseType_t woken = pdFALSE;
if (pin == ALERT_PIN) {
xSemaphoreGiveFromISR(alert_sem, &woken);
portYIELD_FROM_ISR(woken);
}
}
/* Task: drain the source, then re-check the level before sleeping. */
void alert_task(void *arg)
{
for (;;) {
xSemaphoreTake(alert_sem, portMAX_DELAY);
do {
imu_read_status(&st); /* clears the alert source, ~150 us */
handle(&st);
} while (HAL_GPIO_ReadPin(ALERT_PORT, ALERT_PIN) == GPIO_PIN_RESET);
}
}
The do/while re-checks the level, so an event that arrived while the line was held low is caught by the next status read. There is no lost wakeup: if a new edge lands between the pin going high and the task blocking on the semaphore, the give is already pending and the task takes it immediately.
Trade-offs. STM32's EXTI block is edge-only: there is no level mode to switch to. Parts with a level-capable pin interrupt (or a GIC SPI wired to the pin) can use level mode, but then you must clear the source before returning or you re-enter forever. Polling the pin at 1 kHz while it is low is a fallback, at the cost of up to 1 ms of added latency.
Failure modes and how to see them. (1) No edge while held low: the event is invisible to EXTI. (2) A late PR clear wipes an edge that arrived during the handler. (3) Blocking I2C and printf in the ISR stall every other interrupt. Detect all three the same way: scope ALERT against a GPIO you toggle at ISR entry and require one entry per low interval, and compare the sensor's own event or FIFO count against what you consumed.
Bench repro (STM32F4 @ 168 MHz, IMU with active-low open-drain ALERT, 4.7 kΩ pull-up):
| t | Event |
|---|---|
| 0 | Event A: ALERT falls, EXTI ISR entry |
| 0–3.8 ms | printf in the ISR (3.8 ms): ALERT still low, source not yet cleared |
| 200 µs | Event B: sensor re-asserts. Line already low → no edge, nothing latched |
| 3.8–3.95 ms | I2C read of 6 status bytes at 400 kHz (~150 µs) clears A and B together |
| 3.95 ms | Handler returns, ALERT releases |
Two events, one ISR entry, one sample consumed. The IMU ran unserviced for 200 ms, which at that integration rate is 12° of angle error. The fix is the drain-and-recheck loop above, not a wider edge filter.
Curated: · Written: · Reviewed:
Q&A-33You set CPHA=0 because "mode 0 is default." The flash samples on the trailing edge. What do you capture?
What you capture: every bit one edge late. With CPHA=0 the master samples on the leading edge. A flash that samples on the trailing edge is a CPHA=1 part, and CPHA=1 parts launch data on the leading edge. So the flash drives each new bit on the same edge the master latches it, and the master latches the level that was on MISO before the flash updated it: the previous bit. The received stream is the true stream delayed by one bit: the MSB of each captured byte is the LSB of the true previous byte, and the very first captured bit is whatever MISO held before the flash launched (indeterminate. Pull-up level or the last driven bit).
Mechanism, edge by edge. Label leading edges L1..L8. A CPHA=1 slave launches b7 on L1, b6 on L2, … b0 on L8, and samples on the trailing edges. A CPHA=0 master samples on L1..L8. At L1 the flash is just now driving b7, so the master captures the pre-edge level (stale). At L2 the line has held b7 since L1, so the master captures b7. At L3 it captures b6, and so on. The master's byte is [stale, b7, b6, b5, b4, b3, b2, b1]; b0 lands in the next byte's MSB.
Trace: JEDEC ID read (0x9F) from a part whose true ID is 0xEF 0x40 0x16.
| Edge | Flash drives (CPHA=1) | Master samples (CPHA=0) |
|---|---|---|
| L1 | b7 = 1 | stale |
| L2 | b6 = 1 | b7 = 1 |
| L3 | b5 = 1 | b6 = 1 |
| L4 | b4 = 0 | b5 = 1 |
| L5 | b3 = 1 | b4 = 0 |
| L6 | b2 = 1 | b3 = 1 |
| L7 | b1 = 1 | b2 = 1 |
| L8 | b0 = 1 | b1 = 1 |
| L9 (next byte) | next b7 | b0 = 1 |
Captured byte 1 = stale 1 1 1 0 1 1 1. Carrying the shift across byte boundaries: 0xEF's LSB (1) becomes the MSB of the second captured byte, and 0x40's LSB (0) becomes the MSB of the third. So the master reads 0x77 0xA0 0x0B if the stale bit is 0, or 0xF7 0xA0 0x0B if it is 1: against a true ID of 0xEF 0x40 0x16. It is not a byte shift; it is a bit shift that smears across byte boundaries.
Resolving a mode conflict: three options, one ground truth.
- Datasheet timing diagram (authoritative). The sample edge is the one with the setup/hold window drawn around it. That decides CPHA; CPOL is a separate axis (idle high vs low). Read it, don't guess.
- Scope (confirms). Probe SCLK and MISO, trigger on the 0x9F command, and check which SCLK edge MISO is stable across. This is evidence, not a decision procedure.
- Trial (last resort). Try the four modes and see which returns a sane ID, but a shifted stream still looks like data, so validate against the datasheet's expected JEDEC ID, never against "did I get three bytes."
Set the mode explicitly in the driver (spidev SPI_MODE_3, or device-tree spi-cpha/spi-cpol). "Mode 0 is default" is a Linux spidev habit, not a device fact.
Failure modes and detection. A one-bit shift produces a stream that parses as data, so a green LED or a non-empty buffer proves nothing. Page reads fail CRC 100% because every byte is wrong. The first byte's MSB is indeterminate, so occasionally the garbage looks plausible. Detect it by comparing the JEDEC ID to the datasheet's expected value and by scoping the sample edge: a shifted ID is not an ID.
Curated: · Written: · Reviewed:
Q&A-37You issue 0x3B dual-output read with 8 dummy clocks. The flash wants 4. The payload is shifted. Who is right?
I pin SPI dummy clocks for a dual-output flash read to a scope channel or a current shunt before I trust any LED or printf about it.
I treat dummy clocks as part of the command, in SCLK edges, not as a delay in microseconds. Wrong dummy count bit-shifts the entire payload.
Concretely, i take dummy cycles from the command table at that frequency and dummy-cycle register, I count SCLK edges on a scope, and I CRC a known page.
The reason for that specificity is a failure I have seen: Command 0x3B at 48 MHz wanted 4 dummy clocks. I ran 8, four extra. Dual I/O moves 2 bits per clock, so 4 extra clocks shifted 8 bits, not 4. 256-byte page CRC failed 100 percent. DMA TC LED still fired after 256+overhead bytes. I called the flash "bad silicon."
0x3B dual-output dummy mismatch at 48 MHz.
| Dummy clocks | Dual-I/O shift | 256-byte CRC |
|---|---|---|
| 4 (wanted) | 0 bits | pass |
| 8 (used), 4 extra | 4 clocks × 2 bits = 8 bits | 100% fail |
| DMA TC | fired | — |
I would not consider it settled without evidence: I would count SCLK edges between command and first MISO nibble and require 4, then CRC page 0 against a programmer dump.
Dummy clocks are edges, not a sleep.
Curated: · Written: · Reviewed:
Q&A-35You need 9-bit addressing. You set M=1 then write 8-bit bytes. Slaves never wake. What bit did you not set?
The bit you didn't set is bit 8: the ninth bit, the address mark.
With M=1 the USART data register is nine bits wide, not eight. An 8-bit write to DR fills bits 0-7 and leaves bit 8 at 0. Bit 8 = 0 means "data frame"; bit 8 = 1 means "address frame". So every byte you sent was a data frame, and a slave sitting in mute mode (RWU=1) waiting for an address mark never saw one. It stayed muted.
The fix is to write the address byte as a 9-bit value with bit 8 set. For address 0x42 that's 0x142.
// STM32 HAL, USART1 configured with WordLength = UART_WORDLENGTH_9B (M=1)
uint16_t addr = 0x142; // bit 8 = 1 -> address mark, address 0x42
uint16_t data = 0x042; // bit 8 = 0 -> data
HAL_UART_Transmit(&huart1, (uint8_t *)&addr, 1, 10);
HAL_UART_Transmit(&huart1, (uint8_t *)&data, 1, 10);
With 9-bit word length HAL treats the buffer as uint16_t and Size as the number of 9-bit words, so the cast and the 1 are correct.
Trace of the two writes, LSB first, 9-bit frame:
| Write | DR value | bit 8 | Frame on the wire | Slave sees |
|---|---|---|---|---|
| 0x42 (8-bit) | 0b0_0100_0010 | 0 | start 0 1 0 0 0 0 1 0 0 stop | data, stays muted |
| 0x142 | 0b1_0100_0010 | 1 | start 0 1 0 0 0 0 1 0 1 stop | address mark, RWU clears |
That's the whole bug: one bit, set in software, carried in the frame.
Alternatives, and when each is right:
| Scheme | Where the flag lives | Trade-off |
|---|---|---|
| 9-bit mark (M=1) | bit 8 of every frame | classic multiprocessor mode; buffers and DMA must be 16-bit, and every slave must be configured for 9 bits |
| Parity bit as mark (M=0, parity on) | parity bit repurposed as address/data | works on 8-bit-only UARTs, but you give up parity error detection and the receiver must expose the parity bit |
| Hardware address match | peripheral compares against a programmed address register and clears RWU itself | no software in the wake path, but only on parts that have it, and it's per-USART |
Failure modes and how to catch them:
- 8-bit write with M=1: MSB 0, all frames data, slaves never wake. Detect by decoding 9-bit frames on a logic analyzer and asserting bit 8 = 1 on the address frame only.
- DMA with 9-bit: if the memory buffer is uint8_t, the DMA moves 8 bits per transfer and drops bit 8. Use uint16_t buffers.
- Slave side: if WAKE is set for idle-line detection instead of address mark, the slave wakes on line idle, not on the mark. A different bug with the same symptom.
Confirm the fix end to end: address frame with bit 8 = 1, then a slave GPIO toggle within two byte times.
Curated: · Written: · Reviewed:
Q&A-34APB is 16 MHz. You want 115,200 16× oversample. What BRR do you program, and do you ship the error?
For UART baud divisor error at 16 MHz I want a number I can recompute from a capture, not a story about a board that seemed alive.
I treat baud error as (actual-wanted)/wanted, and I refuse over about 2 percent with a typical 2 percent crystal and a 2 percent peer. I program STM32 BRR as mantissa plus fraction, not as round(f/(16×baud)) to 9.
Concretely, i compute USARTDIV=f/(16×baud)=8.6806, I pack BRR=0x008B (8 + 11/16), I recompute actual baud, and I pick 8× oversample or a PLL multiple when 16× cannot hit.
The reason for that specificity is a failure I have seen: 16e6/(16×115200)=8.6806. Treating USARTDIV as the integer 9 gives 16e6/(16×9)=111,111 baud (−3.55 percent) and I would not ship that. Packed BRR 0x008B is USARTDIV=8+11/16=8.6875, actual=16e6/139=115,108, error=(115108-115200)/115200=−0.08 percent, which I would ship. At 9,600, USARTDIV=104.1667, BRR=0x0683 (104+3/16), actual=16e6/1667≈9,598, error=−0.02 percent.
16 MHz APB, 16× oversample.
| Wanted | BRR | Actual | Error |
|---|---|---|---|
| 9,600 | 0x0683 (104+3/16) | 16e6/1667≈9,598 | −0.02% |
| 115,200 as integer 9 | mantissa 9, 16e6/(16×9) | 111,111 | −3.55%, do not ship |
| 115,200 packed | 0x008B (8+11/16) | 16e6/139=115,108 | −0.08%, ship |
I would not consider it settled without evidence: I would measure bit time on a scope (wanted 8.68 µs, got 8.687 µs at 115,108 baud) and a BER test of 100,000 bytes against a GPSDO UART.
Rounded integer BRR is not the STM32 fraction field.
Curated: · Written: · Reviewed:
Q&A-101You have an MCU with 12 free pins: a 6-axis IMU sampled at 1 kHz, a 256-Kbit EEPROM, a GPS module streaming NMEA at 9,600 baud, and a debug console. Which bus for each, and what breaks if you pick wrong?
Assign by what the device speaks, then by rate and pin cost
The GPS is UART-only and the console is UART (or SWO), so those two are decided by the device, not by you. That leaves the IMU and the EEPROM on the 12-pin budget, and the deciding numbers are rate and bus sharing.
| Device | Bus | Pins | Rate needed | Deciding reason |
|---|---|---|---|---|
| 6-axis IMU @ 1 kHz | SPI | 4 (SCK, MISO, MOSI, CS) | 14 B × 1 kHz = 14 kB/s | 8 MHz SPI is 1 MB/s; I2C would share with EEPROM |
| 256-Kbit EEPROM | I2C | 2 shared | < 1 kB/s | multi-drop, 2 pins, slow is fine |
| GPS NMEA @ 9,600 | UART | 2 | ~800 B/s | module is UART-only |
| Debug console | UART or SWO | 2 or 1 | ~1 kB/s | debug only |
Total: 4 + 2 + 2 + 2 = 10 pins, inside 12.
Why the IMU is SPI and not I2C
The IMU at 1 kHz needs 14 kB/s. I2C fast mode is 400 kHz, and after start/address/ACK overhead you get roughly 40 kB/s of payload: 35% duty just for the IMU. Add the EEPROM on the same bus and a 5 ms page write blocks every IMU read for five sample periods. You miss samples, and the failure looks like jitter, not an error. SPI at 8 MHz is 1 MB/s, so the IMU uses ~1.4% of the bus and never waits for the EEPROM.
Clocking and master responsibility
SPI and I2C are synchronous: the master drives the clock, so the slave's timing is your problem only in setup/hold. UART is asynchronous: both ends must agree on baud, and a 2% error at 9,600 is fine but at 115,200 it is marginal. I2C slaves can stretch SCL: a 900 µs stretch against a 100 µs master timeout hangs the bus. SPI has no flow control at all: if the slave is not ready, you need a ready pin or a fixed cadence, or you clock out garbage.
What breaks if you pick wrong
- IMU on I2C shared with EEPROM: 5 ms page writes block 1 kHz reads. Detect with sample-timestamp deltas > 1 ms, or a scope on SCL showing the gap.
- Two devices on one UART: UART is point-to-point. Two push-pull transmitters on one line contend; you see framing errors and possibly damaged pins. RS-485 half-duplex or a mux is the fix, not a second device on the same pair.
- EEPROM on SPI: works, but each SPI device needs its own CS. With 12 pins and four devices, that pin is the one you do not have.
- Long SPI traces at 8 MHz ring; I2C at 400 kHz with 4.7 kΩ pull-ups and 200 pF of bus capacitance is already marginal (rise time ~1 µs vs the 300 ns fast-mode limit).
Curated: · Written: · Reviewed: —
Q&A-103Your low-priority task kicks the IWDG every 500 ms. A higher-priority task occasionally blocks for 900 ms. The board resets in the field. Walk me through the fix and how you'd prove the reset came from the IWDG.
What a strong candidate says first
The reset is real and the watchdog is doing its job: it is telling you the feed point is wrong. Two independent defects: the window is sized against typical latency instead of worst case, and the feed sits where it cannot observe the failure you care about. Fix both, then confirm with RCC_CSR.
Size the window from worst case, not average
IWDG timeout on STM32 is
t = (prescaler × (reload + 1)) / f_LSI
with prescaler in {4, 8, 16, 32, 64, 128, 256} and reload 12-bit. Prescaler 64, reload 2499 gives 64 × 2500 / 32000 = 5.0 s nominal. But LSI is only nominally 32 kHz; the datasheet tolerance over temperature and voltage is wide enough that a nominal 5 s window can be several seconds off. Budget the minimum, not the typical. If your worst-case interval between feeds is 900 ms (a flash erase, a long mutex hold, a burst of 1 ms ticks) a 5 s window leaves 4 s of margin. A 1 s window does not. Either widen the window or chunk the blocking operation so it feeds between chunks. Widening alone is not enough if the blocking operation can grow.
Why feeding from an ISR or timer callback hides the bug
A timer callback or SysTick handler runs at interrupt priority. It preempts every task, including the one that is stuck. So the watchdog keeps getting fed while the control task is dead: you have converted a watchdog into a "did the CPU take any interrupt" detector. It catches a hard lockup with interrupts masked and nothing else. The same applies to feeding from a high-priority task: it runs regardless of whether the low-priority work is progressing.
The pattern that works
Each monitored task sets a bit; a supervisor (lowest priority, so it only runs when everything else has yielded) checks all bits and feeds only if every task checked in since the last feed.
static volatile uint32_t hb;
void control_task(void *a) {
for (;;) { hb |= HB_CTRL; do_step(); } /* 900 ms worst case */
}
void supervisor(void *a) { /* lowest priority */
const uint32_t all = HB_CTRL | HB_COMMS | HB_LOG;
for (;;) {
vTaskDelay(pdMS_TO_TICKS(200));
if ((hb & all) == all) { hb = 0; IWDG->KR = 0xAAAA; }
/* missing bit, or starved supervisor: do not feed */
}
}
A task that hangs stops setting its bit; a task that hogs CPU starves the supervisor. Both stop the feed. Feeding from the idle hook is a weaker version of the same idea: it detects CPU hogging but not a task blocked forever on a semaphore.
Debugging which reset it was
Read RCC_CSR before writing RMVF. On STM32F4:
| Bit | Flag | Source |
|---|---|---|
| 31 | LPWRRSTF | low-power mode |
| 30 | WWDGRSTF | window watchdog |
| 29 | IWDGRSTF | independent watchdog |
| 28 | SFTRSTF | NVIC_SystemReset |
| 27 | PORRSTF | power-on |
| 26 | PINRSTF | NRST pin |
| 25 | BORRSTF | brown-out |
IWDGRSTF set with WWDGRSTF clear points at the IWDG. Log the flags plus a monotonic reset counter in the RTC backup registers: they survive a system reset and are not cleared by the IWDG. Then reproduce: toggle a GPIO at each feed and scope the maximum interval, or read DWT->CYCCNT at feed time and keep the max. If the max interval is under the window and you still reset, the LSI is running faster than nominal or the window is shorter than you computed.
When to use WWDG instead
WWDG is clocked from PCLK1 and has a window: feeding too early also resets. Use it when you want to catch a runaway loop that feeds too often, not just a starved one. IWDG is the one that survives STOP and clock failure; WWDG is not.
Curated: · Written: · Reviewed: —
Q&A-104You enable the IWDG, attach the debugger, halt the core at a breakpoint, and the board resets a few seconds later. Why does the watchdog keep counting while the core is halted, and how do you stop that without disabling the watchdog in production?
The IWDG is clocked from the LSI, not from HCLK and not from the core. Halting the core at a breakpoint stops instruction fetch; it does not gate the LSI or the IWDG prescaler. The counter keeps decrementing, hits zero, and the reset fires. That is the watchdog working as designed: the debugger is the thing that is wrong.
Fix it in the debug configuration, not in the product. STM32F4: DBGMCU->APB1FZ |= DBGMCU_APB1_FZ_DBG_IWDG_STOP; (bit 12). L4/G4: the same bit in DBGMCU_APB1FZR1. H7: DBGMCU_APB1LFZR1. That freezes the IWDG counter while the core is halted. Leave it out of release builds: a frozen watchdog in the field is a dead watchdog.
/* F407, LSI ~32 kHz, /32 prescaler, reload 4095 -> ~16.4 s nominal */
IWDG->KR = 0x5555; /* unlock PR/RLR */
IWDG->PR = 0x03; /* /32 */
IWDG->RLR = 4095;
IWDG->KR = 0xCCCC; /* start */
IWDG->KR = 0xAAAA; /* feed */
#ifdef DEBUG
DBGMCU->APB1FZ |= DBGMCU_APB1_FZ_DBG_IWDG_STOP;
#endif
Timeout arithmetic: t = 4 x 2^PR x (RLR+1) / f_LSI. With PR=3, RLR=4095: 4 x 32 x 4096 / 32000 = 16.384 s. The F4 datasheet gives LSI 17-47 kHz, so the same config is 11.1 s to 30.8 s across parts and temperature. Do not set the timeout to the edge of your worst-case loop; leave margin for that spread.
Feeding strategy is where the real answer is. A free-running IWDG only catches "the feed call stopped being reached." A loop that spins and still calls the feed passes it:
while (1) { IWDG->KR = 0xAAAA; } /* free-running IWDG: never resets */
Windowed IWDG (IWDG_WINR on L4/G4/H7; F4 has no window, use WWDG) resets if you feed before the counter has dropped below WINR. The reset value 0x0FFF disables the window; a smaller value enables it. Set it so a legitimate loop, which spends time doing work, feeds late enough, and a runaway loop that feeds immediately trips:
IWDG->KR = 0x5555;
IWDG->WINR = 0x0800; /* feed only when counter < 0x0800 */
| IWDG | WWDG | |
|---|---|---|
| Clock | LSI ~32 kHz | PCLK |
| Window | WINR on L4/G4/H7 | always |
| Runs in STOP | yes, if LSI kept | no |
| Debug freeze | DBG_IWDG_STOP | DBG_WWDG_STOP |
RTOS angle: if the feeder is a low-priority task and a high-priority task hogs the CPU, the feeder never runs and the IWDG resets. That is the watchdog detecting task starvation: correct behaviour, but you must be able to tell it apart from a real hang. Feeding from a timer ISR masks starvation entirely, because the ISR runs regardless of which task is starved. Pick one deliberately: task-fed for starvation detection, ISR-fed only if you have another way to detect a stuck task.
After reset, read RCC->CSR: IWDGRSTF tells you it was the watchdog, not a power-on or NRST. IWDG reset does not clear the backup domain or .noinit RAM, so a crash record there survives.
Curated: · Written: · Reviewed: —
Q&A-63IWDG timeout is 8 s. You STOP for 30 s on RTC. You reset at 8 s. Which bit did you not set?
The bit is IWDG_STOP: the IWDG freeze bit in DBGMCU (DBGMCU_CR bit 8 on F1, DBGMCU_APB1_FZ bit 12 on F4/L4). And setting it would not have saved you.
That is the bit the question is fishing for, and it is the one you did not set. But read what it gates: it freezes the IWDG counter when the core is halted by the debugger. It is a debug-halt freeze, not a low-power-STOP freeze. On STM32 the IWDG is clocked from the LSI and keeps counting straight through STOP; no configuration bit stops it there. So the reset at 8 s is the IWDG doing exactly what the reference manual says, not a missing option.
The two bits people conflate:
DBGMCU_CR.DBG_STOP: keeps the clocks alive in STOP so a debugger can stay attached.DBGMCU_*.IWDG_STOP: freezes the IWDG counter while the core is halted.
Neither one does anything in production with no debugger attached.
What actually fixes it. Three options, in the order I would try them:
- Refresh from the RTC wakeup. Wake every 4 s, kick the IWDG, go back to STOP. One wakeup per 4 s instead of one per 30 s.
- Lengthen the IWDG period. With LSI at 32 kHz, prescaler 256 and reload 4095, the timeout is 256 × 4096 / 32000 = 32.8 s. That covers a 30 s STOP with 2.8 s of margin: thin, and LSI tolerance eats into it, so only if the STOP is bounded and you have checked the LSI spec for the part.
- Use a watchdog clocked from a clock that stops in STOP (WWDG on PCLK). It will not reset you during STOP, but it also is not watching: the RTC has to cover the STOP window.
The failure, traced. 30 s STOP intended, IWDG 8 s, LSI 32 kHz. The IWDG fires at 8 s, the part resets, boots, runs 200 ms at 12 mA, and drops back into STOP. The duty cycle becomes 8 s STOP + 200 ms RUN, not 30 s STOP.
| Item | Value |
|---|---|
| intended STOP | 30 s |
| actual cycle | 8 s STOP + 200 ms RUN |
| STOP current | 8 µA |
| RUN current | 12 mA |
| average | (8 µA × 8 s + 12 mA × 0.2 s) / 8.2 s ≈ 301 µA |
| 250 mAh at 301 µA | 830 h ≈ 34.6 days |
| 250 mAh at 8 µA | 31,250 h ≈ 3.6 years |
That is a factor of ~38 in battery life, and the symptom on the bench is a device that looks like it resets at random.
How I would confirm it. Read RCC_CSR reset flags after each wake; IWDGRSTF set means the IWDG fired. Log it across 10 STOP cycles of 30 s and require IWDGRSTF clear, plus average current ≤ 15 µA measured rather than estimated.
Curated: · Written: · Reviewed:
Q&A-48Idle calls WFI. DMA to SRAM stalls. Who gated the clock?
The 60-second answer
WFI didn't gate anything. On STM32F407, WFI with SLEEPDEEP = 0 enters Sleep mode: the Cortex-M4 core clock stops, but each AHB/APB peripheral keeps its clock only if its low-power-mode enable bit is set in RCC_AHB1LPENR, RCC_APB1LPENR or RCC_APB2LPENR. The DMA controller's clock is gated by DMA1LPEN (bit 21) and DMA2LPEN (bit 22) of RCC_AHB1LPENR. Clear DMA1LPEN and DMA1's clock stops the moment the core enters Sleep; a transfer in flight stalls with no transfer-complete and no error flag. The SRAM is clocked from HCLK and has no LPEN bit of its own on F4, so "SRAM" is a misread of the symptom: the clock that went away belongs to the DMA controller or to the peripheral raising the request.
Assumptions: STM32F407, STM32CubeF4 HAL, SLEEPDEEP = 0 (Sleep, not Stop), DMA1 servicing a peripheral-to-memory RX transfer into SRAM.
Mechanism
Sleep gates clocks per peripheral, not globally. Two bits decide whether an RX transfer survives:
RCC_AHB1LPENR.DMA1LPEN: the DMA controller's own clock.RCC_APB2LPENR.SPI1LPEN(or the matching APB1/APB2 bit): the clock of the peripheral that raises the request.
Gate the DMA clock and the controller freezes mid-transfer: the peripheral keeps filling its RX buffer, the DMA never drains it, and the SPI overrun flag (OVR) sets. Gate the peripheral clock and no request is ever raised, so the DMA sits idle. Both read as "the DMA stalled"; the register dump separates them. These LPEN bits reset enabled, so the gate is almost always software clearing them: a low-power init trimming idle current.
| Symptom | Gated bit | What you see |
|---|---|---|
| DMA frozen mid-transfer | AHB1LPENR.DMA1LPEN = 0 | NDTR stops, no TC, SPI OVR sets |
| No requests at all | APB2LPENR.SPI1LPEN = 0 | NDTR never decrements, no OVR |
Fix
/* STM32F407, STM32CubeF4 HAL */
__HAL_RCC_DMA1_CLK_SLEEP_ENABLE(); /* RCC_AHB1LPENR.DMA1LPEN = 1 */
__HAL_RCC_SPI1_CLK_SLEEP_ENABLE(); /* RCC_APB2LPENR.SPI1LPEN = 1 */
__WFI();
Diagnostic
Read RCC->AHB1LPENR and RCC->APB2LPENR at the stall. Bit 21 of AHB1LPENR clear means the DMA clock is the one that went away.
Arithmetic
SPI1 at 4 MHz, 1024-byte RX: 1024 x 8 = 8192 bits, 8192 / 4e6 = 2.048 ms to the last bit. If the DMA clock is gated at t = 0, TC never arrives; OVR sets once the RX buffer fills and the next word lands.
Failure modes
- Silent stall: no TC, no DMA error flag. Only
OVRon the peripheral and a frozenNDTRshow it. - Stop mode instead of Sleep:
SLEEPDEEP = 1stops the AHB/APB clocks regardless of the LPEN bits, so the DMA can never run. If you need the DMA alive, stay in Sleep. - Clearing all LPEN bits to cut idle current: a common low-power init does this and takes the DMA with it.
Trade-off
Keeping DMA1LPEN and SPI1LPEN set costs idle current: the DMA and SPI clocks keep toggling in Sleep. That is the price of a live transfer; measure it with the DMA running, not with it disabled.
Curated: · Written: · Reviewed:
Q&A-61RUN is 12 mA. STOP is 8 µA. A wake costs 40 µJ at 3.3 V. How long must you stay in STOP to win?
1.01 ms. Sleep longer than that and STOP wins; sleep less and you'd have burned less energy leaving the MCU in RUN.
Break-even is the wake energy divided by the current you avoid, times the rail:
t_be = E_wake / ((I_run - I_stop) x V)
= 40 uJ / ((12 mA - 8 uA) x 3.3 V)
= 40e-6 / 0.03957
= 1.011 ms
The 8 µA moves the denominator by 0.07%, so the usable rule of thumb is: one wake costs about a millisecond of RUN current.
| Item | Value |
|---|---|
| I_run | 12 mA |
| I_stop | 8 µA |
| E_wake | 40 µJ |
| V | 3.3 V |
| t_be | 1.011 ms |
Two duty cycles against that line, both on a 1 kHz loop:
200 µs STOP once per 1 ms: loses.
- STOP energy: 8 µA x 3.3 V x 200 µs = 5.3 nJ
- wake: 40 µJ
- cycle total: 40.005 µJ per 1 ms
- RUN for the same 1 ms: 12 mA x 3.3 V x 1 ms = 39.6 µJ
RUN wins by 0.4 µJ. Average current is 12.12 mA against 12 mA: you paid a wake to save 5 nJ.
10 ms STOP per 11 ms cycle: wins.
- STOP energy: 8 µA x 3.3 V x 10 ms = 0.264 µJ
- wake: 40 µJ
- cycle total: 40.26 µJ per 11 ms = 3.66 mW = 1.11 mA average
That is 10.8x below RUN. On a 1000 mAh cell: 3.5 days in RUN, 37 days duty-cycled.
Where this goes wrong in practice:
- E_wake must be the whole wake event, STOP exit through re-entry: PLL relock, peripheral re-init, sensor read, first ADC conversion. Measuring only the CPU exit latency undercounts by whatever the peripherals add, and that is usually the larger part.
- Averaging DMMs miss a 40 µJ burst. Use a shunt and a scope at a sample rate well above the wake duration, or a coulomb counter, and integrate the trace. A 200 µs wake needs at least a few hundred kSa/s to resolve.
- Measured I_stop above the datasheet's 8 µA usually means a debug UART, an LED, or a pull-up left enabled. Any of those can exceed the current you are trying to save.
- The RTC that wakes you runs in STOP. Its current is part of I_stop, not free.
Assumptions: one wake per cycle, the cycle repeats indefinitely, and the alternative is RUN for the whole cycle. The formula treats the wake as instantaneous; if the wake event itself runs at RUN current for t_w, the cycle is awake for t_w either way, so break-even becomes t_be + t_w.
Curated: · Written: · Reviewed:
Q&A-62You enter STOP then a 4 µs pulse arrives on EXTI. You never wake. The pulse is legal. What race did you accept?
Core answer.
The race is between the arriving edge and the clear of the EXTI pending bit in your sleep-entry sequence. The 4 µs pulse is legal: it is far longer than one APB clock period, so the EXTI edge detector latched it and set EXTI_PR. Your entry code then cleared EXTI_PR after the edge and before WFI. That clear erased the only record of the wakeup request, so WFI slept with nothing pending. You did not lose the pulse; you discarded the latch it set.
Assumptions: STM32F4 (RM0090), STOP mode, the line is configured as an EXTI interrupt and unmasked in EXTI_IMR, and you sleep with WFI.
Mechanism.
WFI returns when any unmasked EXTI line has its pending bit set (or the NVIC has a pending interrupt). Ordering is everything:
// STM32F4 / RM0090. Safe ordering.
EXTI->PR = EXTI_PR_PR2; // write 1 to clear any stale edge
__DSB(); // let the clear retire before sleeping
__WFI(); // a later edge sets PR and wakes here
The broken version clears after the edge:
if (!pin_high()) { // "no work"
EXTI->PR = EXTI_PR_PR2; // edge lands here -> erased
__WFI(); // sleeps forever
}
The dangerous window is between the last observation that says "no work" and the clear. Any edge in that window is destroyed by the clear. The window after the clear is safe: an edge there sets PR and WFI wakes immediately.
The pin claim to drop. A common wrong diagnosis is "that pin cannot wake from Stop." In Stop mode any unmasked EXTI line wakes the core; the dedicated WKUP pin (PA0) is special only for Standby. If PE2/EXTI2 did not wake, the line was masked or its PR was cleared, not because PE2 is incapable.
Alternatives, and when the design is wrong.
WFIvsWFE:WFIwakes on an enabled interrupt;WFEwakes on an event. If you configured the line as event-only,WFIwill never wake: useWFEor enable the interrupt.- Clear before vs after
WFI: clearing before is safe only if nothing clears after. The robust variant is to not clear beforeWFIat all and clear on wake, accepting a harmless spurious wake. - Polling vs STOP+EXTI: polling burns current; STOP+EXTI is right only with an unmasked line.
Failure modes and detection.
- Debugger attached: an SWD halt prevents STOP entry, so the race vanishes on the bench and only appears in the field.
- Floating or externally held pin: no edge, no wake.
- Detection: scope the pin and
EXTI_PRacross the entry window; inject 4 µs pulses 10,000 times and require 10,000 wakes.
| Entry sequence | Outcome |
|---|---|
| clear PR, then WFI | safe: a later edge sets PR and wakes |
| edge, then clear PR, then WFI | lost: the clear erases the live request |
| WFI, line masked | lost: no wake source |
| WFI, line event-only | lost: WFE would wake, WFI will not |
Curated: · Written: · Reviewed:
Q&A-65You expect a 1 kHz SysTick in STOP. You wake every 30 s. What clock did you actually keep?
You kept the LSE 32.768 kHz RTC (or LPTIM), not SysTick.
SysTick counts HCLK or HCLK/8: its clock is derived from the core clock. STOP gates HCLK and the core, so the instant you enter STOP, SysTick stops counting. There is no 1 kHz tick running in STOP. What keeps running is the low-speed oscillator: LSE at 32.768 kHz feeding the RTC (and LPTIM), or LSI at ~32 kHz feeding the IWDG. The 1 kHz tick you see after wake is reconstructed in software from the RTC's elapsed count.
Do the arithmetic before you trust it. 32.768 kHz is 2^15. Integer-dividing it gives 1024 Hz (÷32), 512 Hz, 256 Hz: never 1000 Hz. A "1 kHz" tick built from LSE is really 1024 Hz, 2.4% fast. If the ISR treats each tick as 1 ms, after 30 s of wall time you have counted 30,720 ticks and your software clock reads 30.72 s; over an hour that is 86 s of drift. Either accept 1024 Hz and scale, or read the RTC's own second/subsecond registers, which are exact.
Wake period: 30 s × 32.768 kHz = 983,040 LSE cycles. The RTC wakeup timer is a 16-bit down-counter clocked at RTCCLK ÷ (2, 4, 8, 16), so 2048 Hz max → 30 s = 61,440 counts, which fits in 16 bits. LPTIM in STOP has the same shape.
| Clock | Source | In STOP | Notes |
|---|---|---|---|
| SysTick | HCLK (or HCLK/8) | gated, dead | no tick |
| RTC | LSE 32.768 kHz | runs | wakeup timer, calendar |
| LPTIM | LSE / LSI | runs | 16-bit, prescaled |
| IWDG | LSI ~32 kHz | runs | resets, does not wake |
| SWD attached | — | HCLK kept on | false 1 kHz |
Failure modes I have hit.
- Debugger attached. The DBGMCU_CR DBG_STOP bit keeps HCLK alive in STOP, so SysTick keeps ticking and the 1 kHz looks fine on the bench. Detach SWD and it dies. Never validate STOP timing with a debugger attached.
- IWDG as an accidental wake. IWDG runs on LSI in STOP and its timeout is a reset, not a wakeup. Set it to 8 s, enter STOP for 30 s, and the part resets every 8 s: you see an 8 s cadence and blame the RTC.
- LSI accuracy. LSI is specified to a few percent over temperature, so a 30 s LSI-based wake can be off by a second or more. LSE with a ±20 ppm crystal is off by ~0.6 ms over 30 s. If the 30 s matters, it must be LSE.
- vTaskDelay across STOP. A 10-tick delay queued before STOP is not 10 ms of wall time; it is 10 ms of tick time that only advances when the RTC wakes you. The task resumes 30 s later.
How I would settle it. Detach SWD, enter STOP, and require RTC EXTI (or LPTIM) to be the only enabled wake source. Measure current: a few µA means HCLK is really off. Scope a GPIO toggled in the wake ISR and check the period against a reference. Reconstruction error should be at most one RTC tick.
Curated: · Written: · Reviewed:
Q&A-67Internal LDO is in high-power mode. STOP current is 180 µA not 8 µA. Which PWR bit is still RUN?
The bit is LPDS in PWR_CR, and it is still 0: the value it holds in RUN. LPDS picks which internal regulator runs during STOP: LPDS=0 keeps the main (high-power) regulator on, LPDS=1 hands over to the low-power regulator. 180 µA is the main-regulator STOP current; 8 µA is the low-power one. No other bit in PWR_CR accounts for that gap.
LPDS is latched when the core enters STOP, not when you set it, so the STOP path has to write it every time, immediately before the sleep instruction:
/* STM32F4, CMSIS device headers */
PWR->CR |= PWR_CR_LPDS; /* low-power regulator for STOP */
SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
__DSB();
__WFI();
LPDS defaults to 0, so a STOP path that never touches PWR_CR gets the main regulator. Worse, a shared PWR_CR read-modify-write in the RUN init that runs again after this clears LPDS, and you are back at 180 µA with no other symptom. On parts with a different PWR layout the same choice lives in a regulator-mode field (LPMS on the L4 family, for instance) but the failure is identical.
Keeping LPDS=0 is sometimes deliberate. It is not automatically a bug:
- Wake latency. The low-power regulator has to restart on exit, and the datasheet's STOP wakeup time is longer for that case than for the main regulator. If you wake every few hundred microseconds, the extra regulator startup can cost more energy than the higher static current saves, and LPDS=0 is the lower-energy configuration.
- State retention. Check your part's STOP retention table: if the low-power path does not hold something you need across STOP, keep the main regulator up and pay the current.
- Debug. With SWD attached you cannot measure the difference: the debug unit adds roughly 100 µA, which is why 180 µA looks plausible on a bench with a probe connected.
Failure modes and how to catch them.
- LPDS cleared by a later PWR_CR write. Detect with a breadcrumb: read PWR->CR after STOP entry and require the LPDS bit set.
- LPDS never set because the STOP path was copied from the RUN init. Detect by measuring with SWD off; expect ≤15 µA, not 180 µA.
- "The LED toggled after WFI" only proves the core woke. It says nothing about the regulator, and it is the test that lets this ship.
| Configuration | STOP current | 250 mAh cell |
|---|---|---|
| LPDS=0, main regulator | 180 µA | ~58 days |
| LPDS=1, low-power regulator | 8 µA | ~3.6 years |
| LPDS=1, SWD attached | ~108 µA | ~96 days |
250 mAh / 180 µA = 1389 h ≈ 58 days. 250 mAh / 8 µA = 31250 h ≈ 3.6 years. The 22.5× gap is the whole battery life, and the SWD row is why the bench measurement hides it.
Curated: · Written: · Reviewed:
Q&A-68You retain 128 KB in STOP for 8 µA extra versus 2 KB. Do you need the 128 KB?
Short answer: no, not for 48 bytes of calendar state. Retain the 2 KB bank, power down the other 126 KB, and you keep the same data for 0.125 µA instead of 8 µA. You need the 128 KB only if the state you must survive STOP genuinely exceeds 2 KB, or if recomputing it on every wake costs more energy than the retention current.
Why the cost scales the way it does. Retention current is leakage from the cells you keep biased. The retention regulator holds the array powered, and leakage is roughly proportional to the number of cells retained, so the price is linear in KB. Here that is 8 µA / 128 KB = 0.0625 µA per KB, about 1 µA per 16 KB. The 2 KB bank is 2/128 of that: 0.125 µA.
The arithmetic.
| Retained | Extra current | Power at 3.3 V | Charge over 1 year |
|---|---|---|---|
| 128 KB | 8 µA | 26.4 µW | ~70 mAh |
| 2 KB | 0.125 µA | 0.41 µW | ~1.1 mAh |
| State actually needed | 48 B | — | — |
8 µA × 3.3 V = 26.4 µW; × 8760 h = 231 mWh; ÷ 3.3 V = 70 mAh. On a 250 mAh cell that is 28% of the pack spent to hold 48 bytes. The 2 KB option is 1.1 mAh, 0.4%.
Making it real. The trap is that retention is often a linker decision, not a code decision. If .bss lands in the retained region, every global keeps the bank powered. Put the calendar in its own section and let the linker place only that:
/* calendar.c — C, GCC/Clang section attribute */
__attribute__((section(".retained_2k")))
static rtc_state_t g_calendar; /* 48 bytes */
Map .retained_2k into the 2 KB bank in the linker script, leave the 128 KB bank out of the retained region, and configure the retention controller for that bank only. Confirm with a current trace, not by reading the map file.
When 128 KB is the right call. Two cases. First, the state is genuinely large: a DSP filter history, a crypto session, a frame buffer you must resume. Second, wake rate: if you wake thousands of times a second, recomputing state from scratch each time can cost more than the µA you saved. Compare in energy per wake, not in µA.
Failure modes to check.
- Retained-by-default BSS: the bank stays powered because nobody moved the section. Detect by measuring STOP current with the app's real linker script, not a bare-metal example.
- Persisting to flash instead: write energy and endurance. A 48-byte record rewritten on every wake burns cycles; retention has no write cost.
- Trusting the datasheet number: 8 µA is typical at 25 °C, and leakage rises with temperature. Re-measure at your maximum ambient.
Retained RAM is a line item. Pay for the bytes you keep.
Curated: · Written: · Reviewed:
Q&A-64STOP is specified 8 µA. You measure 1.01 mA. 20 pins are floating inputs. What do you do before blaming the regulator?
Don't blame the regulator yet. 1.01 mA is almost exactly what 20 floating CMOS inputs draw: at roughly 50 µA of shoot-through per pin, 20 × 50 µA = 1 mA, and 1 mA + 8 µA STOP = 1.008 mA. Within a hair of your 1.01 mA reading. The regulator is doing its job; the pins are the load.
What I do, in order:
- Configure every unused pin before measuring anything else. Analog mode (input buffer disabled, no pull) is the lowest-current option on most parts; a pull-up or pull-down is fine if the pin must be defined and the pull current is acceptable. Never leave a pin as a floating digital input.
- Measure pin-group by pin-group. Set 19 pins to analog, leave one floating, and watch the delta. That attributes the current to specific pins instead of guessing.
- Disconnect SWD/JTAG. A live debug probe holds pins and adds its own current; a STOP number taken with SWD connected is not a STOP number.
- Fix voltage and temperature. Leakage is strongly V- and T-dependent; quote the number at a stated 3.3 V and 25 °C.
The arithmetic, once:
| Item | Current |
|---|---|
| STOP spec | 8 µA |
| 20 floating inputs × 50 µA | 1,000 µA |
| Predicted total | 1,008 µA |
| Measured | 1,010 µA |
| After analog config | ~9 µA |
At 1.008 mA a 250 mAh cell lasts 250 / 1.008 ≈ 248 h ≈ 10.3 days. At 9 µA it lasts 250 / 0.009 ≈ 27,800 h ≈ 3.2 years. Same board, same regulator: the difference is entirely the pin configuration.
Why floating inputs cost milliamps: a floating CMOS input sits at an undefined mid-rail voltage, so both the PMOS and NMOS of the input inverter are partially on and current flows straight from VDD to VSS. That is shoot-through, not leakage, and it is orders of magnitude larger than the 8 µA STOP spec. The 50 µA/pin figure is the assumption to verify on your part, it varies with input buffer design, but the order of magnitude is what makes 20 pins add up to milliamps.
Failure modes to check before you accept the fix:
- A pull-up on a pin that is externally driven low burns current continuously; analog mode is better there.
- Pins that look unused but are bonded to a module, a level shifter, or a test point are not unused.
- One configured pad can hide the problem: on a board I worked on, the only non-analog pin was a green LED on a push-pull output, and it was the sole thing drawing current after the rest were fixed.
I don't call it settled until a current trace with all unused pins analog, SWD off, at 3.3 V and 25 °C reads at most 15 µA. If it still reads milliamps with every pin defined, then the regulator, or something else on the rail, is worth suspecting.
Curated: · Written: · Reviewed:
Q&A-69A button bounces 3.2 ms. You wake STOP on EXTI and run 12 mA for 20 ms of debounce in software. What hardware filter did you skip?
The filter you skipped is the analog one at the pin: an RC low-pass feeding a Schmitt-trigger input (or a dedicated debounce IC). It sits between the switch and the MCU pin, so the 3.2 ms of contact chatter is smoothed into a single clean edge before EXTI ever sees it. With it, the bounce never becomes a wake, and the 20 ms software debounce becomes unnecessary.
The EXTI digital glitch filter is the near-miss, and it is the trap in this question. On STM32 it samples the pin on a selectable clock and requires N consecutive equal samples (N = 1..8). At 32 kHz LSE, 8 samples is 8 / 32768 = 244 µs. Your bounce is 3.2 ms, about 13× longer, so the digital filter passes every edge. It is a spike suppressor, not a debounce.
Why the software path costs what it does: one STOP exit plus 20 ms of RUN at 12 mA per edge. Assume a tactile switch produces ~12 edges across the 3.2 ms bounce (labelled assumption: scope yours).
| Item | Value |
|---|---|
| Bounce | 3.2 ms, ~12 edges |
| EXTI digital filter, 32 kHz LSE, 8 samples | 244 µs: passes all edges |
| Software debounce | 20 ms × 12 edges = 240 ms at 12 mA |
| Energy per press | 240 ms × 12 mA = 2.88 mA·ms = 0.80 µAh |
| 1,000 presses/day | 240 s × 12 mA = 0.80 mAh/day |
| RC + Schmitt at pin | 1 edge per press, 0 extra wakes |
The RC time constant has to exceed the bounce: τ = R·C ≥ 3.2 ms, with the Schmitt threshold (e.g. 1/3 and 2/3 VDD) restoring a clean edge. 10 kΩ with 1 µF gives τ = 10 ms, comfortably past 3.2 ms. Cost is one resistor, one cap, and a Schmitt input: many MCU pins have one; otherwise a 74HC14.
Failure modes:
- RC too short: τ < bounce, so edges still get through. Detect by scoping the pin.
- No Schmitt: a slow RC edge parks the input in the linear region and the pin draws crowbar current or oscillates. Detect by measuring pin current.
- Digital filter mistaken for debounce: you keep the 240 ms-per-press RUN cost and believe you fixed it.
If the board is already spun and you cannot add the RC, the fallback is a lockout: on the first edge, mask the EXTI line for 10 ms, then re-enable. That is one STOP exit per press, not twelve. It is software, so it is the thing the question asks you to avoid, but it is the correct fallback.
Verify by scoping the pin and the RUN current for one press: you want one edge and one 20 ms RUN burst, not twelve.
Curated: · Written: · Reviewed:
Q&A-45eExpectedIdleTime is 0xFFFFFFFF. The 32-bit tick is 0xFFFF0000. You wanted an 18-hour STOP. What wrap did you miss?
The wrap you missed is in the addition, not the compare. now + idle is 32-bit: 0xFFFF0000 + 0xFFFFFFFF = 0x1FFFEFFFF, truncated to 0xFFFEFFFF. That is now − 1. Your expected-wake tick sits one tick behind the current tick, so the deadline is already in the past. Whatever test decides "is the wake still ahead of me?" (wake > now, or a hardware compare against the live counter) is satisfied the moment you arm it. STOP is never entered; you drop straight back to RUN.
Second bug stacked on top: 0xFFFFFFFF ticks at 1 kHz is 49.7 days, not 18 hours. 18 h is 64,800,000 ticks, 0x03DCC500. So the value you asked for is wrong even before the wrap.
Why it behaves that way. Unsigned wrap is the correct tool for elapsed time: now − start is right across a wrap. It is not safe for an absolute deadline built as now + delta unless the comparison is wrap-safe. The idiom that survives a wrap is the signed difference: (int32_t)(wake − now) > 0 means the deadline is still ahead. With wake = now − 1 that difference is −1, so the guard correctly refuses to sleep, but only if you wrote it that way.
uint32_t now = 0xFFFF0000u; // 1 kHz tick
uint32_t idle = 0xFFFFFFFFu; // requested
uint32_t wake = now + idle; // 0xFFFEFFFF (wrapped)
if (wake > now) { // 0xFFFEFFFF > 0xFFFF0000 -> false
arm_wakeup(wake); // never reached
enter_stop();
}
// wrap-safe form:
if ((int32_t)(wake - now) > 0) { ... } // -1 -> false, no sleep
Alternatives, and when each is right.
- Cap the sleep to the counter's max period and re-arm in a loop. Right when the hardware counter is narrower than the sleep: a 24-bit ARR, or an RTC wakeup timer with a bounded max.
- Chain: sleep the maximum, subtract it, sleep again. Right for multi-day sleeps on a short-period timer.
- Keep a 64-bit deadline or a monotonic seconds counter. Right when a single sleep can exceed half the counter range, so the signed difference itself would overflow.
- Wrap-safe 32-bit signed difference. Right when the sleep stays under 2^31 ticks and you want to keep the counter narrow.
- Don't widen the compare to 64-bit while still reading a 32-bit hardware counter: you still need the wrap-safe difference on the low word.
Failure modes and how you catch them.
- Immediate wake: current stays at RUN (mA) instead of STOP (µA). Catch it with a current trace, or a GPIO toggled on STOP entry and exit.
- Silent wrong duration: no fault flag, just battery. 49.7 days instead of 18 h misses the deadline by a month. Catch it by logging actual sleep against requested.
- The timer that actually runs in STOP is the low-power one (an RTC wakeup), not SysTick: SysTick is a core timer and stops in deep sleep, so it cannot be the thing that wakes you.
| Item | Value |
|---|---|
| now | 0xFFFF0000 |
| idle requested | 0xFFFFFFFF |
| now + idle (mod 2^32) | 0xFFFEFFFF |
| wake − now (signed) | −1 tick |
| 0xFFFFFFFF ticks @ 1 kHz | 49.7 days |
| 18 h @ 1 kHz | 64,800,000 ticks = 0x03DCC500 |
Curated: · Written: · Reviewed:
Q&A-70You STOP the core. ADC DMA to SRAM should fill 256 samples. The buffer stays 0xA5. Who stopped the DMA clock?
The low-power mode you entered did. On STM32L4/L4+/U5, STOP2 gates the DMA and ADC kernel clocks; STOP0 and STOP1 keep them running. Arm an ADC+DMA transfer, enter STOP2, and the DMA controller never sees a request: nothing is written to SRAM and the buffer keeps whatever your init code put there, 0xA5. The core sleeping is not the ADC sleeping, but in STOP2 the ADC is sleeping too.
Confirm it in five minutes, in this order.
- Reset flags. Read RCC_CSR (RMVF, BORRSTF, PINRSTF, IWDGRSTF, LPWRRSTF). If a reset fired, 0xA5 is just your init code re-running and the DMA story is a red herring.
- Remaining count. Read the DMA channel's CNDTR. 256 means no transfer ever happened: clock or request missing. 0 means it completed and your bug is elsewhere (wrong buffer address, or you read a different buffer than the DMA wrote).
- Mode actually entered. The PWR bit that selects the low-power regulator (LPSDSR on L4) tells you STOP0/1 versus STOP2. Read the register; don't trust the macro you called.
- ADC clock source. The ADCSEL mux in RCC_CCIPR. If it points at a PLL, STOP turns the PLL off and the ADC stops converting even in STOP0. Point it at HSI16 or MSI.
- ADC_CFGR.DMAEN and DMACFG. DMAEN must be set, and DMACFG=1 (circular) or the ADC stops after one conversion.
Ranked suspects. Mode gating is first. Second is the ADC clock source being PLL-derived: the DMA clock is fine but the ADC never produces a sample to request. Third is DMAEN never set, though that would have failed before STOP too, so it is unlikely if the same code worked in RUN. Fourth is a reset, which the RCC_CSR read rules out.
One cross-check: if you woke on DMA TC, the DMA clock was running, because the transfer-complete interrupt cannot fire from a gated controller. If you woke on something else (RTC, EXTI), that is consistent with the DMA never having run.
Cost of the fix. Currents below are illustrative: measure yours.
| Mode | DMA/ADC clock | Current | 256 samples @ 200 kS/s |
|---|---|---|---|
| STOP2 | gated | 2 µA | never: buffer stays 0xA5 |
| STOP0 | runs | 180 µA | 1.28 ms, 0.76 µJ |
256 samples × 2 B = 512 B. 256 / 200 kS/s = 1.28 ms. Energy at 3.3 V: 180 µA × 3.3 V × 1.28 ms = 0.76 µJ.
When to use which. STOP2 if you can duty-cycle the sampling: wake on RTC, run the ADC in a short burst, sleep again. STOP0 if you need continuous DMA into SRAM while the core sleeps. If 180 µA is too much, cut the sample rate or shorten the conversion window so the active time shrinks.
Curated: · Written: · Reviewed:
Q&A-59On-the-fly AES-XIP hits a 12 µs QSPI stall. The core fetches a 6-cycle instruction. What do you budget?
Assumptions first. Core at 80 MHz (confirm from the clock tree; the cycle arithmetic scales linearly with it). AES-XIP decrypts on the fly, so a line fill is a QSPI read plus the AES pipeline, measured at 12 µs. Instruction cache line 32 bytes. The critical section is the PWM ISR, 50 µs period.
The budget. The 6-cycle instruction is not the line item. On a hit it costs 6 cycles = 75 ns. On a miss it costs 6 cycles plus a 960-cycle line fill = 966 cycles ≈ 12.075 µs. So the budget is
budget = core cycles + (misses × 960 cycles)
and the only term worth engineering is the miss count. One missing fetch in the ISR eats 24% of a 50 µs PWM period; three eat 72%.
| Term | Cycles @ 80 MHz | Time |
|---|---|---|
| 6-cycle fetch, cache hit | 6 | 75 ns |
| QSPI + AES-XIP line fill | 960 | 12 µs |
| one missing fetch | 966 | 12.075 µs |
| 3 missing fetches in ISR | 2898 | 36.2 µs |
| PWM period | 4000 | 50 µs |
Mechanism. On-the-fly AES-XIP decrypts each cache line as it is fetched; the 12 µs is the QSPI transaction plus the AES pipeline, not the instruction. Misses are per line, not per instruction: a 32-byte line holds several Thumb instructions, so the first fetch of a line pays 960 cycles and the rest hit. That is why the miss count, not the instruction count, is the budget.
What I would do. Place the PWM ISR and its callees in SRAM or TCM: zero misses, zero stall, at the cost of the SRAM footprint. If it must stay in XIP, lock the ISR's lines in the cache or pre-warm them before enabling the timer, and bound the residual misses. Measure with DWT CYCCNT: run the ISR from XIP and from SRAM, publish both numbers.
Failure modes. Cache eviction by other code between ISR entries turns a warm ISR cold, so the miss count is not a constant. A second master on the QSPI (DMA, another core) contends for the bus and stretches the 12 µs. And a WCET measured with a warm cache is the classic wrong number: it certifies the ISR at hit latency and misses the stall entirely.
Evidence. CYCCNT delta for ISR-in-XIP versus ISR-in-SRAM, miss count from the cache controller's counters, and the QSPI stall re-measured under contention.
Curated: · Written: · Reviewed:
Q&A-66Vdd sags to 2.4 V for 80 µs while you program a 32-bit word. The part's PVD is 2.7 V but disabled. What is in flash?
Core answer
You can't know, and that's the point. With PVD disabled nothing stopped the write, so the flash controller kept clocking the program sequence while the charge pump was starved. What's in flash is an indeterminate word: some bits programmed, some not. It is not the value you intended, and it is not necessarily the erased value either. Treat the word, and probably the whole page, as corrupt.
Why
Flash programming doesn't write with Vdd directly. The controller runs an on-chip charge pump that boosts Vdd to the programming voltage the cells need for hot-carrier injection or Fowler-Nordheim tunneling. The pump can only regulate that voltage while Vdd is above the part's minimum programming voltage: the number the datasheet quotes as the Vdd floor for program. At 2.4 V the pump can't hold it, so the programming pulse is weak or aborted mid-sequence.
Two consequences:
- Programming only ever clears bits (1→0). A cell that got enough charge is programmed; a cell that didn't stays erased. So the result is the intended value ORed with a mask of bits that failed to program. For an intended 0x00000000 that bound is vacuous: any value from 0x00000000 to 0xFFFFFFFF is possible.
- The controller's state machine is mid-sequence. Depending on the part it may abort, complete with garbage, or hang until reset.
Your numbers make it worse: the sag is 80 µs and the program is 40 µs, so the sag covers the entire program window. No part of the write ran at spec.
What you can and can't say
| Statement | True? |
|---|---|
| Flash holds the intended word | No |
| Flash holds the erased word | No |
| Flash holds a bitwise superset of the intended 1s | Yes: bits only go 1→0 |
| The exact value is knowable | No |
Detection and recovery
- ECC on the word: a partially programmed word almost always fails ECC (single- or multi-bit). This is your primary detector.
- CRC over the region: catches the case where ECC is absent or the corruption spans the word.
- Read-back verify after program: necessary but not sufficient. After a brownout the read itself is fine, the value is wrong.
- Retry: erase the page and rewrite. Don't try to patch the word.
Prevention: the alternatives
- PVD at 2.7 V, enabled, reset or NMI: the right answer if the part has it. Check the threshold tolerance and response time against the flash minimum programming voltage with margin: a PVD that trips at 2.7 V ± 100 mV may not protect a part whose flash floor is 2.7 V.
- BOR: fixed threshold, often lower than the flash floor. Read the datasheet; it may not be enough.
- Software ADC check before write: doesn't help. The sag happens during the write, not before it.
- Write to a scratch page, verify, then commit: narrows the window, doesn't close it.
Failure modes
- Torn word: partially programmed, ECC/CRC fails on next boot.
- Stuck controller: some parts need a reset to recover; the flash may report busy indefinitely.
- Silent corruption: no ECC and the torn value happens to look valid. A flag that reads as set.
- Erase interrupted by brownout: the sector is indeterminate, not just the word.
What I'd do
Enable PVD at 2.7 V with reset (or an NMI that aborts the write), gate writes on a voltage check with margin, and ECC/CRC every region with a retry path. Then prove it: sag Vdd to 2.4 V on a MOSFET during program, 200 times, PVD enabled, and require 200 resets before the write completes and zero torn words.
Curated: · Written: · Reviewed:
Q&A-51The bootloader CRCs 384 KB and jumps. An attacker swaps a 384 KB image with the same CRC. What check was missing?
The missing check is authenticity: a signature verified against a key the attacker cannot change.
CRC-32 is a checksum, not a MAC. It takes no secret input, and it is linear over GF(2), so an attacker does not need a collision: they compute the 4-byte correction that forces any payload to the CRC already sitting in the header. "Same CRC" is not a constraint on the attacker; it is a free variable they solve for. The bootloader then CRCs the image it just read and compares against a field inside that same image, so both sides of the comparison are attacker-controlled.
What is missing is a check that binds the image to a key held outside the image:
- SHA-256 over the whole image, header and CRC field included.
- Verify an ECDSA P-256 signature over that digest with a public key burned into OTP (or ROM).
- Only then jump.
The private key never touches the device, so a swapped image fails verification. Two things are easy to get wrong. The digest must cover the header, or the attacker edits the length or entry point and leaves the signed body intact. And the verifier plus the public key must live in ROM/OTP, not in the updatable image, or the attacker replaces the check itself. Add a monotonic version counter if rollback to an older signed image matters.
Worked budget at 48 MHz for a 384 KiB image:
| Check | Time | Stops a swapped image |
|---|---|---|
| CRC-32 over 393,216 bytes | 18 ms | no |
| SHA-256 + ECDSA P-256 verify | 42 ms | yes |
| total | 60 ms | fits an 80 ms boot budget |
Keep the CRC anyway. It is cheap and catches bit rot before you spend 42 ms on the signature. It just is not the security boundary.
Failure modes worth naming: a green LED after CRC reports "checksum matched", not "image is trusted", which is exactly how a CRC-valid swapped image boots. And a signature check that runs after the jump, or on a copy the attacker can race, is no check at all.
How I would confirm the fix: flash a CRC-valid, unsigned image and require the bootloader to refuse and stay in the recovery path; flash a correctly signed image and require boot within the 80 ms budget including CRC. If the unsigned image boots, the check is still missing.
Curated: · Written: · Reviewed:
Q&A-53Slot B is signed version 6. OTP monotonic is 8. Do you boot B because the signature is valid?
No. A valid signature proves the image is authentic and unmodified; it says nothing about whether that image is still allowed to run. Version 6 is below the OTP monotonic value 8, so anti-rollback rejects it. The signature check passes and the boot gate fails.
Why the two gates are separate
Secure boot verifies the image against a public key burned into the device. That answers "did we sign this?" It does not answer "is this the oldest version we still trust?" A v6 image signed with the same key is authentic and still dangerous: it predates whatever was fixed in v7 and v8. An attacker who obtains any legitimately signed old image (from a leaked release, a recovered device, or a compromised build server) can replay it. Anti-rollback is the gate that closes that.
The rule
The image carries a security version number (SVN) inside the signed header, so the value you compare is itself authenticated. Compare it to the monotonic counter:
svn < otp→ refuse, do not boot, do not touch the counter.svn == otp→ boot, no counter write.svn > otp→ boot tentatively, confirm the image is healthy, then advance the counter.
The counter lives in one-way storage: eFuse bits, or a TPM/secure-element NV counter. It only goes up. That is the whole point, and it is also the trap: an increment you cannot undo.
boot(image):
if not verify_signature(image, pubkey): # e.g. ECDSA P-256 over SHA-256
return REFUSE_SIG
svn = image.security_version # inside the signed header
otp = read_otp_counter() # monotonic, one-way
if svn < otp: return REFUSE_ROLLBACK # v6 < 8 lands here
if svn == otp: return BOOT # no counter write
if boot_and_confirm(image): # trial boot, health check
advance_otp_counter(svn) # irreversible
return BOOT
Trace with the question's numbers: signature verifies, svn = 6, otp = 8, 6 < 8 → REFUSE_ROLLBACK. No counter write, no boot of B. With A/B slots the bootloader falls back to slot A; if A is also below 8, the device has no bootable slot, and that is a provisioning failure rather than a rollback decision.
Failure modes
- Incrementing before confirming. If you blow the counter the moment you see
svn > otpand the new image then fails to boot, you have permanently locked out the version that worked. Gate the write on a confirmed boot. - A single comparison branch.
if svn < otpis one branch an attacker can fault-inject past. Compare twice through independent paths, or do the comparison in hardware, and treat disagreement as a refusal. - A counter that is not actually one-way. If the "monotonic" value lives in flash or a file, it rolls back along with the image. It has to be OTP or a hardware NV counter.
- Detection. Log both values on refusal and alert on repeats. One refusal is a mis-provisioned device; a fleet-wide pattern is a downgrade attempt.
The trade-off
Strict anti-rollback means you cannot recover a fielded device by rolling back to a known-good older release. That is the cost, and it is usually worth paying, but it changes your release process: you must be confident enough in a build to burn the counter for it. Some products keep a rollback window of N versions instead of a hard floor, trading some downgrade resistance for field recoverability.
Curated: · Written: · Reviewed:
Q&A-56You rotate the public key in OTP. Slot A was signed with key 0. Do you still boot A?
Assumption first: OTP holds a fused digest of the trusted public key (or the key itself), and the ROM bootloader verifies each slot's signature against that fused material before handing control to the image. "Rotate" here means fuse key 1 and, to actually finish the rotation, revoke key 0.
No, not unless A was resigned with key 1 first. Once key 0 is revoked, the ROM rejects A's signature and there is no policy dial that changes that. If A still boots after the rotation, it is because key 0 is still fused and still trusted, which means the rotation hasn't happened yet.
The decision is entirely determined by what's in OTP:
| OTP state | A signed with key 0 | Boots? |
|---|---|---|
| key 0 only | yes | yes: rotation not started |
| key 0 + key 1 (window) | yes | yes: old key still trusted |
| key 1 only, key 0 revoked | yes | no: verification fails |
| key 1 only, key 0 slot overwritten | yes | no: verification fails |
So "do you still boot A" is the wrong question to ask at that point. The ROM already answered it. The question you control is the ordering.
Ordering that doesn't brick:
- Sign A and B with key 1.
- Verify both slots against key 1 on a bench board, not the fleet.
- Fuse key 1's digest into OTP.
- Re-verify both slots still boot.
- Revoke key 0.
Steps 1–2 before step 3 is the whole game. Revoke-then-resign is the brick.
Failure modes and how you see them:
- Revoked key 0 with A still on key 0 → the ROM halts at verification. The only way back is the ROM's recovery path (UART/USB download mode or an external programmer). If secure boot is paired with flash encryption and debug is locked, that path is closed and the board is scrap.
- Empty B slot → no fallback image when A fails. Keep B signed and valid at all times.
- Anti-rollback counter → if the rotation also bumped the security version, an image signed with key 1 but a lower counter is refused too. Resigning alone doesn't fix that.
- Key window left open forever → both keys verify, so a leaked key 0 still boots. Close the window once the fleet is resigned.
Trace of the ROM check (pseudocode, the way the ROM runs it):
fused = {1} # key 0 revoked
hdr = read_slot("A") # key_id = 0, sig, image
if hdr.key_id not in fused:
fail("key revoked") # -> recovery or halt
if not verify(hdr.sig, hash(hdr.image), pubkey[hdr.key_id]):
fail("bad signature")
jump(hdr.image)
With fused = {1} and hdr.key_id = 0, the first check fails. A never executes.
Before touching the fleet: run a rotation drill on a handful of boards (resign, verify, fuse, verify, revoke) and confirm the recovery path works on one board with a deliberately bad slot. If the recovery path doesn't work, don't revoke.
Curated: · Written: · Reviewed:
Q&A-52You copy slot B then reset. Slot B is now active without a confirm. A boot loop bricks both. What state did you skip?
The state you skipped is the trial state: the bootloader's per-slot boot-attempt counter and the successful flag. You went from "image written to B" straight to "B active," and in an A/B bootloader "active" without a trial marking reads as "confirmed." The bootloader now has no signal that B is unproven, so nothing tells it to fall back.
How the metadata actually works. A/B slot metadata is a small struct per slot: priority, successful (bool), and tries_remaining. The bootloader picks the highest-priority slot, boots it, and on a failed boot decrements tries_remaining. At zero it clears priority, marks the slot unbootable, and boots the next slot. Confirm is a separate write: after your self-test passes, you set successful = true. The trial state is what you set before B's first boot: priority high, successful = false, tries_remaining = N.
Why both slots brick. The trial state is what bounds the retries and gates the fallback. Skip it and the fallback either never fires or fires until nothing is left:
- If the bootloader only falls back on the trial state, B is treated as confirmed. B boot loops, the bootloader retries B forever, and A is never tried. A is intact but unreachable: the device is bricked.
- If the bootloader's fallback marks the failed slot unbootable, a loop that fails both slots leaves both marked unbootable. B fails → unbootable → switch to A. If A was never confirmed either, you only ever confirmed the slot you were replacing, A fails → unbootable. No slot is bootable.
Trade-offs. Two credible designs:
- Counter-based fallback: the bootloader owns
tries_remainingin slot metadata. Cheap, no extra hardware, but the counter lives in the same flash you are updating, so a power loss during the metadata write can corrupt it. Mitigate with two metadata copies plus a CRC, or a monotonic counter in a dedicated partition. - Watchdog plus revert: a hardware watchdog resets the SoC on a hang; the bootloader counts resets in an always-on register or RTC scratch and reverts after N. This survives a wedged bootloader that never reaches the metadata read, but it needs a reset source that the reset itself does not clear.
A confirm-bit design is the wrong choice when there is no second slot to fall back to (single-slot devices), or when the confirm write can be interrupted and you have no atomic metadata scheme, then a failed confirm bricks the only slot.
What I would verify. Flash a trial image that resets at 100 ms and require A to run after the retry budget, with B still unconfirmed. Program-complete is not confirmed.
Curated: · Written: · Reviewed:
Q&A-54Erase of slot B is 40 kB in 220 ms. Mains dies at 80 ms. What must still boot?
The firmware question under power-loss during a flash erase is which path still races after the path I just stepped through.
I treat erase as destroying the slot. Power loss mid-erase leaves B unreadable. A stays the active slot until B is fully programmed, authenticated, and then marked trial.
Concretely, i erase B, program B, CRC and verify signature, then mark B trial. A remains active through that sequence. I never mark B active before program plus CRC, and I test a supply drop at 80 ms of erase.
The reason for that specificity is a failure I have seen: I set B active, then erased. Drop at 80 ms of 220 ms. B unreadable, active equals B. Brick. A still had the old image. 7 of 40 lab drops. LED on erase-started was our only breadcrumb.
220 ms erase, 80 ms power loss.
| Item | Value |
|---|---|
| erase | 40,960 bytes, 220 ms |
| drop | 80 ms |
| B | unreadable |
| lab bricks if active=B first | 7 / 40 |
| required | A boots 40 / 40 |
I would not consider it settled without evidence: I would brownout the 3.3 V rail at 80 ms into erase on 40 tries and require A to boot 40 of 40.
Active must point at a slot that still exists.
Curated: · Written: · Reviewed:
Q&A-55A and B both CRC-fail. The product has no SWD in the field. What boots?
Nothing of yours boots. The mask ROM always runs (it lives in ROM, so it can't CRC-fail) but it finds no valid image in A or B and hands off to nothing. SWD is the escape hatch you don't have in the field, so the only way back in is in-band, over whatever connector the product ships with. If the ROM has no fallback and there's no recovery slot, the unit is bricked: no application, no updater, no transport. "What boots" is the ROM, and then nothing.
The decision that matters is what the ROM does next, and that depends on the part.
Boot decision, traced:
- Reset → ROM bootloader reads option bytes.
- BOOT0 = 0 → jump to flash base.
- Immutable bootloader (sector 0, write-protected) computes CRC of A → fail.
- CRC of B → fail.
- Check recovery-valid flag → if set, enter recovery mode and enumerate a signed update; else halt.
Step 5 is the whole question. Without it, steps 3–4 are terminal.
Options, with cost:
| Option | Flash cost | Field-reachable | When it's the right call |
|---|---|---|---|
| ROM system bootloader (e.g. STM32 AN2606) | 0 | only if BOOT0 strap or backup-register magic is reachable | BOOT pin exposed, or a spare pin can be strapped |
| Dedicated recovery slot | ~28 KB | yes, if the transport is alive | sealed unit, no ROM fallback, connector present |
| Rollback to golden image | 384 KB | yes | you can afford a third full copy |
| External media (SD/USB) | 0 flash | needs a connector | Linux-class SoC with a ROM USB loader |
Trade-offs. A recovery slot costs flash: 28 KB against 384 KB per slot is 7.3%: plus one irreversible OTP/RDP lock, and it adds a permanent signed-updater code path you now have to maintain. It buys a field-recoverable unit. The ROM bootloader costs nothing but depends on a pin or a backup register the application can write before jumping; if BOOT0 is strapped to flash and potted, it's unreachable and worthless. Rollback needs a third copy: A/B alone can't roll back when both fail, which is exactly this case.
When not to use a recovery slot. If the ROM loader is reachable in the field, a third slot is redundant flash. If the unit is sealed with no connector, a recovery slot has no transport to feed it: dead weight.
Failure modes. The recovery slot itself CRC-fails (same flash, same wear). The signed updater has a bug and rejects a valid image. The transport is dead: UART pin damaged, connector corroded. RDP level set so recovery can't read the incoming image. Each is detectable: a double-fail fixture that corrupts A and B and requires recovery to enumerate a signed update within 2 s of reset catches the first three; a bench test with RDP at the production level catches the last.
Arithmetic. UART at 115,200 8N1 is 11,520 B/s. A 384 KiB image (393,216 B) is 393,216 / 11,520 = 34.1 s. A 28 KB recovery image (28,672 B) is 2.5 s: fast enough to be the first thing you try.
Two slots can still be zero slots.
Curated: · Written: · Reviewed:
Q&A-57The trailer is 16 bytes: magic, length, CRC. A reset hits after 8 bytes. The bootloader reads length 0xFFFF. What protocol did you skip?
The protocol you skipped is the trailer's commit protocol: program the validity marker last, and gate the read on magic and CRC before you trust length. 0xFFFF is erased flash. Every bit still 1. The length word was never committed; the bootloader read a field the reset left unprogrammed and used it anyway.
Why 0xFFFF, mechanically
NOR flash bits only go 1→0. Erased is 0xFF. A program interrupted mid-word leaves the bits that already flipped at 0 and the rest at 1, so a torn word reads as the AND of old and new. With the trailer laid out magic(4) | length(4) | CRC(8), a reset after 8 bytes means magic committed, the length word was mid-program and its bits didn't take, and CRC was never written.
| offset | field | state after reset at 8 bytes |
|---|---|---|
| 0–3 | magic | committed |
| 4–7 | length | torn → 0xFFFF |
| 8–15 | CRC | erased → 0xFFFFFFFF |
The bootloader saw a valid magic, read length 0xFFFF, and never looked at the CRC that would have failed.
The protocol, both halves
Writer: order the program so the validity marker commits last. Write length and CRC first, magic last. A torn write then leaves magic erased, and the trailer is rejected instead of half-trusted.
Reader: check magic, recompute CRC over the trailer and the payload it describes, and only then use length. A CRC reading 0xFFFFFFFF fails, so the bootloader falls back to the other slot rather than jumping.
Trace
Bootloader reads magic → valid (it committed). Reads length → 0xFFFF = 65,535. Without CRC gating it copies 65,535 bytes out of the slot and jumps to them. 65,535 sits inside a 384 KiB (393,216-byte) slot, so no bounds check fires: the length is in range, just wrong. With CRC gating: CRC reads 0xFFFFFFFF, mismatch, reject, boot the other slot.
Alternatives
- A/B two-copy trailer. Keep two 16-byte trailers, write the inactive one, CRC it, then flip a single-word bank select. Costs 16 extra bytes and one extra program (~2 ms). Survives a torn write because the active copy is untouched.
- Append-only journal of trailer records, newest valid wins. More flash and a scan at every boot.
- Single copy with CRC-gated read only. Cheapest, but every torn write forces a fallback to the other slot. Fine with two slots, fatal with one.
When the ordering is unnecessary
If the flash controller guarantees word-granular atomicity (ECC plus a write-complete status) or you program the whole 16-byte trailer in one operation the controller reports as done-or-not, commit ordering is redundant: CRC gating alone is enough.
Failure mode and detection
Without it the bootloader jumps to garbage: 65,535 bytes of erased or partial payload used as a vector. Detect it by resetting during trailer program 50 times and asserting the reader sees either the old trailer or the new one, never a mixed length. That test is what would have caught this.
Curated: · Written: · Reviewed:
Q&A-58Factory sets CONFIRMED in the same script as PROGRAM. First power in the truck HardFaults. Why can you not revert?
The short answer
Because the confirm flag is the bootloader's only revert gate, and the factory set it before the image ever ran. The bootloader reads that flag before your code executes; with it set, the revert branch is never taken. There is also no old image on the device to revert to: the factory wrote the primary slot directly, so the secondary slot is empty. A HardFault is invisible to the bootloader: it does not count failed boots, so the unit boot-loops instead of falling back.
The mechanism
This is the MCUboot-style A/B scheme. Each slot has a trailer at its end holding a magic, a copy_done flag and an image_ok flag. The bootloader reads the primary slot's trailer before jumping to the application:
| Primary trailer state | Bootloader action |
|---|---|
| magic bad | boot primary as-is |
image_ok = 1 | boot primary, never revert |
copy_done = 1, image_ok = 0 | revert: swap the old image back |
copy_done = 0, image_ok = 0, valid image in secondary | swap the new image in (test), boot it |
The application confirms by calling boot_set_confirmed(), which sets image_ok. imgtool --confirm sets the same flag at build time, and a factory script can write the trailer directly. All three produce the same result: image_ok is set before the first boot. Whether the factory writes the primary slot directly or programs the secondary and lets the bootloader swap, the outcome is the same.
So the sequence is: factory programs with image_ok already set. First power in the truck: the bootloader reads image_ok = 1, boots the image, it HardFaults. Watchdog resets. The bootloader reads image_ok = 1 again, boots the same image. Loop.
Why there is no way back
- The gate is closed. The revert decision is a single read of
image_ok. It is set. Nothing the application does changes that: a HardFault is a CPU event, not a state the bootloader observes. - There is no fallback image. Revert is a swap; it needs a second image in the secondary slot. The factory programmed the primary slot directly, so the secondary slot holds nothing. Even if the bootloader wanted to revert, there is nothing to swap in.
- There is no unconfirm. The API is
boot_set_confirmed(); there is noboot_set_unconfirmed(). The flag lives in the primary slot's trailer sector, which the running application cannot safely erase.
Detection and recovery
Detection: read the trailer on a boot-looping unit. image_ok = 1 with a crashing image is the cause. A boot counter: increment a word in a noinit RAM section or a dedicated flash page, clear it after a successful self-test: would have caught it, but MCUboot's default does not count boots.
Recovery: MCUboot serial recovery (MCUmgr over UART or USB) or the SoC's ROM DFU, if either is provisioned. Otherwise a debugger. If none is enabled, the unit is bricked.
What to do instead
Program with image_ok clear. Let the application run its self-test and call boot_set_confirmed() only after it passes. That is the entire point of the test swap: the first boot is the test, and an unconfirmed image reverts on the next reset. If you need a factory-time check, add a boot counter with a max-attempts limit so a boot-looping image reverts after N resets.
Curated: · Written: · Reviewed:
Q&A-84You encrypt the 384 KB image with AES-CTR. An attacker flips one ciphertext bit. What happens to a jump opcode?
Direct answer. AES-CTR is a stream cipher: C_i = P_i XOR E_k(counter_i). The keystream does not depend on the plaintext, so flipping one ciphertext bit flips exactly the corresponding plaintext bit, at the same offset, and changes nothing else. Decryption still succeeds: there is no padding to fail and no tag to check. So the jump opcode changes in exactly one bit, and which bit decides the outcome.
What that does to the instruction. Take x86 JMP rel32: opcode E9, then a 4-byte little-endian displacement. Two cases.
- Flip a bit in the opcode byte.
E9=1110 1001. Flip bit 0 →E8=1110 1000,CALL rel32: the jump becomes a call and pushes a return address. Flip bit 1 →EB=1110 1011,JMP rel8: the instruction now consumes a one-byte displacement, so every following byte is decoded as a new instruction and the stream desynchronizes. Flip bit 2 →ED=IN eax, dx, privileged, faults in user mode. - Flip a bit in the displacement. The instruction is still a jump, but the target moves.
JMPat0x1000with bytesE9 10 00 00 00: rel32 = 0x10 = 16, next instruction at 0x1005, target = 0x1005 + 16 = 0x1015. Flip bit 4 of the displacement byte (0x10 → 0x00): target becomes 0x1005, 16 bytes earlier. Flip bit 7 (0x10 → 0x90 = 144): target becomes 0x1005 + 144 = 0x1095, 128 bytes later. Each flipped bit moves the target by a power of two, and the attacker picks which.
Scope. The flip is confined to the one 16-byte block whose counter produces that keystream byte. A 384 KB image is 393,216 bytes = 24,576 blocks; the other 24,575 decrypt byte-for-byte identical. The damage is one bit in one block: small, precise, and invisible to anything that only checks that decryption ran.
Why it matters. The attacker needs no key. They choose the offset and the bit, so they decide whether the jump becomes a call, faults, or lands in a gadget. There is no probabilistic corruption here; it is deterministic and repeatable.
Detection and fix. The only reliable detection is authentication: AES-GCM (16-byte tag) or encrypt-then-MAC with HMAC-SHA-256 over the ciphertext. Verify the tag before you decrypt or execute anything: that ordering is the point, because it means you never act on unauthenticated plaintext. A tag mismatch means refuse to boot. If you must keep CTR, add a separate signature over the image and check it in the loader before the first jump. Without one of those, a flipped bit is a silent, attacker-chosen edit to your code.
Curated: · Written: · Reviewed:
Q&A-85The TRNG returns 0xFFFFFFFF forever. You still make keys. Which health test did you skip?
The test you skipped is the Repetition Count test.
SP 800-90B defines two continuous health tests that run on every sample: the Repetition Count Test (RCT) and the Adaptive Proportion Test (APT). A TRNG that returns 0xFFFFFFFF forever is the textbook RCT failure: consecutive identical samples. If your 256-bit key is 32 copies of 0xFF, the RCT either never ran or its result was not wired to key generation.
Assumptions: 90B-style continuous tests, one sample per 32-bit word, min-entropy H ≈ 1 bit/sample, false-positive rate α = 2⁻²⁰.
RCT cutoff: C = 1 + ⌈−log₂(α)/H⌉ = 1 + 20 = 21. Twenty-one consecutive identical samples trips it, which a stuck source reaches in 21 reads. The APT would also catch a stuck source, but only after up to W = 1024 samples, and its cutoff comes from the binomial CDF. So if you ran APT alone you would still fail eventually; the test whose absence lets a constant stream through immediately is the RCT.
| Test | Catches | Window | Cutoff (H=1, α=2⁻²⁰) |
|---|---|---|---|
| Repetition Count | consecutive identical samples | immediate | 21 identical samples |
| Adaptive Proportion | one value dominating a window | W = 1024 | binomial-derived, low hundreds |
Why the ready bit lied: the "TRNG ready" flag usually reflects FIFO occupancy, not health. A FIFO full of 0xFFFFFFFF reads as ready. Health status is a separate signal, and it must gate key generation, not the LED.
Trace with RCT present: sample 1 = 0xFFFFFFFF, count = 1; … sample 21 = 0xFFFFFFFF, count = 21 ≥ C → RCT fail → key generation blocked. With RCT absent, the count never increments, the FIFO stays "ready", and every 256-bit key is 0xFF × 32.
Fallbacks, and when each is right:
- Refuse keys, hold the device locked. Correct default for a fielded device: no entropy, no keys.
- Reseed a DRBG from a stored seed. Acceptable only when that seed is per-device unique, injected at provisioning, and held in protected storage (OTP or secure element). Not acceptable if the seed is shared across a batch: you have moved the
0xFFproblem into the seed. It is also a one-shot: a DRBG reseeded from a fixed seed produces a deterministic stream, so it is a boot-time bridge, not a substitute for a live entropy source. - Switch to a second entropy source (ring-oscillator jitter, a second TRNG). Best when the hardware exists; you still run RCT and APT on the new source.
Failure modes to detect: RCT disabled or its cutoff set to zero; health result read but not gating keygen; ready flag wired to FIFO level; startup tests (the same RCT/APT over the first 1024 samples at power-up) disabled, so a stuck source boots clean.
Detection: force a stuck source in a harness by constant-filling the FIFO and require boot to refuse keys; separately verify the RCT fires at exactly 21 identical samples on good silicon.
Curated: · Written: · Reviewed:
Q&A-87UNLOCK with a 32-byte HMAC is sniffed. The attacker plays it back 2 s later. Why does it still work?
The 60-second answer
HMAC proves the message came from someone holding the key and wasn't modified in transit. It says nothing about when the message was sent. The tag is a pure function of (key, message): same key, same bytes, same tag, every time. So the frame the attacker captured is byte-for-byte the frame the device accepts. The verifier recomputes HMAC over the received command, compares, matches, unlocks. It holds no state that distinguishes transmission #1 from transmission #2: no nonce, no counter, no timestamp, no challenge. The 2 s delay is irrelevant; it would work at 2 ms or 2 hours.
Trace:
- t=0, host sends
55 01 01 | 9f 3c … (32-byte tag) - device computes HMAC(key,
55 01 01) == tag → unlock - t=2 s, attacker sends the identical bytes
55 01 01 | 9f 3c … - device computes HMAC(key,
55 01 01) == tag → unlock
The device sees no difference because there is none. The attacker never needs the key: the tag is already computed and travels with the command.
What actually stops it
Freshness has to come from somewhere the MAC cannot supply on its own: state on the device, or a clock.
- Challenge-response nonce. Device emits a random nonce; host sends HMAC(key, cmd ‖ nonce); device checks the nonce is fresh and unused. Costs a round trip and needs a real RNG on the device.
- Monotonic counter. Both sides hold a counter; host sends HMAC(key, cmd ‖ counter); device rejects counter ≤ last accepted. No round trip, one stored value, but it must survive reset and power loss, and it must not roll back.
| nonce (challenge-response) | monotonic counter | |
|---|---|---|
| round trips | 2 (challenge, response) | 1 |
| device state | nonce store / window | one counter value |
| needs RNG | yes | no |
| survives power loss | yes (nonce regenerated) | only if counter is in NVM |
| main failure | nonce reuse from weak RNG; window too wide | desync → rejects valid commands or accepts stale ones |
| NVM wear | none | OTP/EEPROM writes wear out |
Failure modes to name
- Counter in SRAM: lost on reset → device either accepts an old counter (replay window reopens) or rejects everything until resync.
- Counter in OTP: correct but finite write endurance; a counter incremented per command burns it.
- Nonce window > 1: a replay inside the window still lands.
- Weak RNG: predictable nonce → attacker precomputes the tag.
How I'd verify
Replay a captured frame 30 times and require 0 unlocks. Then confirm the freshness window is 1: a second use of the same nonce, or a counter ≤ last accepted, must be rejected. A static HMAC is a password with extra steps.
Curated: · Written: · Reviewed:
Q&A-88The device signs a quote of its UID. The cloud accepts the quote as a login. What binding is missing?
The 90-second answer
Assume the device holds a hardware key and the quote is a signature over a structure containing its UID: a TPM quote or an Android key-attestation blob. The cloud verifies the signature against the device's attestation key and, if it checks out, mints a session.
The missing binding is freshness, and behind it, session binding. A quote proves "this key signed this UID at some point." It does not prove "this key is on the other end of this connection right now." Only the second claim is a login.
Two bindings close the gap. First, a server-generated nonce inside the signed payload: the cloud issues 32 random bytes, the device signs UID ‖ nonce, the cloud checks the nonce is one it issued and has not consumed. That kills replay of a captured quote. Android key attestation does exactly this with setAttestationChallenge; TPM2_Quote takes the same value as qualifyingData. Second, channel binding to the connection. A nonce alone still lets an attacker relay: forward the nonce to the real device, forward the signed quote back. Signing over the TLS exporter (RFC 9266 tls-exporter for TLS 1.3) ties the signature to that specific connection, so a relayed quote fails verification.
The third problem is not a binding. The quote is an identity claim, not an authorization decision. A valid UID says nothing about whether that UID may log in. Authorization belongs to a separate credential: a device certificate issued at enrollment, or a server-side UID → account record.
Alternatives, and when a bare UID quote is fine
| Approach | Binds to | Stops replay | Stops relay | Cost |
|---|---|---|---|---|
| UID quote alone | nothing | no | no | none |
| + server nonce | this login attempt | yes | no | one round trip, nonce store |
| + TLS exporter | this connection | yes | yes | exporter plumbing on both ends |
| mTLS device cert | connection + identity | yes | yes | PKI, cert rotation |
| DPoP (RFC 9449) | this HTTP request | yes | yes | per-request signing |
A bare UID quote is acceptable when it is not a login: fleet inventory, telemetry, health checks, or a one-time enrollment step where you verify the quote once and issue a certificate you use thereafter. It is not acceptable as a session credential on its own.
Failure modes
Replay: one captured signature mints many sessions. In an incident I'd expect to see it as N sessions sharing one signature: 800 sessions from a single 64-byte signature is the shape. Detect by counting distinct signatures per UID and alerting on reuse.
Relay: the attacker proxies the nonce to the real device. Detect by channel-binding mismatch; without channel binding you cannot detect it at all.
Nonce store growth: an unbounded set of issued nonces is a memory leak and a DoS. Bound it with a TTL and an LRU. At 1,000 logins/s and a 5 s TTL you hold roughly 5,000 live nonces: trivial, but only if the TTL is enforced server-side. Device clocks are not trustworthy; expire on server issue time.
Software-backed key: if the UID key is not in a TPM or secure element, the quote is a bearer token and none of the above matters.
How I'd verify
Replay a captured quote with no fresh nonce and require a refusal. Relay a quote across a second TLS connection and require a refusal. Then a fresh nonce on the correct connection must succeed inside the 5 s window and fail after it.
Curated: · Written: · Reviewed:
Q&A-89UART command 0xFE dumps flash in the fixture. The same firmware ships. How do you close it?
State the assumption first: one binary is flashed to both the fixture and production units. If it is instead one source built twice, the fix is smaller: compile the command out of the production image and let CI fail the build if its symbol comes back. I will answer the harder case.
There is time pressure here. A 384 KB image is 393,216 bytes; at 115,200 baud, 8N1 is 10 bits per byte, so 3,932,160 bits / 115,200 = 34 s to read the entire flash with a USB-TTL adapter on the header. No debugger, no unlock. The dump hands over the firmware, the keys inside it, and every other vendor command in the image.
So: put 0xFE behind an OTP fuse read at dispatch time, gate the flash-read routine itself rather than its callers, and make production test assert a NACK instead of trusting a status LED.
Why hardware, not a flag
A flag in flash is circular. The attacker runs 0xFE to get the image, and the image contains the flag, its address and the branch that tests it. He reads it, or patches the check offline and reflashes. An OTP fuse differs in the two ways that matter: it is not in the image, so a dump neither reveals nor moves it, and once blown it cannot be unblown, so no write primitive restores the command.
Ordering matters as much as the gate. Check the fuse at the single point where vendor commands are dispatched, before the opcode is decoded and before the argument buffer is touched: otherwise a malformed frame reaches flash-read code ahead of the check.
static bool factory_unlocked(void) {
return OTP->lifecycle == LC_FACTORY; /* read at point of use, no shadow */
}
void vendor_dispatch(uint8_t op, const uint8_t *args, size_t n) {
if (!production_whitelisted(op) && !factory_unlocked()) {
send_error(); /* same frame as unknown opcode */
return;
}
run_vendor_command(op, args, n);
}
Trace 0xFE on a production part: production_whitelisted(0xFE) is false, so factory_unlocked() reads LC_PROD and returns false, and send_error() fires. The flash-read function is never reached. Because && short-circuits, whitelisted production traffic never even pays for the fuse read.
Better still, let the fused value seed the key the dump routine formats its output with: patch out the check and you get garbage rather than flash. Gate the routine, not the callers: otherwise DFU, an SWD mailbox and every future protocol are each a fresh chance to forget the check.
Trade-offs
| Control | Attacker who has the image | Cost to us | Use when |
|---|---|---|---|
| Compile-out | the code is simply absent | a second build to qualify plus a CI symbol check | one source, two builds: the default |
| OTP fuse gate | the fuse is not in the dump and cannot be unblown | one fuse per unit, one read per non-whitelisted opcode | one binary must ship to both |
| Password stored in flash | the password is in the dump | none | never: it is circular |
| Signed commands | forgery needs a key that is not in flash | key provisioning and rotation | the command must exist in production |
| Debug lock (SWD/JTAG) | does not touch the UART path | already required for IP protection | complementary, never a substitute |
When the fuse is not enough, and how each case shows up
- Fuse sampled once at boot into a RAM shadow: a stray write or a fault injection flips the gate. Read at the point of use, or derive key material from the fuse so a flipped branch yields no usable output.
- Wrong line sequence: the fixture still needs 0xFE after the fuse is blown, so it stops working halfway down the line and fails every later unit. Fix the sequence, not the firmware: blow the fuse at the last station and give post-blow fixture access SWD or a signed command.
- Unblown units ship: production test never checked the fuse state. Put the fuse read in the pass criteria, not just in the parser.
- Another opcode reaches the dump: the whitelist is not the only path. Find it by fuzzing the dispatcher on the production image with random opcodes and lengths.
Calling it closed
End of line: blow the fuse, send 0xFE, require the error frame, and let that decide pass. CI: fail the build if the dump routine's symbol appears in the production ELF. Then send 0xFE to the production image on ten units and require ten error frames, with the fuses read back as blown.
Curated: · Written: · Reviewed:
Q&A-90You AES-128 in 12 µs in software on a Cortex-M0. A 3.3 V shunt at 1 MS/s recovers the key. What did you not budget?
The thing you didn't budget is the power side-channel margin. You budgeted cycles (12 µs of AES inside a 50 µs loop, 38 µs of slack) and shipped. DPA doesn't spend your cycles; it spends your traces. The costs you never put in the plan are the ones that make the implementation leak-resistant (masking, and the entropy it consumes) and the ones that prove it (a leakage assessment campaign). Neither fits the 50 µs loop you designed around.
Why 1 MS/s is enough. At 1 MS/s you get one sample per microsecond, so a 12 µs encryption is 12 samples: roughly one per AES round. That is coarse, but it doesn't stop the attack. The first-round S-box output Hamming weight still shows up in the sample that lands inside round 1; it's diluted by the other 15 S-boxes and the round's other switching, so you need more traces than a 100 MS/s capture would, but the correlation converges. CPA recovers the 16 first-round key bytes independently, then you peel the rest.
The arithmetic that should have been in the threat model. 10,000 traces × 12 µs = 120 ms of actual encryption. Capture overhead dominates: at 10 ms per trace (arm trigger, capture, transfer) that's 100 s. Under two minutes of wall clock, on a bench, with a shunt you can buy. That number decides whether software AES is acceptable, not 12 µs.
| Option | Cost | DPA outcome |
|---|---|---|
| Software AES, no countermeasure | 12 µs (given) | key in ~100 s, 10k traces |
| Software AES + random delays | +0–8 µs | still recovered; alignment undoes the delay |
| Hardware AES, unmasked | accelerator, part-dependent | leaks; narrower window, easier to align |
| Hardware AES, masked + TVLA pass | accelerator + entropy | the bar to ship |
| Software AES, first-order masked | 2–4× cycles | may not fit the 50 µs loop; needs a TRNG |
Failure modes to name. Masked software AES is typically 2–4× the unprotected cycle count, so 12 µs becomes 24–48 µs: inside 50 µs only if nothing else runs, and it needs a fresh mask per encryption from a TRNG. If the part has no TRNG, you cannot mask in software at all. An AES-done GPIO is a free alignment trigger for the attacker; removing it doesn't stop DPA (traces align on the power envelope) but it removes the gift. Random delays are not a countermeasure: cross-correlation realigns them. And an unmasked hardware accelerator is not a fix; it moves the leak to a narrower, easier-to-align window.
What I'd require. Masked hardware AES if the part has it, plus a leakage assessment that passes: the non-specific fixed-vs-random t-test (ISO/IEC 17825) is run on 100,000 traces with a |t| threshold of 4.5. If it must be software, first-order masking with a TRNG, and re-budget the loop: the 50 µs was never the constraint that mattered.
Curated: · Written: · Reviewed:
Q&A-71RDP is 0. SWD pins are the default AF. A competitor dumps 384 KB in 12 s. What did factory skip?
What the factory skipped: the last step on the line. Programming readout protection, and remuxing the SWD pins off their reset default.
RDP 0 means the option byte that gates debug access to flash was never set. SWD pins sitting at their default alternate function means the firmware never took them away from SWDIO/SWCLK. Those two omissions together leave a live debug port on a shipped unit, and the flash is readable through it. The competitor didn't break anything: they used the port the factory left open.
The timing says this is not an exotic attack. 384 KiB in 12 s is 32 KiB/s:
| Quantity | Value |
|---|---|
| Image | 384 KiB (0x60000) |
| Dump time | 12 s |
| Rate | 32 KiB/s ≈ 262 kbit/s |
| Implied SWCLK | a few hundred kHz once protocol overhead is counted |
A few hundred kHz is a default-ish debug clock, not a high-speed reader. So the dump is a cheap CMSIS-DAP probe and one command:
openocd -f interface/cmsis-dap.cfg -f target/stm32f4x.cfg \
-c "init; dump_image fw.bin 0x08000000 0x60000; shutdown"
With RDP at level 1 that dump_image fails: the debug port refuses the flash read, and on parts that implement it the attempt triggers a mass erase, so the image is destroyed rather than leaked.
Why the step gets skipped: the fixture programs over SWD, so RDP has to be the final operation. After the last functional test, before the unit leaves the cell. That is exactly the step that gets cut when fixture time is the KPI. A fixture whose pass indicator is "SWD connected" actively rewards leaving the port open, because the same port that programs the part also proves the part is alive.
What "skipped" looks like in the option bytes: RDP left at level 0, and the SWD pins left at their reset alternate function with no remux to GPIO. Either one alone leaks; both together is the common case.
How I'd confirm it instead of assuming: pull sealed units from the shipping lot and try the dump. Ten units, ten failures expected. Then measure leakage on the SWD pins with the port supposedly off: a remuxed pin should read as a plain GPIO, not as a live debug line.
Failure modes to avoid when fixing it:
- Setting RDP before the final functional test locks the fixture out of reflashing a failed unit.
- RDP level 2 is permanent: no regression, no field rework. Don't reach for it to "be safe."
- Remuxing the pins without setting RDP leaves the port reachable via connect-under-reset, because the debug port is enabled by the option byte, not by the pin function.
Curated: · Written: · Reviewed:
Q&A-76You set RDP 1 in the first factory script. Stations 2 to 4 still need SWD calibration. What did you skip?
Short answer: the ordering. RDP 1 blocks debug access to flash, so stations 2–4 cannot write calibration over SWD. Calibration has to be written under RDP 0, before the lock goes on, or written by firmware running on the chip, which RDP 1 does not block.
What RDP 1 actually does
RDP is an STM32 option-byte setting with three levels. Level 1 blocks read and write access to main flash (and, on some families, backup registers and backup SRAM) from the debug interface: SWD or JTAG. User code running on the core can still read and write flash normally. Level 2 is irreversible: debug is permanently disabled and there is no regression path. Level 0 is the default, unprotected state.
The trap is regression. Going from RDP 1 back to RDP 0 is possible, but it triggers a mass erase of main flash on the next reset. So "just unlock it at station 2" destroys the program written at station 1, and any calibration already stored. The option-byte change also only takes effect after a system reset, so station 1 can lock the part and reset it before station 2 ever sees it.
| RDP level | SWD flash read/write | Regression path |
|---|---|---|
| 0 | allowed | n/a |
| 1 | blocked | to 0, mass-erases main flash |
| 2 | blocked | none, irreversible |
What was skipped, concretely
The lock went on before the last SWD write. The correct sequence is: program and calibrate under RDP 0, set RDP 1 only after the final station that writes over SWD, and reserve RDP 2 for parts that must never be dumped.
Alternatives if calibration must come after the lock
Two work:
- Firmware self-calibration. The on-chip firmware writes calibration values to flash itself. RDP 1 permits this: only the debug interface is blocked. The test station triggers the routine and reads back a result over UART or CAN, not SWD.
- Keep RDP 0 through the line and lock at final test or packaging, after the last station that needs debug access.
Detection
Under RDP 1 the debugger often still attaches: the failure shows up as a flash access error on write, not a missing target. So the symptom at stations 2–4 is a failed flash write, not "no debugger." Read the option bytes on a suspect part; if the RDP byte reads Level 1, that is the cause.
Failure mode
Locking early is silent until the next station tries to write. If the calibration write is the only SWD write after station 1, the whole run is affected: every board that passed station 1 is scrap unless you rework it, and rework means regression (mass erase), reprogramming, and recalibrating from scratch. The fix is to move the RDP 1 write to the last station that touches SWD, or move the calibration write into firmware.
Curated: · Written: · Reviewed:
Q&A-81RDP 1 is locked with a 64-bit password stored in firmware .rodata. Who can unlock?
Core answer (first 90 seconds)
Assumption first: the question describes a part where debug unlock is gated by a 64-bit password, and that password is compiled into .rodata. If both are true, the answer is everyone who has the image. A password in .rodata is not a secret: it is a constant in a file that ships. That means anyone with the .bin/.hex/OTA package, anyone with the ELF on the build server or in CI artifacts, anyone who can read flash from a device (SWD/JTAG on an unprotected part, a bootloader readout command, or a decapped/glitched part), and anyone the firmware was ever shared with. Per-unit provisioning is irrelevant because the same constant unlocks every unit.
Now the correction, because the premise mixes two mechanisms. On STM32, RDP level 1 is not a password mechanism at all. RDP1 blocks debug readout of flash; there is no 64-bit password to type. Regression from RDP1 to RDP0 triggers a mass erase, so the secret is destroyed, not revealed. Parts that do implement a debug-authentication password (STM32H5/U5 product-state lifecycle) keep that password in OTP, not in the image. So "who can unlock" has three different answers depending on which mechanism you actually mean:
- RDP1, no password: nobody unlocks readout. The only path is regression, which mass-erases flash. An attacker with physical access can still execute code on the device and attack the running firmware.
- Debug-auth password in OTP: only holders of the password. The provisioning station, and anyone who extracted it from a device or a log.
- Password in
.rodata: everyone.
Trade-offs
| Unlock mechanism | Where the secret lives | Who can unlock | Cost per unit |
|---|---|---|---|
Password in .rodata | the image | anyone with the image | 0 |
| Password in OTP | OTP, written at provisioning | provisioning station + anyone who reads OTP | OTP write time |
| Derived key (HUK + KDF) | device-unique secret, never leaves | the device itself; no extractable password | needs a silicon key store |
| Certificate-based debug auth | OEM private key, off-device | OEM only | key management + asymmetric crypto on device |
Pick by criteria, not habit: does the secret have to be recoverable, do you need per-unit revocation, can the device do asymmetric crypto, and what does provisioning cost per unit. A shared password in the image fails all four.
Failure modes
- One leaked image unlocks every unit: no per-unit revocation is possible.
- Regression to RDP0 mass-erases field data; if you relied on the password to avoid that, you lose the data anyway.
- OTP write errors at provisioning leave units that can never be unlocked, or that ship with a default.
- A password reused across a product line turns one extraction into a fleet-wide unlock.
Worked example (hypothetical)
Password 0x0123456789ABCDEF stored as a uint64_t in little-endian .rodata appears in the .bin as bytes EF CD AB 89 67 45 23 01. strings finds nothing: none of those bytes are printable ASCII. A byte-pattern scan of the .bin for that 8-byte sequence finds it in seconds. That is the whole attack: no debugger, no glitch, just a copy of the firmware.
How I'd verify
Scan the .bin for the 8-byte pattern and require zero hits, then confirm per-unit OTP verify on 10 samples. Do not trust strings: it only finds ASCII.
Curated: · Written: · Reviewed:
Q&A-82You set RDP 1. After NRST, SWD still dumps RAM. Is that a fail?
No, not a fail. RDP 1 gates readout of main flash and option bytes through the debug port. It does not gate general-purpose SRAM. A debugger that attaches over SWD after NRST and reads RAM is doing exactly what the part allows. The fail condition is the opposite: if SWD can read flash under RDP 1, your option byte isn't actually programmed.
Assumptions: an STM32-family part, RDP level 1, SWD attached after a system reset, and "dumps RAM" meaning reads of general-purpose SRAM through the AHB-AP.
Why RAM stays readable
RDP lives in the option bytes and is enforced by the flash memory interface. At level 1 the flash controller refuses debug-port reads of main flash and option bytes; the CPU can still fetch and execute from flash. SRAM is a separate slave on the bus matrix with no RDP gate, so the debug AHB-AP reads it directly. NRST resets the core and peripherals but does not clear SRAM contents, so whatever was in RAM before reset is still there when the debugger attaches. That is why the dump works.
| SWD access | RDP 0 | RDP 1 | RDP 2 |
|---|---|---|---|
| Main flash read | allowed | blocked | blocked |
| Option bytes read | allowed | blocked | blocked |
| General SRAM read | allowed | allowed | no debug port |
| Debug port | full | limited | disabled |
On some parts the backup SRAM is also gated or erased by RDP: check your reference manual for that row. General-purpose SRAM is not.
So the verdict holds: RAM readable under RDP 1 is expected. Flash readable is the fail.
If SRAM secrets are the concern, RDP 1 is the wrong control
- RDP 2. The debug port is disabled entirely. Right call when the device is sealed and you never need SWD again: it is irreversible, and you lose field debug and debug-based programming.
- Keep secrets out of SRAM. Store them in a secure element or a crypto peripheral with its own key store, or keep them encrypted in flash and decrypt into a peripheral. Right call when you need SWD for production test.
- Zeroize SRAM on boot. Helps against a warm reboot, but not against a debugger that halts the core at reset before your zeroize runs. Do not rely on it as the primary control.
Failure modes to check
- Flash read succeeds under RDP 1: the option byte is not programmed, or you are on level 0. Real fail.
- You assumed SRAM was protected because the RM table mentioned "SRAM": that row is usually the backup SRAM, not general SRAM.
- Regression to RDP 0 triggers a mass erase of flash, so an attacker can wipe but not read. That is by design, not a leak.
Concrete check: attach SWD after NRST, read a known flash address and a known SRAM address. Flash should fault or read as zero; SRAM should return the pre-reset contents. If flash returns real data, you have a fail.
Curated: · Written: · Reviewed:
Q&A-80PA13 and PA14 are SWD. At 50 ms you remux them to PWM. The fixture cannot attach. When do you remux?
Remux after the fixture has attached and finished, not at 50 ms. If the fixture attaches at 80 ms, 50 ms is 30 ms too early. The safe trigger is a fixture-done handshake; a fixed delay is the fallback.
PA13 and PA14 carry SWDIO and SWCLK out of reset. The debug port owns them until the remux write releases them to the timer alternate function. Once that write lands, the fixture's probe can no longer drive SWCLK or read SWDIO. So the attach at 80 ms does not see a target. It is not a probabilistic race; if remux precedes attach, attach fails every time.
When to remux, concretely:
- Production: fixture sets a done bit (OTP or a reserved RAM location) after ICT. The app polls that bit and remuxes only after it is set. This is the only trigger that does not depend on a guessed delay.
- No handshake: delay longer than the fixture's worst-case attach plus margin. A 3 s window covers an 80 ms attach with room. Energy cost: 12 mA * 3 s = 36 mC = 0.01 mAh. That is nothing next to a 4-day NPI delay.
- Field: if the field firmware needs PWM on those pins, remux after boot in the field image. Keep the factory image on SWD until the fixture is done. Do not remux on engineering builds; you will lose debug exactly when you need it.
Alternatives and trade-offs:
- Use different pins for PWM. If the timer has another channel on a non-debug pin, take it. You keep SWD and PWM.
- Keep SWD alive and drive the LED from a different pin. The PWM-on-PA13 LED is an app win, but it costs the factory its attach point.
- If you must remux early, provide a recovery path: a boot-mode strap plus the ROM bootloader, or a test point that can force the debug port back. Without that, a field unit that remuxes before a reflash is unrecoverable over SWD.
Failure modes and detection:
- Fixture attach fails with an SWD ACK timeout or "no target". Scope SWCLK and SWDIO: at 50 ms SWCLK stops; at 80 ms the fixture drives SWCLK and gets no response.
- Remux during a transaction corrupts flash programming. Gate on fixture-done, not just attach.
- OTP bit never set: app waits forever, watchdog resets, PWM never starts. Detect by reading the bit in the fixture log and by a timeout that falls back to a safe delay.
Trace of the failure:
| t | event | SWD state | fixture result |
|---|---|---|---|
| 0 | reset | SWDIO/SWCLK active | - |
| 50 ms | app remuxes PA13/PA14 to PWM | SWD released | - |
| 80 ms | fixture drives SWD | no target | attach fails |
Trace of the fix:
| t | event | SWD state | fixture result |
|---|---|---|---|
| 0 | reset | active | - |
| 80 ms | fixture attaches | active | OK |
| 120 ms | fixture sets done | active | OK |
| 121 ms | app remuxes | released | - |
I would not call it settled without evidence: attach SWD at 2.9 s and 3.1 s on 10 boards. Require 10 of 10 attach before the remux and 0 of 10 after, with the OTP override. That proves the window and the handshake.
Curated: · Written: · Reviewed:
Q&A-100You apply the rev-Y FLASH prefetch workaround on every die. Rev W hangs in the workaround. What do you read first?
Read the revision ID of the die in front of you, then the errata entry that revision selects. That order is the answer.
Read the rev ID, then the errata row it picks
The register is DBGMCU_IDCODE on the STM32 parts this pattern comes from: DEV_ID in bits [11:0], REV_ID in bits [31:16] (confirm the field layout in your family's reference manual). It is read-only and needs no debugger attached, so firmware can read it. Then open the errata sheet, find the affected-revisions line, and read the workaround for the revision you just read. Both reads, in that order.
The part number is not the answer: it does not identify the mask, the same orderable part ships with more than one revision, and a mixed reel is normal. Key the workaround table on the pair (DEV_ID, REV_ID), because the REV_ID code is only meaningful against the DEV_ID it came with.
It has to be the first thing SystemInit does
The workaround lives in flash setup, so any log line or status LED you add after it says nothing about whether it hung.
reset
-- reset handler
-- .data copy / .bss zero (runs from flash, ACR still at reset value)
-- SystemInit
-- read DBGMCU_IDCODE, keep REV_ID <-- first
-- write FLASH_ACR (prefetch, latency) <-- rev-Y workaround lives here
-- PLL, clocks, peripheral init
-- main
| What you might read | What it gives you | Why it is not first |
|---|---|---|
| carton rev letter or top marking | the revision the reel claims | firmware cannot see it, and a mixed reel makes it a guess |
| DEV_ID, bits [11:0] | which part | identical across the masks that differ here |
| REV_ID, bits [31:16] | the mask revision, and therefore the errata row | only meaningful next to its DEV_ID |
| current errata sheet | which workarounds still apply | only as current as the document you hold |
Why W hangs in the Y workaround
The workaround is specified for the revisions the errata lists. On any other revision you are running a sequence of flash-controller writes whose effect on that mask is undocumented: a bit that is reserved there, a poll on a status bit that never changes state there, an ordering that mask's flash controller does not re-arbitrate. Different root cause, same observable. The PC never leaves flash setup, so main never runs and nothing you wrote in main ever appears. That is why reading the code first does not help: the code is only wrong because it does not know which die it is on.
To find the line, set a GPIO before each step of the sequence - the same pin you would have used for a workaround-applied LED, now toggled per step. No spare pin: halt under a debugger mid-hang and look at the PC. Inside the ACR or wait loop means the workaround; in a fault handler means something else.
Trade-offs
- Per-revision gating. One image for a mixed reel, and prefetch stays enabled on revisions that do not need it off. Measure the throughput you keep with a DWT cycle count or a CoreMark-style loop on the actual part rather than assuming a number. Costs a boot read, a maintained rev table, and a declared default for unmatched revisions.
- Default for an unknown revision: skip the workaround and flag it, do not apply it. A sequence that is undocumented on that mask is not the safe branch. Record the REV_ID in a RAM word and as a GPIO pattern, since you have no console this early. Halting is defensible only when the erratum's failure mode is silent corruption rather than a hang; a hang you find in the lab.
- Uniform workaround. One code path, no table. Fine when the sequence is a no-op on every other revision, or when you control the supply down to a single revision. Not fine here: W sits outside the errata's coverage and that is where it hangs.
- Separate images per revision. Needs the revision known at programming time, which a mixed reel and field reflash both defeat.
- Cost of leaving it blanket: a share of every build hangs before main on W dies, looks like a dead board, and ends as rework or a reflash campaign.
Curated: · Written: · Reviewed:
Q&A-102The logger (prio 1) holds the I2C lock. Control (prio 5) blocks. Comms (prio 3) runs 8 ms. You replaced the binary semaphore with a mutex; the miss is unchanged. What did you not check?
Three tasks: logger at priority 1, control at 5, comms at 3. Logger takes the I2C lock, control blocks on it, comms becomes ready and preempts logger. With a binary semaphore the lock has no owner, so the kernel has no one to boost. Control waits until comms finishes its 8 ms, then logger runs again, finishes its critical section, and only then does control proceed. That is unbounded priority inversion: the wait is set by the medium task, not by the critical section.
A mutex changes that because it records the owner. When control blocks, the kernel raises logger's priority to 5 for as long as it holds the mutex. Logger preempts comms, releases the mutex, and drops back to 1. Control runs after the critical section, say 200 µs, not after 8 ms.
If the miss is unchanged after the swap, check these in order.
-
It isn't actually a mutex.
xSemaphoreCreateBinary()returns a handle thatxSemaphoreTake()accepts. It has no owner and no inheritance. The creation call must bexSemaphoreCreateMutex(). Also, mutexes are task-only:xSemaphoreTakeFromISR()on a mutex returnspdFAIL. If the ISR path uses a binary semaphore, that path has no inheritance. -
The holder blocks while holding the mutex. Inheritance raises priority; it does not make a blocked task runnable. If logger takes the mutex and then calls
vTaskDelay(), waits on a queue, or blocks on a second lock, control still waits for that block to clear. Copy the data under the mutex, release, then do the slow work. -
Chained inversion through a non-inheriting primitive. Logger holds the I2C mutex and then blocks on a binary semaphore or queue held by another low-priority task. FreeRTOS mutexes do chain inheritance, the second holder inherits the raised priority, but only if the second lock is also a mutex. A binary semaphore in the chain breaks it. Convert every lock in the chain to a mutex, or restructure to avoid nesting.
-
The holder is in a critical section or has interrupts masked.
taskENTER_CRITICAL()or a long ISR keeps logger from being preempted even at priority 5. Inheritance cannot preempt a masked region. Measure the longest critical section; if it is 8 ms, that is the real bug. -
configUSE_MUTEXESis 0. ThenxSemaphoreCreateMutex()is not compiled in, or the build silently falls back. CheckFreeRTOSConfig.h.
Timeline table:
| Time | Binary semaphore | Mutex |
|---|---|---|
| 0 | Logger (1) takes lock | Logger (1) takes mutex |
| 10 µs | Control (5) blocks | Control (5) blocks; logger → 5 |
| 20 µs | Comms (3) preempts logger | Logger (5) preempts comms |
| 8.02 ms | Comms done; logger resumes | Logger releases at 220 µs; control runs |
| 8.22 ms | Control runs | — |
Detection: toggle a GPIO in control before and after the take, and in logger around the critical section. A scope shows the real blocking time. uxTaskPriorityGet() on the holder while control is blocked should read 5 with a mutex and 1 with a semaphore. SEGGER SystemView or Tracealyzer shows the preemption directly.
Alternative: priority ceiling protocol assigns the lock the highest priority of any task that can take it, and the holder runs at that priority immediately. It prevents deadlock and bounds inversion to one critical section, but it requires knowing the ceiling at creation and can cause unnecessary blocking. FreeRTOS does not implement it; VxWorks and ThreadX do.
Curated: · Written: · Reviewed: —