</>EmbeddedInterview

Explain memory barrier in brief.

MediumARM Architecture

A memory barrier is a mechanism that enforces the required ordering or completion of memory operations on a CPU.

ARM uses a weakly ordered memory model, meaning memory reads and writes may become visible to other CPU cores in a different order than specified in the program.

1. Without memory barrier

Consider two CPU cores sharing data and flag, initially both zero.

// CPU Core 0
data = 100;
flag = 1;

// CPU Core 1
if (flag == 1)
    printf("%d", data);

Equivalent ARM instructions on Core 0:

STR R0, [R1]    // Store data = 100
STR R2, [R3]    // Store flag = 1

Due to weak memory ordering, Core 1 may observe flag = 1 before data = 100 becomes visible.

Therefore, Core 1 could read data = 0.

2. With memory barrier

In Linux kernel code:

// CPU Core 0
WRITE_ONCE(data, 100);
smp_wmb();
WRITE_ONCE(flag, 1);

// CPU Core 1
if (READ_ONCE(flag) == 1) {
    smp_rmb();
    value = READ_ONCE(data);
}
CPU Core 0CPU Core 1Write data = 100Read flag = 1Write barrierRead barrierWrite flag = 1Read data = 100

Now, if Core 1 observes flag = 1, it is guaranteed to observe data = 100, assuming no other writes modify the shared variables.

3. Types of memory barriers in ARM

Barrier Full form Purpose
DMB Data Memory Barrier Enforces memory access ordering.
DSB Data Synchronization Barrier Waits for required preceding operations to complete.
ISB Instruction Synchronization Barrier Synchronizes subsequent instruction execution with the updated execution context.

DMB — Data Memory Barrier

STR R0, [R1]
DMB ISH
STR R2, [R3]

Ensures the required ordering of memory accesses within the inner-shareable domain.

Used in: Multicore synchronization, shared memory and spinlocks.

DSB — Data Synchronization Barrier

STR R0, [R1]
DSB SY
WFI

Ensures the preceding store completes before the CPU executes WFI (Wait For Interrupt).

Used in: Peripheral configuration, cache maintenance, power management and TLB maintenance.

ISB — Instruction Synchronization Barrier

MSR SCTLR_EL1, X0
ISB

Ensures subsequent instructions execute using the updated processor configuration.

Used in: MMU configuration, system register updates and execution context changes.

4. Linux kernel memory barrier APIs

API Purpose
smp_mb() Full SMP memory barrier
smp_rmb() Read memory barrier
smp_wmb() Write memory barrier
dma_rmb() DMA read ordering
dma_wmb() DMA write ordering
barrier() Compiler barrier only

5. Where are memory barriers used?

  • Multicore communication.
  • CPU and DMA shared memory.
  • Device drivers and MMIO registers.
  • Lock-free circular buffers.
  • Spinlocks and atomic operations.
  • MMU and cache configuration.

Interview key point: DMB ensures ordering, DSB ensures completion, and ISB synchronizes instruction execution. A memory barrier does not automatically flush the cache, and the volatile keyword is not a replacement for a memory barrier.