Skip to content
Tech Interview Prep
Technical interview guide

Microcontroller Architecture & Memory-Mapped I/O

How a microcontroller's CPU, memory, and peripherals are organized around a single address space, and the architectural tradeoffs between common MCU families.

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

Scope: Arm CMSIS 6 and Cortex-M programmer guidance; Linux MMIO ordering/accessor guidance; STM32 Cortex-M4 programming manual reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

What is Memory-Mapped I/O (MMIO), and how does it compare to Port-Mapped I/O (PMIO) in terms of instruction set architecture and bus operations?

Answer

What a strong candidate says first

MMIO maps a device's control, status and data registers into the same physical address space as RAM, so the CPU reaches them with ordinary loads and stores. PMIO gives devices a second, separate address space that only dedicated instructions can touch. MMIO inherits the full instruction set, every addressing mode, MMU/MPU protection and DMA reachability, and also inherits caching and speculation, which you must explicitly turn off. PMIO gets a small, cache-free, naturally serialized access path in exchange for a 64 KB address space, a two-instruction vocabulary and extra bus pins. Arm and RISC-V have no PMIO at all; x86 is the architecture that still carries it.

MMIOPMIO
Instruction setAny load/store (LDR/STR on Arm, MOV to memory on x86) with all addressing modes and widths.IN/OUT only. Operand is AL/AX/EAX; port is an 8-bit immediate or DX.
Address spaceShared with RAM; consumes physical address space.Separate, 64 KB on x86, 16-bit port numbers.
Bus signallingOrdinary address/data/control; decode by address range.Extra pins mark I/O cycles: M/IO#, IOR#, IOW#.
ProtectionMMU/MPU region or page attributes.x86: CPL vs IOPL in EFLAGS, plus the TSS I/O permission bitmap.
Caching and orderingMust be typed non-cacheable/Device; barriers required.Never cached; not reordered with other I/O accesses.
DMAAny bus master can reach it.CPU-mediated; DMA engines address memory.

One MMIO store, traced on a Cortex-M4 (STM32F407)

C
#define GPIOC_ODR (*(volatile uint32_t *)0x40020814UL)
GPIOC_ODR |= (1UL << 13);      /* set PC13 */

The read-modify-write compiles to:

LDR r3, [r2]            @ r2 = 0x40020814
ORR r3, r3, #0x2000
STR r3, [r2]
  1. 0x40020814 sits in 0x40000000–0x5FFFFFFF, which the Armv7-M default memory map already types as Device: non-cacheable, and not accessed speculatively.
  2. The store leaves the core on the AHB system bus. The AHB1 matrix decodes the 1 KB window 0x40020800–0x40020BFF and selects GPIOC.
  3. The value lands in ODR; PC13 moves on the next peripheral clock edge.
  4. GPIOC->BSRR = (1UL << 13); is a single store with no read, and is preferable: the RMW above can drop a concurrent write to a different pin in ODR.

An APB peripheral adds a bridge hop. USART2 at 0x40004400 hangs off an AHB-to-APB bridge that asserts PSEL, drives PADDR/PWDATA/PWRITE, and stretches the transfer with wait states.

PMIO in practice

x86 still reaches PCI configuration space through ports: write 0x80000000 | bus<<16 | dev<<11 | func<<8 | reg to 0xCF8, then read or write 0xCFC. IN/OUT take only AL/AX/EAX, with the port as an 8-bit immediate or in DX, so any port above 255 must be materialised in DX first. The whole I/O space is 64 KB. Modern x86 devices (PCIe BARs, LAPIC at 0xFEE00000, IOAPIC at 0xFEC00000) are MMIO; PMIO survives for legacy and configuration access.

Failure modes

  • Without volatile, the compiler deletes the store or hoists the load out of a polling loop. volatile fixes that and nothing else.
  • Ordering: on Arm a normal-memory store (a DMA descriptor) can become visible after a Device store (the doorbell) unless a DSB sits between them. DMB orders without waiting.
  • Read side effects: a status register that clears on read is consumed by a second read, including one from a debugger. Device memory is not speculated, which is why the region is typed that way.
  • Faults: an unmapped MMIO address, or a peripheral whose clock is gated (RCC->AHB1ENR bit clear on STM32), raises BusFault or HardFault. An x86 IN from an unassigned port typically returns 0xFF and does not trap.
  • DMA engines issue memory addresses, so they can drive MMIO directly and cannot drive PMIO; port I/O stays CPU-mediated.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Design and validate an MCU/MMIO implementation for volatile.

Answer

Core answer (first 90 seconds)

volatile is a compiler contract, not a hardware one. C11 6.7.3 and C++ [dcl.type.cv] require every access to a volatile lvalue to be evaluated exactly as written, in program order relative to other volatile accesses. That is precisely the compiler half of the MMIO problem: no dead-store elimination, no merging two writes into one, no hoisting a status read out of a polling loop. It gives you nothing for atomicity, nothing for CPU-level ordering, and nothing for cacheability.

So the design is four layers, and validation is a disassembly check plus a read-back test.

Design

Type. Every register is a volatile-qualified lvalue of exact width. CMSIS already encodes this: __IO is volatile, __I is volatile const, __O is volatile. Never use bitfields for MMIO: their layout is implementation-defined.

C
/* C11, arm-none-eabi-gcc 13.2 -O2, Cortex-M4 */
#define REG32(a) (*(volatile uint32_t *)(uintptr_t)(a))
#define UART0_DR  REG32(0x40001000u)
#define UART0_SR  REG32(0x40001004u)
#define UART0_ICR REG32(0x40001008u)   /* write-1-to-clear */

Ordering. __asm__ volatile("" ::: "memory") is a compiler barrier only. __DMB() (CMSIS emits DMB) orders accesses; __DSB() is required when the write must have completed: before enabling a clock, or before returning from an ISR that armed a DMA; __ISB() after writing MPU or control registers.

Atomicity. A read-modify-write on a register is three accesses. Use _Atomic uint32_t (lock-free on ARMv7-M, Cortex-M3/M4/M7, via LDREX/STREX) or a PRIMASK critical section. ARMv6-M (Cortex-M0/M0+) has no LDREX/STREX, so a 32-bit RMW needs the critical section.

Memory attributes. The region must be Device, not Normal-cacheable. On Cortex-M the default map already marks 0x40000000–0x5FFFFFFF as Device; if you remap it with the MPU, keep the Device attribute. On Cortex-A the MMU descriptor must be Device-nGnRnE. volatile cannot fix a cacheable device region.

Validation

The operational test is the disassembly. Compile at -O2 and read arm-none-eabi-objdump -d:

C
void kick(void) { UART0_DR = 1; UART0_DR = 2; }

Without volatile, GCC emits a single str: the first store is dead. With it, two str in order. Same for while (!(UART0_SR & TXFE)) {}: without volatile the load is hoisted and the loop never exits. Then a read-back test: write a register, read it back, confirm the value; read a free-running counter twice and confirm it changes.

Failure modes

failuremechanismdetectioncost
volatile shared counterticks++ is ldr/add/str; an ISR between ldr and str loses the incrementcounter drifts against a hardware timer over 60 slost ticks, wrong timeouts
compiler barrier mistaken for CPU barrierasm volatile("" ::: "memory") emits zero instructionsdisassemble: no dmb/dsb mnemonicordering bug appears on silicon, not in the simulator
posted storeDevice write sits in the write buffer; a later read of another address is serviced firstintermittent, shows up at -O2 or with added wait statesperipheral acts on stale config
cacheable device regionMPU/MMU maps the region Normal; reads hit stale linesread a changing register twice, get the same valuesilent, no fault raised
compound access`UART0_ICR= bit` is ldr/orr/str on a write-1-to-clear registerunrelated flags cleared after the first write

Trade-offs

volatile is right for a register only this core touches; _Atomic is right for anything shared with an ISR or another core, and costs a LDREX/STREX retry loop or a PRIMASK window. __DMB is cheaper and sufficient for ordering; __DSB stalls until the write buffer drains and is only needed when completion matters. Bit-banding (Cortex-M3/M4 alias at 0x42000000) gives an atomic single-bit set or clear with no critical section, but it is absent on Cortex-M7.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and validate an MCU/MMIO implementation for access qualifiers.

Answer

Core answer (first ~90 seconds)

Assume a 32-bit Cortex-M with a memory-mapped peripheral block, C11, and CMSIS-style headers. The design is three typedefs, a struct overlay, and compile-time assertions that pin the layout.

C
#include <stdint.h>
#include <stddef.h>

typedef volatile const uint32_t ro_reg_t;  // __I  : read-only
typedef volatile uint32_t       wo_reg_t;  // __O  : write-only
typedef volatile uint32_t       rw_reg_t;  // __IO : read/write

typedef struct {
    ro_reg_t  ID;        // 0x00  read-only
    rw_reg_t  CTRL;      // 0x04
    wo_reg_t  TXDATA;    // 0x08  write-only, write triggers TX
    ro_reg_t  RXFIFO;    // 0x0C  read pops the FIFO
    rw_reg_t  STATUS;    // 0x10  write-1-to-clear flags
} UART_Type;

#define UART0 ((UART_Type *)0x40004000UL)

_Static_assert(sizeof(UART_Type) == 0x14, "UART layout drift");
_Static_assert(offsetof(UART_Type, TXDATA) == 0x08, "TXDATA offset");

volatile stops the compiler caching a register in a loop or deleting a write; const on ro_reg_t makes UART0->ID = x a compile error. That is the whole design: the type system encodes access direction, and the assertions catch header drift at build time.

Validation: three layers

  1. Compile-time: the _Static_asserts above, plus -Wcast-qual (GCC/Clang), which flags (uint32_t*)&UART0->ID casts that strip const.
  2. Host-side: overlay the same struct on a plain array and run the driver against it, asserting the exact sequence of reads and writes.
  3. Hardware: an MPU region marked read-only over the ID block, because const is a compiler promise, not a bus-level one.

Failure modes and detection

failurehow it happensdetection
const cast write*(uint32_t*)&UART0->ID = 1 through void* evades -Wcast-qualcode review; MPU fault at runtime
generated header wrongSVD marks a write-only register __IO; a read returns garbageread-back test against the datasheet
read has side effectRXFIFO read pops; a debugger or polling loop drains itbus scope; FIFO count check
mixed fields`CTRL= BIT` on a write-1-to-clear register clears other flags
hardware protection assumedDMA or a rogue pointer writes a const registerMPU region; fault handler

Trade-offs and alternatives

  • Bitfield structs vs. explicit masks: bitfields read nicely, but the C standard leaves bit ordering implementation-defined; for cross-compiler headers use masks and shifts.
  • volatile on the whole struct vs. per-field typedefs: whole-struct is simpler but blocks optimization on fields that do not need it; per-field typedefs are tighter.
  • CMSIS __I/__O/__IO vs. hand-rolled: CMSIS is the de-facto standard and SVD-generated; hand-rolled typedefs work but you lose the tooling.

When not to: if a driver owns all access, keep the raw struct private and expose an API. The qualifiers then guard the driver, not every caller.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Design and validate an MCU/MMIO implementation for register layout.

Answer

Core answer (first 90 seconds). Assume a 32-bit MCU, C11, one peripheral whose register map is fixed by the reference manual, and the manual as the single source of truth. Design the layout as a volatile struct overlay with explicit reserved arrays, place it at a #defined base, and validate it with _Static_assert on every offsetof and on sizeof, plus one boot-time read of a read-only ID register. That gives compile-time proof of layout and a runtime proof of the base address.

C
#include <stdint.h>
#include <stddef.h>

typedef struct {
    volatile uint32_t CR;        /* 0x00 */
    volatile uint32_t SR;        /* 0x04 */
    volatile uint32_t DR;        /* 0x08 */
    uint32_t          RESERVED0[5]; /* 0x0C..0x1F */
    volatile uint32_t BRR;       /* 0x20 */
} UART_Type;

