</>EmbeddedInterview

What is a memory barrier and why would firmware need one?

HardEmbedded C

Short answer: A memory barrier forces an ordering between memory operations that the CPU, its write buffers or the bus would otherwise be allowed to reorder or delay. Arm has three barrier instructions: DMB (memory accesses before it are observed before those after it), DSB (all memory accesses complete before any later instruction executes), and ISB (flush the pipeline so later instructions are fetched and decoded with the new context).

Barrier Guarantees Typical use
DMB ordering of memory accesses multi-core shared data, DMA descriptor updates (descriptor written before the "go" bit), lock implementations
DSB completion of memory accesses before continuing before WFI (enter sleep), after clearing an interrupt flag at the end of an ISR, before an operation that depends on a write having reached a peripheral, after cache maintenance
ISB pipeline refetch after writing CONTROL (switching stack or privilege), after changing VTOR, MPU, or enabling the FPU, after self-modifying code (with cache maintenance)

Embedded examples

/* end of an ISR on a core with write buffers (Cortex-M7, or bus-bridged peripherals) */
TIM2->SR = ~TIM_SR_UIF;    /* clear the update flag */
__DSB();                   /* make sure the write reached the timer before returning,
                              otherwise the still-pending interrupt re-triggers the ISR */

/* changing privilege/stack */
__set_CONTROL(__get_CONTROL() | CONTROL_SPSEL_Msk);
__ISB();

/* MPU reconfiguration */
MPU->CTRL = MPU_CTRL_ENABLE_Msk | MPU_CTRL_PRIVDEFENA_Msk;
__DSB();
__ISB();

Single-core Cortex-M: most cores (M0/M3/M4) do not reorder memory accesses much, so barriers are rarely needed for plain data. Arm still recommends them in the architectural cases above (CONTROL, MPU, VTOR, before sleep), and they matter on Cortex-M7 (write buffers, caches) and for accesses to peripherals behind bus bridges.

Multi-core and Cortex-A: reordering is common. Use C11 atomics with acquire/release ordering (atomic_store_explicit(&ready, 1, memory_order_release)), which emit the right barriers, or the kernel's smp_mb(), smp_wmb(), dma_wmb().

Compiler vs CPU barriers: volatile and __asm volatile("" ::: "memory") only constrain the compiler; they emit no instruction. CMSIS __DMB()/__DSB()/__ISB() include a compiler barrier and the hardware instruction.