#define UART0_BASE (0x40000000UL)
#define UART0      ((UART_Type *)UART0_BASE)

_Static_assert(offsetof(UART_Type, CR)  == 0x00, "CR offset");
_Static_assert(offsetof(UART_Type, SR)  == 0x04, "SR offset");
_Static_assert(offsetof(UART_Type, DR)  == 0x08, "DR offset");
_Static_assert(offsetof(UART_Type, BRR) == 0x20, "BRR offset");
_Static_assert(sizeof(UART_Type) == 0x24, "UART size");

Why offsets drift. The compiler inserts padding to satisfy alignment: a uint8_t followed by a uint32_t puts the word at offset 4, not 1. If the hardware has that register at offset 1, every access is wrong. Explicit RESERVED0 arrays make the gaps intentional, and offsetof asserts pin them. _Static_assert evaluates a constant expression at compile time: a mismatch is a build error, not a field bug.

Validation. Compile with -Wpadded (GCC/Clang) so accidental padding is reported, and -Wpacked. At boot, read a read-only ID/version register and compare to the datasheet value; that catches a base-address typo that a constant shift would hide from offsetof. Only write/read-back a scratch register if the manual says it is writable and side-effect-free.

Alternatives.

approachcostuse when
struct overlay + _Static_assertrelies on compiler layout; needs assertsfixed ABI, want compile-time checks
macro accessors #define UART_CR (*(volatile uint32_t*)(UART0_BASE+0x00))no type grouping, no sizeof checksparse or irregular maps, padding-immune
headers generated from CMSIS-SVDgenerator can be wrong; pin its versionvendor ships an SVD

Failure modes and detection.

faulteffectdetect
#pragma pack(1) left onsizeof shrinks; unaligned word access faults on device memorysizeof/offsetof asserts; HardFault
unsigned instead of uint32_ton a 16-bit MCU reads/writes 16 bits, clobbers the neighbour_Static_assert(sizeof(uint32_t)==4); offset assert
reserved gap missingnext register lands at the wrong offsetoffsetof assert
base typoall accesses shifted by a constantboot ID-register read-back
derivative header reusedwrong map for the partassert device-ID at boot; pin part number

Criterion. Struct overlay when the map is dense and you want compile-time proof; macro accessors when it is sparse or padding-hostile; SVD generation when the vendor provides one and you pin the generator version.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Design and validate an MCU/MMIO implementation for access width.

Answer

Core answer (first 90 seconds)

Assume a Cortex-M class MCU, 32-bit AHB/APB peripherals, registers at fixed addresses. The design rule: every MMIO register is reached through a volatile pointer of exactly the register's width, and every access compiles to exactly one load or store of that width. No bitfields, no memcpy, no uint8_t * cast onto a 32-bit register.

C
#include <stdint.h>
#include <stddef.h>

typedef struct {
    volatile uint32_t CTRL;    // 0x00  RW
    volatile uint32_t STATUS;  // 0x04  write-1-to-clear
    volatile uint32_t CNTLO;   // 0x08  RO, reading latches CNTHI
    volatile uint32_t CNTHI;   // 0x0C  RO
} timer_t;
#define TIMER0 ((timer_t *)0x40001000u)

static inline uint32_t mmio_rd32(volatile uint32_t *p) { return *p; }
static inline void     mmio_wr32(volatile uint32_t *p, uint32_t v) { *p = v; }

_Static_assert(sizeof(timer_t) == 16, "layout drift");
_Static_assert(offsetof(timer_t, CNTHI) == 0x0C, "CNTHI offset");

volatile stops the compiler caching or reordering the access; the fixed-width pointee stops it narrowing. The _Static_asserts catch padding drift the day someone inserts a field.

Why each failure happens

  • Compiler byte store. A bitfield struct struct { uint32_t EN:1; uint32_t MODE:2; } turns r.EN = 1 into a read-modify-write: LDR r0,[r1]; ORR r0,#1; STR r0,[r1]. On a write-1-to-clear STATUS register that store clears every flag that happened to be set. Write mmio_wr32(&TIMER0->STATUS, 1u << 3) instead.
  • Torn 64-bit read. Reading CNTLO then CNTHI as two loads can be interrupted. Trace: CNTLO reads 0xFFFFFFFF; the counter ticks; CNTHI reads 0x00000001. Combined (HI<<32)|LO = 0x00000001FFFFFFFF, true value 0x0000000100000000: off by 0xFFFFFFFF. Fix: read HI, LO, HI again and retry if HI changed, or use the hardware latch (reading CNTLO latches CNTHI).
  • Wrong half order. If the peripheral latches on read of CNTLO, reading CNTHI first pairs a stale high half with a fresh low half. The order is part of the register contract, not a style choice.
  • Unaligned fault. On Cortex-M an unaligned access to Device memory raises UsageFault (UNALIGNED) when SCB->CCR.UNALIGN_TRP is set; otherwise it may split into two bus cycles. Keep every access naturally aligned.
  • Reserved adjacent register. A struct spanning a gap, or a read-modify-write on a word holding reserved bits, writes back whatever was read and can clear status or trigger a side effect.

Trade-offs

Raw volatile uint32_t * everywhere is fastest and adds no abstraction, but nothing checks layout. Accessor macros give one place to audit and inline to nothing at -O1 and above. A vendor HAL is portable but hides the width and can emit subword accesses. Pick accessors when the register set is shared across drivers; raw pointers are fine for one-off bring-up.

Validation

  1. Disassemble: arm-none-eabi-objdump -d build/*.o | grep -A2 40001000 and confirm each register address is touched by exactly one LDR/STR of the right width. No LDRB/STRB, no LDM/STM splitting the 64-bit read.
  2. Runtime: write 0xFFFFFFFF to CTRL and read back; set one bit in STATUS and confirm only that flag clears; read the 64-bit counter 10^6 times while it runs and assert monotonicity.
  3. Fault test: enable UNALIGN_TRP, perform a deliberately unaligned read, confirm the UsageFault handler fires.
failuredetection
byte store on 32-bit regobjdump shows STRB at the register address
torn 64-bit readmonotonicity assert fails under load
wrong half ordercounter jumps backwards on wrap
unaligned accessUsageFault handler entry
reserved bits writtenstatus flags clear unexpectedly after an unrelated write

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate an MCU/MMIO implementation for endianness.

Answer

Assume a little-endian Cortex-M4 (ARMv7-M; endianness is sampled at reset and reflected in AIRCR.ENDIANNESS, bit 15) driving a fixed-function peripheral whose register map is big-endian. The design decision is who owns the byte swap, the SoC interconnect or the driver, and the validation problem is that a read-back through the same path cannot distinguish a correct path from a double swap.

Design: one owner, named accessors. Put the swap in the driver, because the driver is reviewed and versioned while the interconnect wiring usually is not. On a little-endian CPU, a big-endian device register needs a byte reversal on every access:

C
// arm-none-eabi-gcc 12.x, Cortex-M4, little-endian
#include <stdint.h>
#define REG32(a) (*(volatile uint32_t *)(a))

static inline uint32_t rd_be32(uintptr_t a) { return __builtin_bswap32(REG32(a)); }
static inline void     wr_be32(uintptr_t a, uint32_t v) { REG32(a) = __builtin_bswap32(v); }

__builtin_bswap32 lowers to a single REV instruction on Cortex-M3/M4: one cycle, no library call.

Trace. Device control register at 0x4000_0000, device defines value 0x0000_0001 as "enable" (bit 0). wr_be32(0x40000000, 1) computes bswap32(1) = 0x01000000 and stores it little-endian, so the bytes at 0x00..0x03 are 00 00 00 01. The device reads offset 0x00 as its MSB: 0x00, and offset 0x03 as its LSB: 0x01 → 0x0000_0001. Correct. Without the swap the CPU stores 01 00 00 00, the device reads 0x0100_0000, and bit 24 is set instead of bit 0.

The double-swap blind spot. If the interconnect is word-invariant (it already permutes byte lanes so the 32-bit value is preserved), the device sees 0x0100_0000 again: the two swaps cancel. Reading the same register back through the same accessor returns 0x0000_0001 and looks perfect. You cannot detect this with a write/read of one register. Read a read-only ID register whose value the datasheet fixes, say 0x0000_1234:

wiringraw read of IDcorrect access
byte-invariant (no interconnect swap)0x3412_0000swap in software
word-invariant (interconnect swaps)0x0000_1234raw access, no swap

Exactly one column matches the datasheet; that tells you which owner is real.

DMA descriptors. Descriptor fields are memory structures, and the DMA engine may define them big-endian independently of the register map. A length of 256 written little-endian as 0x0000_0100 is read by a big-endian DMA as 0x0001_0000 = 65536: a 256× overrun. Detect it with a guard byte after the buffer and the DMA's transferred-count register, not by trusting the descriptor you wrote.

Bit numbering is not byte order. After correct byte handling, field [31:24] is still [31:24] and bit 0 is still the LSB of the 32-bit value. Reversing bitfields because "big-endian means MSB first" is a separate bug.

Trade-offs. Driver-side swap costs one REV per access and is portable to a big-endian core; word-invariant wiring costs nothing at runtime but hides the swap, breaks silently if a driver adds its own, and is a board decision that may not survive a respin. Choose driver-side when the same driver must run on both endiannesses or the device is fixed IP; choose wiring-side only when the access is per-packet and the SoC documentation states it.

Validation. _Static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) at compile time; the ID-register read at boot; an asymmetric pattern (0x1234_5678, all four bytes distinct) written to a scratch register and read back through a different register; a DMA round-trip with a guard byte; and a bus trace to see the actual bytes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and validate an MCU/MMIO implementation for reserved bits.

Answer

Assumptions

32-bit MMIO, single core, registers documented in a reference manual (RM) that marks reserved bits either "keep at reset value" or "write as 0". Header is generated or hand-checked against that RM. Example below is STM32F4 (RM0090): the masks and the W1C behaviour are from that manual, not invented.

Core answer

Design: one header per peripheral, one _Pos/_Msk pair per documented field, and no named field for reserved bits. Access goes through a small set of inline helpers, not raw REG |= at call sites. The helpers encode the access policy per register class, so the policy lives in one place instead of in every driver.

Validate in three layers: a CI static check that every write is either a full-word header constant or a masked helper call; a read-back assertion that reserved bits still equal their reset value after each write; and a boot-time snapshot diff against the header's reset constants.

Design artefact

C
/* uart.h — masks checked against STM32F4 RM0090 */
#define UART_CR1_UE_Pos   13u
#define UART_CR1_UE_Msk   (1u << UART_CR1_UE_Pos)
#define UART_CR1_TE_Pos   3u
#define UART_CR1_TE_Msk   (1u << UART_CR1_TE_Pos)

static inline void uart_cr1_set(uint32_t msk) { UART1->CR1 |=  msk; }
static inline void uart_cr1_clr(uint32_t msk) { UART1->CR1 &= ~msk; }

/* EXTI_PR is rc_w1: write 1 clears, write 0 leaves unchanged. */
static inline void exti_pr_clear(uint32_t msk) { EXTI->PR = msk; }

Register classes and policy

classRM wordingaccess policy
RW with reserved"reserved, keep at reset value"masked RMW; reserved bits preserved
W1C (rc_w1)"write 1 to clear"write-only, never RMW
RO"read-only"read only; writes ignored
WO"write-only"full word from header constant

Trace: why RMW breaks a W1C register

EXTI_PR = 0x0000_000C: lines 2 and 3 pending. Code wants to clear line 2 only.

  • Buggy: EXTI->PR |= (1u << 2) reads 0x0000_000C, ORs 0x0000_0004 → 0x0000_000C, writes it. Both lines clear. Line 3's interrupt is lost.
  • Correct: EXTI->PR = (1u << 2) writes 0x0000_0004. Only line 2 clears; line 3 stays pending.

The mechanism: on a W1C register the read value is the set of pending flags, so OR-ing a mask back in clears every flag that was already set. The write-only helper removes the read entirely.

Failure modes and detection

  • RMW on W1C → lost interrupts. Detect: soak test comparing interrupt count against expected; the read-back check also flags bits cleared that were never targeted.
  • Wrong reset assumption → header says reset 0x0, silicon resets to 0x0000_0100. Detect: boot snapshot diff against header constants.
  • Stale header after a silicon revision → field moved. Detect: write a known value, read back, compare; CI diffs the header against the current RM.
  • Undocumented bit copied from a forum → writing it changes behaviour. Detect: reserved-bit read-back assertion fails.

Trade-offs

Strict masked RMW is safe against reserved bits but costs an extra read per write (one more AHB transaction: it matters inside an ISR) and is wrong on W1C. Full-word writes are atomic and fast but clobber reserved bits if the header is stale. Criteria: full-word writes only for registers with no W1C bits and an RM-generated header; masked RMW for mixed RW registers; write-only for W1C. Don't apply one policy to all four classes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and validate an MCU/MMIO implementation for write-one-to-clear.

Answer

Assumptions: 32-bit MMIO registers on an ARM Cortex-M (STM32F4, EXTI_PR at 0x40013C14), C11, GCC arm-none-eabi, volatile access. W1C semantics: writing 1 to a bit clears it, writing 0 leaves it unchanged.

Core answer (first 90 seconds). A write-one-to-clear status register is cleared by storing a 1 to the bit you serviced; storing 0 to a bit does nothing. So the correct clear is a single store of a mask containing exactly the bits you handled: no read-modify-write. That store is one 32-bit AHB write, atomic, and because you never write a 1 to a bit you did not read as set, an event that asserts between your read and your write is never lost. The classic bug is reading the whole register, masking off your bit, and writing the result back: that writes 1 to every other pending bit and silently clears events you never handled.

C
#define EXTI_PR (*(volatile uint32_t *)0x40013C14U)
#define MY_MASK 0x1U   /* bit 0 = the line this handler services */

void EXTI0_IRQHandler(void) {
    uint32_t pending = EXTI_PR;           /* snapshot */
    uint32_t handled = pending & MY_MASK; /* only bits I own */
    EXTI_PR = handled;                    /* write 1 to clear exactly those */
    if (handled) { /* service */ }
}

The buggy version, for contrast:

C
uint32_t v = EXTI_PR;
v &= ~MY_MASK;   /* clear my bit in the copy */
EXTI_PR = v;     /* writes 1 to every OTHER pending bit -> clears them */

Trace. EXTI_PR = 0x0000_0005 (bits 0 and 2 pending), handler owns bit 0.

  • Correct: read 0x5, handled = 0x1, write 0x1 → bit 0 cleared, bit 2 survives. EXTI_PR = 0x4.
  • Buggy: read 0x5, v = 0x4, write 0x4 → bit 2 cleared. EXTI_PR = 0x0. Event on bit 2 lost.
  • Concurrent arrival: read 0x1, then hardware asserts bit 2 → 0x5. Correct writes 0x1; bit 2 survives and re-enters the ISR. Buggy writes 0x4; bit 2 is cleared and lost.

Validating it. Assert two lines, service one, then check the other's pending bit is still set and its ISR still fires. To catch the RMW window specifically, inject the second event from a debugger write to EXTI_SWIER (software interrupt) between the read and the store: the buggy handler drops it, the correct one re-triggers.

Failure modeDetectionCost
RMW clears unrelated eventsSWIER injection in the read→write windowLost interrupts, silent
Wrong polarity (W1S vs W1C)Compare against reference manual per registerClears the wrong thing
Mixed RW/W1C in one wordWhole-word RMW clears set status bitsConfig corruption or lost events
Compiler bitfield RMWDisassemble the field assignmentReintroduces the hazard
Stale snapshot assumed currentEvent after read not in snapshotRe-triggers (correct) or lost (read-back)

Mixed RW fields. If bits [15:8] are W1C status and [7:0] are RW config, a whole-word RMW writes 1 to any set status bit and clears it. Keep config in a shadow variable and write shadow_cfg | status_to_clear.

Compiler bitfields. struct { uint32_t flag:1; }: assigning the field can emit a load-modify-store of the whole word, reintroducing the hazard. Use volatile uint32_t and explicit masks.

Wrong polarity. NVIC ISER is write-1-to-set; ICPR is write-1-to-clear. Writing 1 to ISER enables, to ICPR clears pending. Mixing them clears the wrong thing: check the reference manual per register.

Trade-offs. Direct mask write is right when you know which bits you handled, which is the normal ISR case. Read-back write-back is only safe when you intend to clear all pending bits. Do not use direct mask write on a mixed RW/W1C register without a shadow copy of the RW fields.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

Design and validate an MCU/MMIO implementation for read-to-clear.

Answer

Core answer. Assume a 32-bit MCU, a peripheral whose data or status register clears or pops on read, and a driver that must not lose events. The design rule: exactly one function in the firmware is allowed to read that register, and it copies the value into a RAM shadow before returning. Everything else (logging, telemetry, the debugger's view, the test harness) reads the shadow, never the register. If the silicon documents a non-destructive mirror or peek register, use that instead of a shadow; if it doesn't, the shadow is mandatory. Validation is then a read-count check: the number of bus reads of that address must equal the number of events, proven with a trace, not by inspection.

Design. For a FIFO that pops on read (ARM PL011 UARTDR at base+0x00; FR at +0x18, bit 4 RXFE = RX FIFO empty), a single shadow byte is wrong: it keeps only the last entry. Shadow into a ring buffer:

C
#define UART0_DR (*(volatile uint32_t *)0x40001000u)
#define UART0_FR (*(volatile uint32_t *)0x40001018u)
#define FR_RXFE  (1u << 4)

static volatile uint8_t  rx_ring[64];
static volatile uint16_t rx_head, rx_tail;

void uart_rx_isr(void) {                 // sole reader of UART0_DR
    while (!(UART0_FR & FR_RXFE)) {
        uint16_t next = (uint16_t)((rx_head + 1u) & 63u);
        if (next == rx_tail) { (void)UART0_DR; continue; }  // full: pop and drop
        rx_ring[rx_head] = (uint8_t)(UART0_DR & 0xFFu);
        rx_head = next;
    }
}

Trace, FIFO holding 'A' then 'B', head=tail=0: FR.RXFE=0 → next=1≠0 → ring[0]='A', head=1. FR.RXFE=0 → next=2 → ring[1]='B', head=2. FR.RXFE=1 → exit. Consumer reads ring[0]='A', ring[1]='B'. Both preserved. A single-byte shadow would have returned only 'B'.

Map the region Device-nGnRnE (Cortex-A) or Device (Cortex-M). volatile stops the compiler reordering or eliding the read; the memory attribute stops the CPU speculating, merging or replaying it. Without the attribute a speculative load can clear a flag that no code asked to clear.

Alternatives.

optionwhen it winscost
single owner + RAM shadowno mirror register existsRAM, one copy per event
documented peek/mirror registersilicon provides onenone; verify it is truly non-destructive
write-1-to-clear insteadhardware offers W1C (e.g. NVIC ICPR)none; reads become harmless
disable IRQ and polllow rate, latency-tolerantloses events during the disabled window

Prefer W1C where the silicon offers it: a read is then idempotent and the whole problem disappears. Read-to-clear is the fallback.

Validation. (1) Static: the register address literal appears in exactly one translation unit; check the map file. (2) Destructive test: read the register twice, assert the second read is empty/zero and the first value is gone. (3) Read-count: instrument with ITM/ETM or a bus analyzer, assert reads == events. (4) Debugger: halt and read the address in the debugger's memory window. It is a real bus access and will clear; confirm that, then inspect the RAM shadow instead. (5) Harness: the test poll must call the owner function, never touch the address.

Failure modes: a double read in a log statement loses a FIFO entry; a debugger watch window silently drains the FIFO; a condition like if (REG & MASK) in a log path clears the flag it tests; a speculative load clears a flag; a test harness that polls the raw address destroys the data it is checking.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate an MCU/MMIO implementation for read-modify-write.

Answer

Assume an ARM Cortex-M MCU (e.g., STM32F4 at 168 MHz) with memory-mapped peripherals. The goal is to update one bit in a control register without disturbing other bits or losing concurrent hardware updates.

Core answer: Use atomic set/clear aliases when available. On STM32 GPIO, write to BSRR (offset 0x18) to set or clear a pin in one store: GPIOB_BSRR = (1U << 5); sets PB5, GPIOB_BSRR = (1U << (5 + 16)); clears it. No read-modify-write. If the register lacks such aliases, use a critical section: disable interrupts, read, modify, write, re-enable. Never use plain read-modify-write on W1C registers or when hardware can set bits asynchronously.

Why plain RMW fails: read returns a snapshot. Hardware sets a bit between read and write. Write writes back the old value, clearing the new bit. Trace: ODR = 0x0000. Want to set bit 5. Read ODR -> 0x0000. Hardware sets bit 3 -> ODR = 0x0008. Software ORs 0x20 -> 0x0020. Write 0x0020 -> ODR = 0x0020. Bit 3 lost.

Alternatives and trade-offs:

| Method | Atomic? | Protects against ISR? | Protects against DMA/other core? | Cost | | BSRR | Yes | Yes | Yes | 1 store | | Bit-band | Yes | Yes | Yes | 1 store | | Critical section | Yes (for ISR) | Yes | No | ~10–20 cycles | | Plain RMW | No | No | No | 1 load + 1 store |

Bit-banding is available on Cortex-M3/M4, not M0/M0+/M7. Alias address for GPIOB ODR bit 5: 0x42000000 + (0x40020414 - 0x40000000)32 + 54 = 0x42408294. Write 1 to set, 0 to clear. Critical section does not protect against DMA or other cores; for multi-core, use LDREX/STREX or a hardware semaphore (e.g., STM32 HSEM). For W1C, write only the bits to clear: EXTI_PR = mask; not read-modify-write.

Validation: Toggle the target bit at 1 kHz while a timer toggles an adjacent bit. Monitor both with a logic analyzer. If the adjacent bit glitches, you have a lost update. For W1C, set two flags in EXTI_PR, then write only one flag to clear; read back and confirm the other flag is still set. For critical section, measure interrupt latency: toggle a pin before and after __disable_irq()/__enable_irq() and measure with an oscilloscope. On a 168 MHz STM32F4, the sequence adds roughly 10–20 cycles (60–120 ns). If your real-time deadline is tighter, use BSRR or bit-banding.

Failure modes: Lost update (detect by reading back after write and comparing, or by logic analyzer). W1C replay: reading a W1C register and writing back the same value clears all flags that were set, including unintended ones. Detect by checking that only intended flags are cleared. Reserved bits: writing 1 to reserved bits may cause undefined behavior; always mask. Detect by reading back and checking reserved bits remain 0. Hardware sets between read/write: as above. Bit-band alias not available: compile-time check or runtime check of CPU ID.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate an MCU/MMIO implementation for atomic aliases.

Answer

Assumptions: Cortex-M4 with bit-banding, peripheral register CTRL at 0x40020000, bit 3 is EN. If the part lacks bit-banding, use the vendor's set/clear register instead.

Design: map each bit to a 32-bit alias word. Formula: alias = 0x42000000 + ((addr - 0x40000000) * 32) + (bit * 4). For CTRL bit 3: 0x42000000 + (0x20000*32) + 12 = 0x4240000C. Write 1 sets, write 0 clears. That is one store instruction; the bus does the bit update, so no software read-modify-write.

C
#include <stdint.h>
#define CTRL_ADDR 0x40020000u
#define PERIPH_BB_BASE 0x40000000u
#define PERIPH_BB_ALIAS 0x42000000u
#define BB_WORD(addr, bit) \
  (*(volatile uint32_t *)(PERIPH_BB_ALIAS + \
    (((uint32_t)(addr) - PERIPH_BB_BASE) * 32u) + ((bit) * 4u)))

static inline void en_set(void)   { BB_WORD(CTRL_ADDR, 3) = 1u; }
static inline void en_clear(void) { BB_WORD(CTRL_ADDR, 3) = 0u; }

Validation: three checks. 1) Address arithmetic: static assert BB_WORD(CTRL_ADDR,3) == 0x4240000C. 2) Polarity and isolation: CTRL=0; en_set(); read CTRL, expect 0x00000008; en_clear(); expect 0. 3) Concurrency: loop 10k times: CTRL=0; main sets bit 0 via alias; SysTick ISR sets bit 1 via alias; read CTRL, expect 0x00000003. If either bit is lost, the alias is not atomic or the offset is wrong.

Trace: CTRL=0. BB_WORD(CTRL_ADDR,3)=1 -> bus writes bit 3 -> CTRL=0x00000008. BB_WORD(CTRL_ADDR,3)=0 -> CTRL=0x00000000. If the formula used bit*1, bit 3 alias would be 0x42400003, unaligned and likely faulting or hitting the wrong bit.

Alternatives: On parts without bit-banding (Cortex-M0/M0+, Cortex-M7, ARMv8-M), use vendor set/clear registers. STM32 GPIO BSRR: write (1<<bit) to set, (1<<(bit+16)) to clear; one store, atomic for that port. Or LDREX/STREX loop on the word, but exclusive access may not be supported on peripheral memory. Or disable interrupts around a normal RMW; portable but blocks interrupts and does not protect against DMA or another core.

Failure modes: wrong alias offset writes an adjacent bit or register; detect by readback and static assert. Swapped set/clear polarity clears when you meant to set; detect by readback. Simultaneous actors doing normal RMW lose updates; detect by the two-context stress test. Cross-register state, e.g. setting EN before clock enable, causes a bus fault or no effect; detect by sequencing the clock enable first. Unsupported derivative has no bit-band alias; access faults or is ignored; detect by reading the reference manual and a boot-time alias probe.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

How do read-sensitive and write-sensitive side effects in MMIO registers impact debugging and compiler optimization, and how are they managed in driver code?

Answer

Unlike normal SRAM, Memory-Mapped I/O (MMIO) registers map bus access directly to hardware state machines. Read-sensitive registers trigger an internal state transition on a read (such as advancing a FIFO read pointer, popping a hardware queue, or clearing interrupt status in a read-on-clear status register). Write-sensitive registers commit commands, trigger DMA transfers, or clear status bits (such as write-one-to-clear flags).

Impact on Compiler Optimizations

Compilers assume memory adheres to ordinary memory semantics (idempotent reads, observable writes only if preserved across sequence points). Under optimization (-O2/-O3), a compiler will:

  1. Eliminate duplicate loads (Common Subexpression Elimination), reading a status flag or FIFO data register once and reusing the register value, failing to observe hardware changes.
  2. Reorder memory accesses across sequence points if aliases are not proven.
  3. Omit writes that appear dead or overwritten.

To prevent this, CMSIS peripheral definitions declare register elements as __IO (defined as volatile uint32_t). The volatile qualifier forces the compiler to emit an exact load or store instruction matching access width and prohibits caching or omitting accesses.

Impact on In-Circuit Debuggers

Debuggers (GDB, OpenOCD, J-Link) probe target memory via background AP/DAP read requests over SWD/JTAG to populate Watch windows, Register inspectors, or memory dumps.

  • Probing a read-on-clear interrupt register consumes the flag before the ISR executes, silently dropping interrupts.
  • Probing a FIFO data register advances the hardware read pointer, discarding incoming payload bytes.

Defensive Driver Implementation Patterns

To handle side-effect registers safely:

  1. Local Shadow Caching: For read-to-clear status registers, read the register exactly once into a local stack variable, then evaluate flags against the local copy.
  2. Avoid Read-Modify-Write (RMW) on Mixed Registers: If a control register contains write-to-clear status flags or write-triggered pulses mixed with configuration bits, a standard |= RMW will clear active flags or re-trigger actions. Use dedicated set/clear registers (atomic aliases) or mask out side-effect bits.
  3. Memory Ordering: On Cortex-M, MMIO addresses are mapped as Device memory (Device-nGnRnE or Device-nGnRE), which enforces access size and prevents speculative execution. When coordinating MMIO writes with peripheral DMA buffers in normal RAM, enforce ordering using Data Synchronization Barriers (__DSB()).
C
/* Example: STM32/CMSIS-Core Safe Status Read & FIFO Pop */
#include "stm32f4xx.h"

void USART1_IRQHandler(void) {
    /* Read-sensitive status register: read ONCE to shadow variable */
    uint32_t isr_status = USART1->SR;

    if (isr_status & USART_SR_RXNE) {
        /* Accessing DR clears RXNE and pops hardware FIFO/holding register */
        uint8_t byte = (uint8_t)(USART1->DR & 0xFF);
        process_byte(byte);
    }

    if (isr_status & USART_SR_ORE) {
        /* Overrun error clear requires reading SR then reading DR */
        volatile uint32_t dummy = USART1->DR;
        (void)dummy;
        handle_overrun();
    }
}
Register InteractionHardware BehaviorFailure ModeMitigation Pattern
Read-on-clear StatusHardware clears flag on bus readDebugger reads memory window, clearing flag before CPU ISR runsMark address as non-inspectable in GDB/SVD; shadow register locally in ISR
FIFO Data PopRead cycle increments read pointerBlind memory dump discards incoming stream dataOmit data registers from debugger peripheral view
Write-1-to-Clear (W1C)Writing '1' clears bit, '0' no-opRead-modify-write (`=`) inadvertently clears concurrent pending interrupts

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Design and validate an MCU/MMIO implementation for memory barriers.

Answer

Assumptions: ARMv7-M Cortex-M7 at 600 MHz, D-cache on, MPU maps 0x4000_0000 as Device-nGnRnE, SRAM as Normal write-back, GCC 12 -O2, CMSIS intrinsics. The design starts by classifying the ordering: compiler, CPU, completion, instruction stream. They are not interchangeable.

barrierwhat it doeswhen to use it
compiler asm volatile("" ::: "memory")stops the compiler moving memory ops across the pointaround MMIO in C, but emits no instruction
DMBorders memory accesses before/after it; does not wait for completionproducer/consumer flag, ordering between Normal and Device
DSBwaits for prior explicit memory accesses to completebefore a DMA doorbell, before power-down, after cache clean
ISBflushes the pipeline and prefetch bufferafter MPU, cache, or vector-table changes

A concrete MMIO design: DMA reads a descriptor from SRAM, then the CPU writes a doorbell register.

C
struct __attribute__((aligned(32))) desc {
    uint32_t src, dst, len, ctrl;
};
volatile struct desc *d = ...;
volatile uint32_t *doorbell = (uint32_t *)0x40001000;

d->src = ...; d->dst = ...; d->len = ...; d->ctrl = DESC_OWN;
SCB_CleanDCache_by_Addr((uint32_t *)d, sizeof *d); /* if D-cache on */
__DSB();          /* descriptor writes complete */
*doorbell = 1;    /* Device-nGnRnE MMIO */
__DSB();          /* only if the next step needs the doorbell completed */

volatile stops the compiler caching the register, but it does not order CPU accesses. DMB before the doorbell would order the descriptor writes before it, but would not wait for them to complete; a slow peripheral bus can still see the doorbell first. DSB is the completion barrier. If D-cache is enabled, DSB alone is not enough: the descriptor must be cleaned first, or DMA reads stale SRAM. After DMA writes to SRAM, invalidate the cache before the CPU reads it.

Validation is two-master and fault-injected. Static: arm-none-eabi-objdump -d must show dsb before the store to doorbell; the MPU config must show Device-nGnRnE for the peripheral and Normal write-back for SRAM; -S must show the compiler barrier. Dynamic: CPU writes a 1 KB descriptor, DMA copies it to a second SRAM buffer, run 10^6 iterations with D-cache on. Toggle a GPIO before the doorbell and in the DMA IRQ. On a scope, the doorbell edge must come after the last descriptor write. Without DSB, the test corrupts intermittently; without cache clean, DMA reads a stale pattern. Fault injection: compile with the DSB removed. If the test still passes, increase bus load or enable D-cache until it fails, otherwise the test is not sensitive.

Trade-offs: DSB stalls the core until prior writes complete. Hypothetical: if the peripheral bus is 50 MHz, one wait state is 20 ns; a DSB waiting for two writes costs about 40 ns. DMB is usually cheaper because it orders without waiting. Over-barriering every register write can add measurable interrupt latency; measure with DWT CYCCNT. Use the narrowest barrier at the protocol boundary. DMB is enough for ordering; DSB when completion is required; ISB only for instruction-stream changes.

failuresymptomdetection
barrier omittedDMA reads stale descriptor; doorbell before dataobjdump missing DSB; scope GPIO; stress with D-cache
wrong kind (DMB instead of DSB)intermittent on slow bus; doorbell before write completesbus trace; replace with DSB and rerun
compiler barrier onlyworks at -O0, fails at -O2objdump shows no DMB/DSB; run optimized
cache maintenance confusedDMA reads stale (need clean before); CPU reads stale (need invalidate after)enable D-cache; compare; align to 32-byte lines
excessive barriersinterrupt latency and throughput dropDWT CYCCNT; compare boundary-only vs every write

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate an MCU/MMIO implementation for posted writes.

Answer

Assumptions first. "Posted" means the store retires at the CPU before the peripheral has seen it: true for PCIe MMIO, and for AHB writes that cross a posted bridge. I'll assume a Cortex-M4 with the peripheral on AHB at a fixed base, and that the flush must be safe to call from an ISR.

Core answer. Design the write path so every store that must be visible before a later action is followed by a flush, and pick the flush primitive from the bus, not from habit. Two primitives exist:

  • __DSB(): architectural. It stalls until all prior explicit memory accesses complete at the CPU/bus interface. Cheap on Cortex-M, and it is what orders the write against events such as gating a clock or entering WFI.
  • Readback of a register in the same peripheral: bus-level. It forces a posted write through any bridge that DSB does not reach, because the read must be serviced by that peripheral after the write.

Use DSB alone when the peripheral sits directly on the AHB/APB. Use DSB plus a same-peripheral readback when the write crosses a posted bridge, because DSB only guarantees completion at the CPU interface, not at the far end.

C
/* Cortex-M4, CMSIS. Peripheral on AHB at 0x4001_0000. */
#define CTRL   (*(volatile uint32_t *)0x40010000u)  /* rw */
#define STATUS (*(volatile uint32_t *)0x40010004u)  /* r, no side effects */

static inline void ctrl_write_flush(uint32_t v)
{
    CTRL = v;        /* posted store */
    (void)STATUS;    /* readback, same peripheral: ordered after the store */
    __DSB();         /* nothing later is reordered before the store completes */
}

Trace: the store to CTRL is issued and retires. Device memory on Cortex-M is ordered, so the STATUS read cannot be observed before the CTRL write; the read is serviced by the peripheral, which forces the write through any bridge in between. Its data is discarded. DSB then holds until the CTRL write is complete at the bus, so a following clock-gate or WFI cannot race it.

flushwhat it guaranteescostwhere it fails
__DSB()prior writes complete at the CPU/bus interfacecheap on Cortex-Mwrite still posted in a downstream bridge
readback, same peripheralposted write reaches that peripheralone bus read: tens of ns on AHB, microseconds over PCIeregister is read-clear; read targets a different device
readback, different devicenothing—never flushes the target

PCIe has the same shape: a read to the same device is ordered after prior posted writes to that device; a read to another device is not.

Failure modes and how you catch them.

  • Readback register is destructive. Read-clear status registers (ST documents these as rc_w0/rc_r) clear a flag or pop a FIFO on read. Catch it by checking the access type in the reference manual, and by a test that reads the register twice and asserts the second value equals the first.
  • Wrong bridge. A readback to a register on a different bus segment does not flush the target. Catch it with a bus trace, or a test that writes then reads a downstream status with a known propagation delay.
  • Lock released early. Dropping the mutex before the flush lets another core observe stale state. Catch it with a two-core stress test under KCSAN/TSAN.
  • No timeout. Polling a status bit without a bound hangs forever on a dead device. Catch it with fault injection and a watchdog.
  • Simulator lacks posting. QEMU and ISS models make MMIO immediately visible, so the bug never reproduces. Catch it by running the test on silicon or a cycle-accurate model.

Validation. The test is: write CTRL, flush, then read a downstream status that only changes after the write lands, and assert it changed within a bounded poll. Run it on silicon, under a bus trace, and once with the readback register swapped for a read-clear one to prove the test catches the destructive case.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design and validate an MCU/MMIO implementation for address map.

Answer

Assumptions. STM32F407 (Cortex-M4F): 1 MB Flash at 0x08000000, 128 KB SRAM at 0x20000000, peripheral region from 0x40000000 (GPIOA at 0x40020000, RCC at 0x40023800), external SRAM on FSMC at 0x60000000. GNU Arm Embedded 10.3 with CMSIS device headers.

Core answer. One machine-readable map (YAML) is the source of truth. A generator emits three things from it: the linker script, the C header, and a boot self-test. Validation is static, the generator rejects overlapping or out-of-range regions, plus runtime, where the self-test reads registers with documented reset values and the MPU turns reserved holes into faults.

Mechanism. MMIO is not memory, and three properties drive the design.

Reads have side effects. Reading USART_DR pops the RX FIFO and clears RXNE. Any register-dump or logging path that touches DR silently eats a byte. The correct clear sequence is read SR, then read DR: reading DR alone leaves ORE set.

Access size is fixed by the peripheral. Most STM32 registers are word-only; a byte write to a 32-bit register is not guaranteed to land in the intended lane. Generate volatile uint32_t * accessors and never memcpy a struct over a peripheral block.

Alignment is mandatory. On Cortex-M4, unaligned accesses are permitted only to Normal memory. MMIO is Device memory, so an unaligned word access always raises a UsageFault: clearing SCB->CCR.UNALIGN_TRP does not change that. Packed structs over peripheral registers are the usual cause.

volatile constrains the compiler only. Add __DSB() between a configuration write and a read that depends on it.

Trade-offs. Generating from one map costs a build step and a ~100-line parser; it buys you no drift between linker, header and reference manual. Vendor CMSIS headers plus the vendor linker script are faster and correct for the reference board, and break the moment the board moves a peripheral or adds external memory. Generate when the board deviates; use vendor files otherwise.

Failure modes and detection.

FailureWhy it bitesDetection
Wrong device / family baseF1 peripheral base used on an F4 part; registers land on the wrong blockRead DBGMCU_IDCODE at 0xE0042000; DEV_ID (bits 11:0) is 0x413 for F407, 0x410 for F103
Peripheral clock gatedRegister reads back 0, writes vanishSelf-test enables RCC->AHB1ENR bit 0, then asserts GPIOA_MODER == 0xA8000000
Read-to-clear read twiceA log path reading USART_DR drops a received byteGenerated accessors expose DR only to the RX path; clear with SR-then-DR
Read-modify-write on a shared registerA read-modify-write on ODR loses a concurrent writeUse BSRR (offset 0x18); flag any read-modify-write on a peripheral register
Unaligned MMIO accessAlways a UsageFault on Device memoryUsageFault handler logs the stacked PC; build with -Wcast-align
Map overlapTwo peripherals claim one range; last writer winsGenerator check below fails the build
Reserved holeAccess to an unimplemented addressBusFault; MPU marks the hole no-access in debug builds
Boot alias0x00000000 aliases Flash (BOOT0=0) or system memory (BOOT0=1); the same code has two addressesAfter SystemInit assert SCB->VTOR == 0x08000000; never emit symbols based at 0x00000000

Artefacts.

Source of truth, map.yaml:

YAML
regions:
  - {name: flash, base: 0x08000000, size: 0x100000}
  - {name: sram,  base: 0x20000000, size: 0x20000}
  - {name: apb1,  base: 0x40000000, size: 0x8000}
  - {name: ahb1,  base: 0x40020000, size: 0x60000}
  - {name: fsram, base: 0x60000000, size: 0x100000}

Generator overlap check (Python 3.9, PyYAML 6):

Python
import sys, yaml
regions = sorted((r["base"], r["base"] + r["size"], r["name"])
                 for r in yaml.safe_load(open("map.yaml"))["regions"])
for (b1, e1, n1), (b2, e2, n2) in zip(regions, regions[1:]):
    if b2 < e1:
        sys.exit(f"overlap: {n1} [{b1:#010x},{e1:#010x}) vs {n2} [{b2:#010x},{e2:#010x})")
print(f"{len(regions)} regions, no overlap")

Linker script: the asserts that matter are the memory-fit ones; the peripheral map is checked by the generator, not by ld:

LD
MEMORY
{
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 1024K
  SRAM  (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
}
SECTIONS
{
  .text : { *(.text*) *(.rodata*) } > FLASH
  .data : { *(.data*) } > SRAM AT> FLASH
  .bss  : { *(.bss*) *(COMMON) } > SRAM
  ASSERT(SIZEOF(.text) + SIZEOF(.data) <= LENGTH(FLASH), "flash overflow")
  ASSERT(SIZEOF(.data) + SIZEOF(.bss) <= LENGTH(SRAM), "sram overflow")
}

Header:

C
#define PERIPH_BASE  0x40000000UL
#define GPIOA_BASE   0x40020000UL          /* AHB1 */
#define GPIOA_MODER  (*(volatile uint32_t *)(GPIOA_BASE + 0x00UL))
#define GPIOA_ODR    (*(volatile uint32_t *)(GPIOA_BASE + 0x14UL))
#define GPIOA_BSRR   (*(volatile uint32_t *)(GPIOA_BASE + 0x18UL))

Self-test:

C
#include <stdint.h>
#define DBGMCU_IDCODE (*(volatile uint32_t *)0xE0042000UL)

void map_selftest(void) {
    RCC->AHB1ENR |= (1u << 0);      /* GPIOA clock */
    __DSB();                        /* let the write complete before reading */
    if ((DBGMCU_IDCODE & 0xFFFu) != 0x413u) fault(FAULT_WRONG_DEVICE);
    if (GPIOA_MODER != 0xA8000000u)         fault(FAULT_GPIOA_RESET);
}

The map is validated when the generator reports no overlap, both link asserts pass, and the self-test reads 0x413 and 0xA8000000.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design and validate an MCU/MMIO implementation for Harvard behavior.

Answer

Core answer (first 90 seconds). "Harvard behavior" means the core can issue an instruction fetch and a data access in the same cycle because they leave through different buses to different memories. On ARMv7-M (Cortex-M7) that split is physical: the I-Code bus fetches from 0x0000_0000–0x1FFF_FFFF, the D-Code bus carries data loads from that same code region, and the System bus serves SRAM (0x2000_0000+) and peripherals (0x4000_0000+). Cortex-M7 adds separate 16 KB I- and D-caches plus ITCM/DTCM. The design job is to place code, place MMIO, and set permissions so the two paths never contend for the same resource.

Assumptions: Cortex-M7 at 480 MHz (STM32H743-class), code resident in flash, DMA-driven peripherals, MMIO at 0x4000_0000.

Design. Three decisions decide everything.

  1. Code placement. Flash fetch costs wait states set by FLASH_ACR.LATENCY (4 WS at 480 MHz on VOS0 for this part; always read the latency table for your voltage scale). Prefetch (FLASH_ACR.PRFTEN) and the I-cache hide that for straight-line code; a taken branch exposes it. If jitter matters, copy the hot loop into ITCM at boot and run it at 1 cycle.

  2. MMIO attributes. Peripherals must be Device memory, never cacheable, and execute-never. Configure an MPU region:

C
// MMIO 0x4000_0000, 512 MB, Device, XN, priv RW
MPU->RBAR = 0x40000000U | (1U << 4) | 1U;  // base | VALID | region 1
MPU->RASR = (1U << 28)   // XN
          | (1U << 24)   // AP = 0b001: priv RW, unpriv no access
          | (0U << 19)   // TEX = 0b000
          | (0U << 18)   // S = 0
          | (0U << 17)   // C = 0
          | (1U << 16)   // B = 1  -> Device
          | (28U << 1)   // SIZE = 28 -> 512 MB
          | 1U;          // ENABLE

RBAR reads back 0x40000011; RASR reads back 0x11010039.

  1. Executable permissions. The data region gets XN set; only the code region is executable. A corrupted function pointer then raises a MemManage fault instead of executing garbage.

Trade-off: ITCM vs I-cache.

ITCM/DTCMI-cache (16 KB on M7)
latency1 cycle, deterministichit 1 cycle; miss = flash latency + refill
code updatecopy at boot, no invalidationmust invalidate after any flash write
costconsumes SRAM, fixed sizetransparent, but jitter on miss
use whenhard real-time, tight jitter budgetlarge code, throughput-oriented

Validation. Static: read back MPU_RBAR and MPU_RASR and confirm the MMIO region is Device and XN. Dynamic: bracket a known loop with DWT_CYCCNT and compare ITCM-resident vs flash-resident execution. Coherency: have DMA write a buffer the CPU has cached, then read it back. Stale data means you need SCB_CleanDCache_by_Addr / SCB_InvalidateDCache_by_Addr around the transfer. Fault injection: jump to a data address and confirm a MemManage fault fires.

Failure modes and detection.

  • Code update without cache maintenance. After a flash program, the I-cache still holds the old instructions. Detect by checksumming the region against the image; fix with SCB_InvalidateICache() after the write completes.
  • Flash latency mis-set. Wrong FLASH_ACR.LATENCY gives intermittent fetch corruption at temperature/voltage extremes. Detect with a flash-readback CRC at boot.
  • DMA/CPU cache incoherency. DMA and CPU disagree on a buffer. Detect with a write-then-read test around the transfer.
  • Debugger timing. Halting stops DWT_CYCCNT and the core clock domain, so cycle counts taken under the debugger are wrong. Detect by comparing attached vs free-running measurements.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design and validate an MCU/MMIO implementation for linker script.

Answer

What a strong candidate says first

A linker script is the contract between the toolchain's abstract sections and the chip's physical address map. Designing one means fixing the memory regions, deciding where each output section runs (VMA) and where it is stored (LMA), and exporting the symbols the C startup and drivers read. MMIO touches it in two places only: reserving the peripheral address range so no allocated section can land there, and exporting peripheral base addresses so the script and the headers cannot drift apart. Validating it means build-time assertions, a startup trace, and CI checks on the produced image: a code review proves nothing.

Assumptions: bare-metal Cortex-M, STM32F407 (1 MB flash at 0x08000000, 112 KB SRAM at 0x20000000, 64 KB CCM at 0x10000000, peripherals from 0x40000000), GNU ld, arm-none-eabi-gcc 13.

The script

LD
MEMORY
{
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 1024K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 112K
  CCM   (rwx) : ORIGIN = 0x10000000, LENGTH = 64K
  PERIPH(rw)  : ORIGIN = 0x40000000, LENGTH = 512M
}
SECTIONS
{
  .isr_vector : { KEEP(*(.isr_vector)) } > FLASH
  .text : { *(.text*) *(.rodata*) } > FLASH
  .data : { _sdata = .; *(.data*) . = ALIGN(4); _edata = .; } > RAM AT> FLASH
  _sidata = LOADADDR(.data);
  .bss (NOLOAD) : { _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); _ebss = .; } > RAM
  .dma (NOLOAD) : ALIGN(32) { _sdma = .; *(.dma) _edma = .; } > RAM
  _estack = ORIGIN(RAM) + LENGTH(RAM);
}
PROVIDE(GPIOA_BASE = 0x40020000);
PROVIDE(RCC_BASE   = 0x40023800);

Why each piece works

> RAM AT> FLASH gives .data a VMA in RAM and an LMA in flash; LOADADDR(.data) is the flash address the startup copy reads from. NOLOAD keeps .bss and .dma out of the load image: they cost zero flash bytes, but nothing zeroes them, so .dma is uninitialized by design and .bss is zeroed by the loop below, not by the loader. KEEP stops --gc-sections from discarding the vector table. ALIGN(32) on .dma satisfies the 32-byte DMA burst requirement.

Startup, traced for a build with 8 KB of .data and 12 KB of .bss: for (p = &_sidata, q = &_sdata; q < &_edata; ) *q++ = *p++; copies 8 KB from the flash LMA to the RAM VMA; for (q = &_sbss; q < &_ebss; ) *q++ = 0; zeroes 12 KB. If AT> FLASH is missing, LMA == VMA == 0x20000000 and the first loop copies RAM onto itself: the classic "data load image wrong".

MMIO: PERIPH is declared so the map is documented and ORIGIN(PERIPH) is assertable, but declaring it does not by itself stop placement. The guard is that no output section targets it, plus a CI check that no allocated symbol falls in 0x40000000–0x5FFFFFFF. The Cortex-M default map already marks that range Device, so no MPU region is needed for ordering; MPU is used to make it XN or to guard the stack.

Trade-offs

One script per board versus one parameterised with --defsym: per-board scripts are readable but drift when the map changes; parameterised scripts hide the map behind build flags. Decide by board count: under three, separate scripts. Peripheral bases in the script versus CMSIS headers: the script is a single source of truth but couples C to the linker; headers are conventional but can disagree with the map. Pick one and assert the other against it.

Failure modes and detection

failurehow it happensdetection
flash overflow hiddenLENGTH(FLASH) set larger than the partld prints region FLASH overflowed by N bytes only if LENGTH is right; assert LENGTH against the part number in CI
data load image wrong.data missing AT> FLASHobjdump -h shows LMA == VMA; startup copy reads uninitialized RAM
DMA alignmentbuffer not 32-byte aligned, or placed in CCM (0x10000000), which DMA cannot reach_Static_assert(((uintptr_t)buf % 32) == 0); runtime check the address is in 0x20000000–0x2001BFFF
stack collisionheap grows up from _end, stack down from _estackfill stack with 0xA5A5A5A5 at boot, measure high-water mark; MPU guard below _estack
bootloader overwrittenapp linked at 0x08000000 while the bootloader owns 0x08000000–0x08007FFFORIGIN(FLASH) must be 0x08008000; assert SCB->VTOR == ORIGIN(FLASH)

CI

arm-none-eabi-size for the flash/RAM budget, objdump -h for LMA/VMA, nm for symbol ranges, and a link with --defsym overrides to prove the assertions fire. A build that links is not a build that boots.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and validate an MCU/MMIO implementation for vector table.

Answer

Assume ARMv7-M, Cortex-M3/M4/M7, one core, a bootloader at 0x08000000 and an app at 0x08020000, and I need the app's interrupts to work and to be able to prove they do. Here's the design, then how I validate it.

Design. The table is a const array in flash, in its own section: first word the initial MSP, second the reset handler, then the 14 core exceptions, then IRQ0..n. Each entry is 4 bytes. The linker places it aligned:

.isr_vector : ALIGN(128) { KEEP(*(.isr_vector)) } > FLASH

KEEP matters: without it --gc-sections drops the table. Alignment: ARMv7-M requires the table aligned to a power of two at least its size, minimum 128 bytes; VTOR bits [6:0] are SBZ. 64 vectors is 256 bytes, so align 256. The core TRM can extend this, so read it rather than assume 128.

Two conventions bite. First, every handler address must have bit 0 set: Cortex-M is Thumb-only and the core reads bit 0 as the Thumb state. A C function pointer already carries it; a hand-built table from symbol addresses must OR 1 in, or you get a UsageFault with CFSR.INVSTATE set. Second, the first word is loaded into MSP at reset; it must be a real RAM address, 8-byte aligned per AAPCS.

At runtime the app points VTOR at its own table before enabling interrupts:

C
#define SCB_VTOR (*(volatile uint32_t *)0xE000ED08)
SCB_VTOR = (uint32_t)vectors & 0xFFFFFF80u;

Then MPU: mark the table region privileged read-only, execute-never, so a stray write can't repoint a handler. Region size is a power of two ≥ 32 bytes, base aligned to size.

Validation. Read VTOR back and assert it equals the expected base and (base & 0x7F) == 0: a misaligned write is silently masked, so the table runs from the wrong place with no fault. Assert the first word is inside RAM and the reset vector is odd and inside flash. Then pend each IRQ in turn and check a per-handler counter, so a wrong entry is caught at bring-up, not in the field. Fill unused vectors with a default handler that records IPSR VECTACTIVE (ICSR bits [8:0], 0xE000ED04) instead of a weak infinite loop. A weak loop turns a missing ISR into a silent hang.

Failure modes and how I catch them:

failuredetection
initial SP badlockup on first exception; assert SP in RAM at reset
Thumb bit clearUsageFault, CFSR.INVSTATE (0xE000ED28 bit 17)
table misalignedread VTOR back, assert low 7 bits zero
VTOR not set after bootloader jumpread VTOR after jump; app IRQs hit bootloader handlers
weak default handlerdefault handler logs VECTACTIVE

Trade-off: flash table vs RAM table. Flash costs no RAM and can't be corrupted, but handlers are fixed at link time. A RAM table (copy at startup, VTOR to RAM) lets an RTOS or bootloader install handlers at runtime, at the cost of the table size, 256 bytes here, and a copy step. I pick flash unless something installs handlers dynamically. On Cortex-M0/M0+ there is no VTOR at all: the table is fixed at address 0, so relocation means memory remap (e.g. STM32 SYSCFG MEM_MODE) or copying the table into RAM at 0. That's the deciding constraint if the part is M0.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and validate an MCU/MMIO implementation for SystemInit.

Answer

Assume STM32F407, 8 MHz HSE crystal, 3.3 V, target 168 MHz. SystemInit runs before main, so no interrupts, no RTOS, no printf. The design must set flash wait states before raising the clock, enable HSE and PLL with timeouts, switch SYSCLK, and update SystemCoreClock.

Here's the core implementation (C99, checked against STM32F407 reference manual RM0090):

C
#define RCC_BASE        0x40023800UL
#define FLASH_R_BASE    0x40023C00UL
#define RCC_CR          (*(volatile uint32_t *)(RCC_BASE + 0x00))
#define RCC_PLLCFGR     (*(volatile uint32_t *)(RCC_BASE + 0x04))
#define RCC_CFGR        (*(volatile uint32_t *)(RCC_BASE + 0x08))
#define FLASH_ACR       (*(volatile uint32_t *)(FLASH_R_BASE + 0x00))

void SystemInit(void) {
    // 1. Enable HSE with timeout
    RCC_CR |= (1U << 16); // HSEON
    uint32_t timeout = 100000;
    while (!(RCC_CR & (1U << 17)) && --timeout); // HSERDY
    if (!timeout) { /* fallback to HSI */ }

    // 2. Set flash latency to 5 WS, enable prefetch, I-cache, D-cache
    FLASH_ACR = (5U << 0) | (1U << 8) | (1U << 9) | (1U << 10);

    // 3. Configure PLL: M=8, N=336, P=2, Q=7, source=HSE
    RCC_PLLCFGR = (8U << 0) | (336U << 6) | (0U << 16) | (7U << 24) | (1U << 22);

    // 4. Enable PLL with timeout
    RCC_CR |= (1U << 24); // PLLON
    timeout = 100000;
    while (!(RCC_CR & (1U << 25)) && --timeout); // PLLRDY
    if (!timeout) { /* fallback */ }

    // 5. Set AHB=1, APB1=4, APB2=2
    RCC_CFGR = (0U << 4) | (0x5U << 10) | (0x4U << 13);

    // 6. Switch SYSCLK to PLL
    RCC_CFGR = (RCC_CFGR & ~0x3U) | 0x2U;
    timeout = 100000;
    while (((RCC_CFGR >> 2) & 0x3U) != 0x2U && --timeout);

    // 7. Update SystemCoreClock
    SystemCoreClock = 168000000U;
}

Validation: measure MCO1 (PA8) with scope, set MCO1 prescaler to 5 for 33.6 MHz. Or use DWT cycle counter: enable DWT->CTRL, count cycles for a 1 ms delay, compute frequency. Check RCC_CFGR SWS bits = 0b10. Read FLASH_ACR, confirm 5 WS. Compare SystemCoreClock to measured. Test without debugger: power cycle, toggle LED at 1 Hz.

CheckMethodPassFail action
HSE readyPoll HSERDY with timeoutHSERDY=1 within 100k loopsFallback to HSI
Flash latencyRead FLASH_ACR5 WSSet 5 WS before PLL
PLL readyPoll PLLRDY with timeoutPLLRDY=1 within 100k loopsFallback to HSI
SYSCLK sourceRead RCC_CFGR SWS0b10Retry switch
FrequencyMCO1/PA8 scope or DWT168 MHz ±1%Reconfigure
SystemCoreClockRead variable168000000Update

Failure modes and detection:

  • Frequency raised before wait states: if PLL switched before FLASH_ACR set, CPU fetches at 168 MHz with 0 WS. Detection: hard fault or wrong execution. Cost: crash.
  • Oscillator never locks: HSE fails, while loop hangs. Detection: timeout counter. Fallback: switch to HSI (16 MHz), set flash latency 0 WS, SystemCoreClock=16000000. Cost: lower performance but boots.
  • Stale core clock: SystemCoreClock not updated, delays and baud rates wrong. Detection: compare to measured. Cost: timing bugs.
  • Infinite loop: no timeout. Detection: watchdog reset. Cost: device bricked until reset.
  • Debugger-only success: debugger slows clock or provides HSE. Detection: test without debugger. Cost: field failures.

Trade-offs: HSE vs HSI: HSE ±10 ppm, HSI ±1% over temperature. Timeout vs no timeout: timeout adds code but prevents hang. Fallback to HSI vs halt: fallback keeps system alive at 16 MHz; halt is safer if clock integrity is critical.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How is an interrupt controller like the ARM Cortex-M NVIC mapped into MMIO, and why does its architecture use distinct set-pending and clear-pending registers rather than a single read-modify-write register?

Answer

In the ARM Cortex-M architecture, the Nested Vectored Interrupt Controller (NVIC) is an integrated core peripheral mapped to the private peripheral bus within the internal System Control Space (SCS), starting at base address 0xE000E000 (NVIC registers span 0xE000E100 to 0xE000ECFC). Because it sits on the internal PPB rather than external AHB/APB interconnects, access latency is minimal (typically single-cycle zero-wait-state access), and accesses are privileged-only by default.

The Concurrency Problem: Read-Modify-Write Races

If interrupt state (pending, enable, or active) were controlled via a single status register, altering the state of IRQ $N$ would require a classic read-modify-write sequence: read register, bitwise OR/AND mask, write back. In a multitasking or pre-emptive interrupt environment, this creates a catastrophic race condition:

  1. Thread/ISR A reads INT_PEND (e.g. contains 0x00000001, meaning IRQ 0 is pending).
  2. Hardware preemption occurs: ISR B triggers, or a hardware event fires setting IRQ 1. INT_PEND hardware state updates to 0x00000003.
  3. ISR B runs and handles IRQ 0, or context returns to Thread A.
  4. Thread A resumes its RMW to set IRQ 2: it writes back its stale snapshot OR'd with bit 2: 0x00000001 | 0x00000004 = 0x00000005.
  5. IRQ 1's pending bit (bit 1) is silently cleared and lost.

Disabling interrupts globally (CPSID i) during every peripheral pending manipulation would add cycles and degrade real-time interrupt response latency.

Architectural Solution: Atomic Set and Clear Registers

To solve this without software locking or critical sections, ARM decouples bit operations into dedicated registers:

  • ISPR[n] (Interrupt Set-Pending Register): Writing 1 to bit $k$ sets the pending state of IRQ $(32n + k)$. Writing 0 has no effect.
  • ICPR[n] (Interrupt Clear-Pending Register): Writing 1 to bit $k$ clears the pending state of IRQ $(32n + k)$. Writing 0 has no effect.
  • Identical patterns apply to interrupt enable via ISER[n] (Set-Enable) and ICER[n] (Clear-Enable).
Thread A (Triggers IRQ 5):               Hardware Peripheral (Triggers IRQ 6):
  LDR R0, =NVIC_ISPR0                      Hardware asserts IRQ 6 pending bit
  MOV R1, #(1 << 5)                        (Internal bit 6 latches to 1)
  STR R1, [R0] (Atomic MMIO Write)
  --> Writes ONLY bit 5;                   --> Simultaneous or interleaved;
      bit 6 is unaffected                     zero cross-talk or bit erasure

Memory Map and Register Layout

Each 32-bit register controls 32 interrupts (Cortex-M supports up to 240 or 480 external IRQs depending on core revision):

Register GroupOffset RangeAccessFunctionBehavior on Write 0Behavior on Write 1
NVIC->ISER[0..7]0x100 - 0x11CRWSet-EnableNo effectEnables IRQ
NVIC->ICER[0..7]0x180 - 0x19CRWClear-EnableNo effectDisables IRQ
NVIC->ISPR[0..7]0x200 - 0x21CRWSet-PendingNo effectSets IRQ pending
NVIC->ICPR[0..7]0x280 - 0x29CRWClear-PendingNo effectClears IRQ pending
NVIC->IABR[0..7]0x300 - 0x31CROActive BitRead-onlyHardware state indicator
NVIC->IP[0..239]0x400 - 0x4EFRWPriority Registers8-bit priority per interrupt (upper bits used)N/A

Pipeline and Barrier Failure Modes

Even with atomic registers, two subtle failure modes occur in Cortex-M firmware:

  1. Peripheral vs NVIC Write Buffer Desynchronization: If clearing a peripheral interrupt flag via APB MMIO before exiting an ISR, the write may be buffered in the write-buffer while the CPU executes BX LR. The NVIC still sees the interrupt line asserted and immediately re-enters the same ISR (tail-chaining storm). A downstream load or __DSB() (Data Synchronization Barrier) is required after the peripheral clear.
  2. Immediate Effect Requirement: If software disables an IRQ via ICER or clears pending via ICPR and relies on it being disabled on the very next instruction, an explicit __DSB() followed by __ISB() is required to ensure the store reaches the NVIC interface and updates the processor's exception pipeline.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Design and validate an MCU/MMIO implementation for clock and reset gating.

Answer

Core answer. Design the bring-up as a fixed sequence per peripheral, and validate it by asserting one observable register value at each step. The order is: enable the bus clock, read the enable bit back, pulse the peripheral reset, confirm the reset value, configure pins and alternate function, configure the peripheral, enable it, poll its ready flag under a bounded timeout, and roll back on any failure. If you cannot name the register that proves a step happened, that step is not validated.

Concrete case, STM32F407 (CMSIS headers, arm-none-eabi-gcc 13.2, -O2). USART2 is a volatile pointer to 0x40004400; without volatile the compiler hoists the read-backs out of the checks.

C
/* PA2/PA3 = USART2_TX/RX, AF7. USART2 sits on APB1. */
static int usart2_bringup(uint32_t brr)
{
    RCC->APB1ENR |= RCC_APB1ENR_USART2EN;        /* 1. bus clock */
    if (!(RCC->APB1ENR & RCC_APB1ENR_USART2EN))  /* 2. read back: the AHB */
        return -1;                                /* write is posted, the  */
                                                  /* read proves it landed  */
    RCC->APB1RSTR |=  RCC_APB1RSTR_USART2RST;    /* 3. reset pulse - only  */
    RCC->APB1RSTR &= ~RCC_APB1RSTR_USART2RST;     /* works with clock on   */
    if (USART2->SR != 0x00C0u) return -2;        /* 4. SR resets to TXE|TC */

    GPIOA->MODER   = (GPIOA->MODER & ~((3u<<4)|(3u<<6))) | (2u<<4)|(2u<<6);
    GPIOA->AFR[0]  = (GPIOA->AFR[0] & ~((0xFu<<8)|(0xFu<<12))) | (7u<<8)|(7u<<12);
    GPIOA->OSPEEDR |= (3u<<4)|(3u<<6);           /* 5. pins */

    USART2->BRR = brr;                           /* 6. configure */
    USART2->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE;
    if (USART2->BRR != brr) return -3;           /* 7. prove the write landed */
    return 0;                                    /* caller rolls back on <0 */
}

The read-back after the clock enable is not decoration. On Cortex-M the AHB write is posted, so a write followed immediately by a peripheral access can reach the peripheral before the clock-enable write does. Reading the same register forces the write to complete.

What each step proves.

stepreadexpectedif wrong
clock enableRCC->APB1ENR bit 171writes to USART2 dropped, reads return 0x0000
reset releasedUSART2->SR0x00C00x0000 = clock off or reset still asserted
pins muxedGPIOA->AFR[0] bits 11:8, 15:127pin idles; no edges on a scope
config landedUSART2->BRRbrr0x0000 = write dropped

Clock tree, same discipline. Raise FLASH_ACR.LATENCY before raising SYSCLK, lower it after. For 168 MHz at 3.3 V: 5 wait states, HSE 8 MHz → PLLM=8 (1 MHz) → PLLN=336 (336 MHz VCO) → PLLP=2 → 168 MHz, AHB /1, APB1 /4 = 42 MHz, APB2 /2 = 84 MHz. APB1 above 42 MHz is out of spec. Wait on RCC_CR.HSERDY and PLLRDY with a bounded counter, not while (!(RCC->CR & RCC_CR_PLLRDY));, if the crystal is not populated that loop never exits and you hang before the watchdog is running. On timeout, fall back to HSI and continue at reduced clock.

Failure modes and how you catch them.

  • Clock gated: USART2->SR reads 0x0000 instead of 0x00C0. On STM32F4 the access does not fault, reads return 0 and writes are dropped, so the only symptom is a driver that reads zeros.
  • Reset still asserted: BRR reads 0x0000 after you wrote it. The reset is clocked, so asserting RSTR with the clock off does nothing.
  • Wrong alternate function: AFR[0] reads 0 or the wrong value and the pin idles. Detect with a TX-to-RX loopback before you ship.
  • Protected write: RCC_BDCR.RTCSEL is write-once until a backup-domain reset, and the RTC/backup registers need PWR_CR.DBP set before writes land. Read back and compare; a silently ignored write leaves the RTC on the wrong clock source.
  • Infinite ready poll: bounded loop, fallback path, and a counter you can log.

Trade-offs. Gate at the RCC or at the peripheral? RCC gating removes the bus clock, so you can no longer read the peripheral's status to find out why it stopped; peripheral-level gating (USART_CR1.UE = 0) keeps the register interface alive. Use RCC gating for power, peripheral gating for diagnosability. Reset-on-init or explicit writes? A reset gives a known state, but RCC_AHB1RSTR.GPIOARST clobbers all 16 pins on port A, including ones another driver owns: reset at boot, reconfigure per pin later. Poll, delay, or interrupt? A fixed delay is a function of the clock tree: a loop tuned at 168 MHz is 4x too short at 42 MHz. Poll with a bound for microsecond waits, interrupt beyond that. And gate only when the peripheral is idle: removing the clock from a USART mid-frame aborts the transfer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate an MCU/MMIO implementation for MPU attributes.

Answer

Assumptions. Cortex-M7 (ARMv7-M PMSA), 16 MPU regions: read MPU_TYPE at 0xE000ED90, DREGION in bits [15:8], don't hardcode it. Privileged RTOS kernel, unprivileged tasks, MMIO at fixed addresses. Region size is a power of two, base aligned to size, minimum 32 bytes.

Design. A region table, most specific regions at the lowest numbers, because region number is priority: on overlap the lowest-numbered region wins per byte.

#BaseSizeRASR SIZETEX,C,BAPXNUse
00x00000000512 KB18001,1,11100Flash, code, priv+unpriv RO
10x2000000064 KB15001,1,10111SRAM, priv+unpriv RW
20x400040004 KB11000,0,00011UART0, priv RW only
30xE00000001 MB19000,0,10011PPB/NVIC, priv RW only

SIZE encodes 2^(SIZE+1) bytes: 11→4 KB, 15→64 KB, 18→512 KB, 19→1 MB. AP 001 = privileged RW, unprivileged no access; 011 = full; 110 = privileged RO, unprivileged RO. XN is RASR bit 28.

Why the UART is TEX=000, C=0, B=0. That is Strongly-ordered (Device-nGnRnE in ARMv8 naming): no cache, no speculation, no write buffer, accesses complete in program order. A UART data register is a FIFO, not memory. With Normal write-back write-allocate (TEX=001, C=1, B=1) two back-to-back stores to the same address coalesce in the write buffer and the FIFO sees one byte; a read can return a cached stale value instead of the new RX byte. Device (TEX=000, C=0, B=1, Device-nGnRE) permits write buffering but not reordering: fine for a register block that tolerates posted writes, not for a FIFO you poll.

Configuration.

C
#define MPU_RNR  (*(volatile uint32_t *)0xE000ED98u)
#define MPU_RBAR (*(volatile uint32_t *)0xE000ED9Cu)
#define MPU_RASR (*(volatile uint32_t *)0xE000EDA0u)
#define MPU_CTRL (*(volatile uint32_t *)0xE000ED94u)

static void region(unsigned n, uint32_t base, uint32_t rasr) {
    MPU_RNR  = n;
    MPU_RBAR = base & 0xFFFFFFE0u;   /* 32-byte aligned */
    MPU_RASR = rasr;
}

void mpu_init(void) {
    /* UART0: XN=1, AP=001, TEX=000,C=0,B=0, SIZE=11, ENABLE=1 */
    region(2, 0x40004000u, 0x11000017u);
    /* ... regions 0, 1, 3 the same way ... */
    MPU_CTRL = 1u;                   /* ENABLE; PRIVDEFENA=0 */
    __asm volatile ("dsb 0xf\n\tisb 0xf" ::: "memory");
}

0x11000017 = XN(1<<28) | AP(1<<24) | SIZE(11<<1) | ENABLE. All regions are written before MPU_CTRL.ENABLE, so no region is live while its base or size changes. PRIVDEFENA is left 0 so privileged code outside a region faults too: safer, but every kernel access must then be covered.

Validation. Three tests, each with an expected fault status.

  1. Attribute read-back: after region(), read MPU_RASR and assert it equals what you wrote; compute base + (1 << (SIZE+1)) and assert it does not cover the next peripheral.
  2. Privilege fault: unprivileged code stores to 0x40004000. Expect a MemManage fault with SCB->CFSR MMFSR DACCVIOL (bit 1) and MMARVALID (bit 7) set, SCB->MMFAR = 0x40004000.
  3. XN fault: branch to 0x20000000. Expect IACCVIOL (bit 0) set. If no fault, XN is clear.

Failure modes and detection.

  • Region granularity exposes a neighbour. A 4 KB region for a 1 KB device exposes 3 KB of adjacent address space with device attributes. Detect by reading back RASR and computing the covered range; fix with SRD subregion-disable (1/8 granularity, region ≥ 256 bytes) rather than spending another region.
  • Priority overlap. A higher-priority region silently widens access. Detect with a deliberate unprivileged write to the overlap address and check it faults; static-check the table for overlapping ranges.
  • Cacheable MMIO. Symptom: two writes to the FIFO produce one byte on the wire. Detect by writing 0x41 then 0x42 and counting bytes at the receiver.
  • MPU enabled after access. Untrusted code runs before MPU_CTRL.ENABLE. Detect by asserting MPU_CTRL & 1 at the top of the untrusted task; a fault test that should fire won't.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate an MCU/MMIO implementation for fault handling.

Answer

I'd assume a Cortex-M4 (ARMv7-M) with CMSIS 5.9.0, bare metal, no FPU context. On Cortex-M0/M0+ there is no CFSR and only HardFault, so the design collapses to a single handler.

Design

Fault handlers are naked so no C prologue runs before the assembly reads the exception stack pointer. The stub picks MSP or PSP from EXC_RETURN, passes the stacked frame and EXC_RETURN to C, which copies the core fault registers plus the frame into a .noinit record, increments a reset counter, and resets. On boot the record is logged and cleared.

C
// Cortex-M4, CMSIS 5.9.0, arm-none-eabi-gcc 10.3
#include "core_cm4.h"

typedef struct {
    uint32_t magic;
    uint32_t cfsr, hfsr, mmfar, bfar, afsr;
    uint32_t stacked_r0, stacked_pc, stacked_lr, stacked_xpsr;
    uint32_t exc_return;
    uint32_t reset_count;
} fault_record_t;

__attribute__((section(".noinit"))) fault_record_t g_fault;

__attribute__((naked)) void UsageFault_Handler(void) {
    __asm volatile (
        "tst lr, #4\n"
        "ite eq\n"
        "mrseq r0, msp\n"
        "mrsne r0, psp\n"
        "mov r1, lr\n"
        "b usage_fault_c\n"
    );
}

void usage_fault_c(uint32_t *stack, uint32_t exc_return) {
    g_fault.magic = 0xFA017;
    g_fault.cfsr = SCB->CFSR;
    g_fault.hfsr = SCB->HFSR;
    g_fault.mmfar = SCB->MMFAR;
    g_fault.bfar = SCB->BFAR;
    g_fault.afsr = SCB->AFSR;
    g_fault.stacked_r0 = stack[0];
    g_fault.stacked_pc = stack[6];
    g_fault.stacked_lr = stack[5];
    g_fault.stacked_xpsr = stack[7];
    g_fault.exc_return = exc_return;
    g_fault.reset_count++;
    if (g_fault.reset_count > 3) {
        while (1) { __WFI(); }
    }
    NVIC_SystemReset();
}

int main(void) {
    if (g_fault.magic == 0xFA017) {
        // log g_fault over UART or read it with the debugger
        g_fault.magic = 0;
    }
    SCB->CCR |= SCB_CCR_DIV_0_TRP_Msk;       // trap divide-by-zero
    SCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk; // enable UsageFault
    __enable_irq();
    __asm volatile (
        "movs r0, #1\n"
        "movs r1, #0\n"
        "movs r2, #0\n"
        "movs r3, #0\n"
        "udiv r2, r0, r1\n"   // divisor 0 -> UsageFault
    );
    while (1);
}

Trace: divide-by-zero

  • CCR.DIV_0_TRP (bit 4) and SHCSR.USGFAULTENA (bit 18) are set. Without USGFAULTENA the fault escalates to HardFault and this handler never runs.
  • The asm sets R0=1, R1=0, R2=0, R3=0, then executes UDIV R2, R0, R1.
  • Divisor is 0 and DIV_0_TRP is set, so a UsageFault is taken; UFSR.DIVBYZERO (CFSR bit 25) is set.
  • Hardware stacks the frame on MSP: R0=1, R1=0, R2=0, R3=0, R12 and LR as the compiler left them, PC = address of the udiv (0x08000123 in this build), xPSR=0x01000000.
  • EXC_RETURN = 0xFFFFFFF9 (thread mode, MSP, no FP). Bit 2 is 0, so the stub reads MSP.
  • usage_fault_c reads CFSR = 0x02000000, HFSR = 0, MMFAR = 0, BFAR = 0, AFSR = 0.
  • stacked_pc = 0x08000123, stacked_lr = return address after the udiv, stacked_xpsr = 0x01000000.
  • Record written, reset_count incremented, NVIC_SystemReset().
  • After reset: g_fault.magic == 0xFA017, g_fault.cfsr == 0x02000000, g_fault.stacked_pc == 0x08000123.

Validation

Run in QEMU netduinoplus2 and on an STM32F407 Discovery. Inject MemManage by configuring an MPU region as no-access and reading it; expect CFSR = 0x00000002 (MMFSR.DACCVIOL). Inject BusFault by reading an unmapped peripheral address; expect CFSR = 0x00000200 (BFSR.PRECISERR). Confirm .noinit survives reset and the record matches.

Trade-offs

DecisionOption AOption BWhen to choose
Log destinationRAM .noinit + resetUART directRAM if the bus may be failed; UART if the bus is healthy and you need live debug
ResetNVIC_SystemReset()WatchdogNVIC for immediate; watchdog if the core may be locked
ContextCore + stacked frame+ FPU lazy stackingAdd FPU if FP code can fault

Failure modes and detection

  • Read-to-clear registers: CFSR/HFSR are write-1-to-clear (RW1C), not read-to-clear, but some vendor status registers are read-to-clear. Read once, store. Detection: CFSR reads 0 after a known fault.
  • Bad stack: check SP within [__stack_start, __stack_end] before use; fall back to MSP. Detection: double fault or lockup.
  • Handler touches failed bus: use only PPB and RAM. Detection: the handler faults again, escalating to HardFault.
  • Watchdog erases log: verify .noinit is not zeroed by startup; use backup SRAM if available. Detection: magic missing after reset.
  • Recovery loop: reset counter in .noinit; after 3 resets enter safe mode. Detection: counter increments each boot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

A peripheral's data register pops one byte from its RX FIFO on every read. Walk me through how a driver reads it: checking the empty flag, draining without dropping or duplicating bytes, what breaks if status is checked after the read, and how DMA changes the access pattern.

Answer

Assume a hardware FIFO with a status register whose RXNE bit means "data available" and a data register whose read pops one entry and clears RXNE. The invariant is: read status first, read data only when status says data is present. Never read data to discover whether data was present.

c /* STM32F4 USART, CMSIS device header names */ #define USART_SR_RXNE (1U << 5) #define USART_SR_ORE (1U << 3)

uint8_t rx_pop(USART_TypeDef u) { while ((u->SR & USART_SR_RXNE) == 0) { / caller supplies timeout / } return (uint8_t)u->DR; / read pops one byte, clears RXNE */ }

size_t rx_drain(USART_TypeDef *u, uint8_t buf, size_t max) { size_t n = 0; while (n < max) { uint32_t sr = u->SR; / status first / if ((sr & USART_SR_RXNE) == 0) break; if (sr & USART_SR_ORE) { / overrun: DR read clears ORE too / } buf[n++] = (uint8_t)u->DR; / then pop */ } return n; }

The drain loop is bounded by max, not by the flag alone. A continuous stream keeps RXNE set forever, so while (RXNE) read() never exits. The bound also lets the caller return to other work and preserves the remaining bytes in the FIFO rather than dropping them.

Trace with three bytes in the FIFO and max = 2: iteration 1 reads SR (RXNE=1), reads DR -> byte0, n=1. Iteration 2 reads SR (RXNE=1), reads DR -> byte1, n=2. Loop exits on n < max; byte2 stays in the FIFO. With max = 4: iteration 3 reads byte2, n=3; iteration 4 reads SR (RXNE=0) and breaks. No byte is read twice because each DR read pops exactly one entry.

If status is checked after the read, b = u->DR; if (u->SR & RXNE) ..., the first read happens when the FIFO may be empty. DR then returns stale or undefined data, and you cannot tell whether b was real. Worse, on parts where reading DR clears the overrun flag, you clear ORE before observing it, so the overrun is invisible. The correct order is SR then DR, which is also how the reference manual specifies clearing RXNE and ORE.

DMA changes the access pattern: the DMA controller reads DR on each RXNE request, so the CPU must stop polling and reading DR, or it steals bytes from the DMA stream. The driver enables the DMA request (DMAEN), uses half-transfer and transfer-complete interrupts, and after the completion flag it issues a barrier (__DMB()) before reading the buffer, because the DMA writes to memory are observed by the CPU through the Arm memory model, not through the peripheral register. In circular mode the driver tracks head and tail against the DMA's write index; in normal mode it re-arms the DMA after each transfer. The status flag is now consumed by the DMA request logic, not by a CPU poll.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

A peripheral register is updated by hardware while software reads it: a 64-bit counter split across two 32-bit registers, or a live status word. How do you read it reliably, and what breaks if you just dereference the pointer?

Answer

Clarify first: which register, how wide, and whether the peripheral gives you a latch. Assume a Cortex-M4 at 168 MHz, a 32-bit peripheral bus, a 64-bit free-running counter exposed as two 32-bit registers with no shadow register, and no DMA snapshot available.

The distinction that decides the answer is atomicity versus staleness. A naturally aligned 32-bit load on Cortex-M is single-copy atomic: the bus returns one value, never half of two. So a 32-bit counter read is never torn. It can still be stale: the counter keeps running while you shift, compare and store, and if you read two related registers separately, hardware can update between them. That second case is where tearing actually happens.

registertechniquewhy
32-bit counter, one loadsingle aligned loadsingle-copy atomic, no retry needed
64-bit counter, two 32-bit regsread high, low, high; retry if high changedthe low word can only carry into the high word
peripheral shadow/latchread low word, then high wordhardware latches, no retry bound
sticky status wordread once, mask, actbits can set and clear between two reads
config register writewrite, DSB, read back, comparea posted write may still be in flight

c /* arm-none-eabi-gcc 13, Cortex-M4, CMSIS-style volatile access / #define CNT_HI ((volatile uint32_t )0x40001000u) #define CNT_LO ((volatile uint32_t *)0x40001004u)

uint64_t counter_read(void) { uint32_t hi, lo, hi2; do { hi = CNT_HI; lo = CNT_LO; hi2 = CNT_HI; } while (hi != hi2); return ((uint64_t)hi << 32) | lo; }

The loop terminates because the carry only goes one way: if it happened between the first and third read, the two high words differ and we retry. Read-twice on a single register is a different case: it works for a monotonic counter, but on a status word a bit can set and clear between the two reads and you accept a value that never existed.

Arithmetic on why the retry matters: a 16-bit counter ticking at 1 MHz wraps every 65.536 ms. A hi-lo read that straddles the wrap returns a value off by 65536 ticks: 65.5 ms of error in a timestamp, enough to break a control loop or a delta calculation.

Read-back verification is the other half. After writing a config register, read it back and compare, because a posted write can still be in flight and a clock-gated peripheral can drop it; a DSB before the read-back forces the write to complete. But read-back is destructive on some registers: a read-to-clear interrupt flag, a FIFO data register, or a W1C status register is consumed by the read-back, and a debugger watch or a logging path that reads them does the same damage.

Failure modes and how you see them:

  • Torn multi-word read: the retry loop never exits, or timestamps jump by exactly one wrap period.
  • Stale value used for a delta: the difference is short by the time between the two reads; detect by comparing against a hardware capture or a DMA-written shadow.
  • Read-back consuming a read-to-clear flag: the interrupt fires once and never again, and the software event count stops matching the hardware count.
  • Missing volatile: the compiler hoists the load out of the loop, the retry never re-reads, and the loop spins forever.
  • Read-modify-write on a register hardware also updates: the write-back clobbers bits set between the read and the write; use set/clear aliases when the peripheral has them.

Curated: · Written: · Reviewed:

Difficulty: Hard