Section 4.37

Memory barrier

Definition

A memory barrier, or memory fence, is an instruction or language operation that limits the reordering of memory accesses across it: accesses of stated kinds that precede the barrier in a thread take effect, as seen by stated observers such as other processor cores or devices, before accesses of stated kinds that follow it. A compiler barrier limits only the compiler; a hardware barrier, a processor instruction such as Arm’s DMB, limits the processor. Each barrier’s specification names the accesses, the observers, and whether it also waits for completion.

The idea

One thread prepares data and then raises a flag; another thread waits for the flag and then reads the data. Written in plain C for readability:

data = 42; ready = 1; in thread A
while (ready == 0) { } r = data; in thread B

Both variables start at 0, and the programmer expects r=42r = 42. Three agents may reorder accesses and break that expectation. The compiler may emit the store to ready before the store to data, because within thread A the two stores are independent. The processor running thread A may make its two stores visible to other cores in the opposite order, which weakly ordered processors, such as most multi-core Arm processors, are allowed to do. The processor running thread B may perform the load of data early, before its load of ready returns 1. Each reordering is invisible to a thread running alone, which is why compilers and processors may make it, and each can give r=0r = 0.

A barrier is a line drawn across one thread’s sequence of accesses that accesses of the named kinds may not cross. Thread A needs one between writing data and writing ready; thread B needs one between reading ready and reading data. A mail clerk told not to post the second letter until the first has been delivered is a fair picture. The picture stops at an important point: a barrier makes no thread wait for another. Thread B must still check the flag, and a barrier in thread A alone does nothing about the order of thread B’s loads.

How it works

Barriers work at three levels, and each level prevents different reorderings.

  1. Compiler barrier. A common form in C is the empty assembly statement asm volatile("" ::: "memory"), which the widely used C compilers GCC §12.17 (GNU Compiler Collection; GNU stands for GNU’s Not Unix) and Clang accept. It tells the compiler that the statement may read or write any memory, so the compiler may neither move memory accesses across it nor keep memory values in registers across it. It emits no instruction, so the processor may still reorder. It is enough only where the processor cannot reorder the accesses concerned, for example between a program and an interrupt handler §6.12 on one single-core processor, which sees its own accesses in program order.

  2. Hardware barrier. A processor instruction that limits the processor’s reordering. The Linux kernel names the common strengths: smp_wmb() orders earlier stores before later stores, smp_rmb() orders earlier loads before later loads, and smp_mb() orders all earlier loads and stores before all later ones, including a store followed by a load, the one case the other two leave open. The prefix smp refers to systems with several processors. Each of these macros also acts as a compiler barrier.

  3. Language synchronization. In C11 and C++11, the 2011 editions of the C and C++ standards [78, 247], atomic operations §9.8 carry a memory order. A store with release order keeps all earlier memory accesses of its thread before it. A load with acquire order keeps all later memory accesses of its thread after it. When an acquire load reads the value that a release store wrote, the release synchronizes with the acquire and creates a happens-before relation §9.10: everything the storing thread did before the release is visible to the loading thread after the acquire. This pattern is called acquire-release ordering §9.11. The compiler emits whatever hardware barrier the target processor needs, possibly none.

The Armv7-M architecture, used by Arm Cortex-M3 and Cortex-M4 §6.3 processors, defines three barrier instructions.

In Armv7-M every barrier applies to all observers and all access types. After reconfiguring the processor, for example after enabling the memory protection unit §6.8 (MPU), the usual sequence is DSB then ISB: the first waits until the configuration write has completed, and the second makes the following instructions run under the new configuration.

For ordinary loads and stores, x86-64 processors keep most orders without barriers. As seen by other cores, they never reorder a load with an earlier load or a store with an earlier store, but they may perform a load before an earlier store to a different address has become visible. Only that store-then-load case needs a hardware barrier there, such as the mfence instruction or an instruction with a lock prefix.

Worked example

Here is message passing in C11. The variable data is an ordinary int and ready is an atomic_int, both starting at 0. Thread A runs

data = 42;
atomic_store_explicit(&ready, 1, memory_order_release);

and thread B runs

while (atomic_load_explicit(&ready,
memory_order_acquire) == 0) { }
r = data;

Trace it.

  1. Thread A writes 42 to data. The release store that follows cannot be moved above this write.

  2. Thread A’s release store writes 1 to ready.

  3. Thread B’s acquire load eventually reads 1, the value the release store wrote, so the release synchronizes with the acquire.

  4. The read of data cannot be moved above the acquire load, and the write of 42 happens before it. So r=42r = 42; the outcome r=0r = 0 is impossible.

What the compiler emits depends on the target. For 32-bit Arm processors of the Armv7 architecture, compilers typically implement the release store as DMB followed by an ordinary store, and the acquire load as an ordinary load followed by DMB. For x86-64 both are ordinary mov instructions, because the hardware already keeps those two orders; only the compiler is restrained.

A device example needs two separate gates. A program fills a descriptor in RAM, a record that tells a DMA §4.36 (direct memory access) controller what to copy, and then writes the controller’s start register, a device register at a memory address. In Armv7-M the descriptor lies in Normal memory, the architecture’s name for ordinary memory, and the start register lies in Device memory, the type used for device registers. The architecture lets an earlier Normal access and a later Device access be observed in either order. A DMB between the two writes makes the controller, which is an observer, see the descriptor before the start command. That barrier says nothing about when the copy ends: the barrier orders the start of the transfer, and only the controller’s completion flag says when the transfer has ended.

Stated precisely

Every barrier’s contract answers four questions, and only the answers count.

  1. Which accesses before it are ordered against which accesses after it: loads, stores or both, to which memory types.

  2. As seen by which observers: the compiler only, other cores, devices, or all of them.

  3. Which guarantee: ordering, meaning observers see the earlier accesses first; completion, meaning later instructions wait until earlier accesses have finished; or context synchronization, meaning later instructions are fetched again under the new processor configuration.

  4. With which partner: a release orders nothing for another thread unless that thread performs an acquire that reads the released value.

The C11 rule, stated exactly. Let WW be an atomic store with release order to an atomic object MM, performed by thread A, and let RR be an atomic load with acquire order from MM, performed by thread B. If RR reads the value written by WW, then WW synchronizes with RR, and every evaluation that comes before WW in thread A’s own order happens before every evaluation that comes after RR in thread B’s own order. Two accesses in different threads to the same memory location, at least one of them a write and at least one not atomic, that the happens-before relation does not order form a data race §9.3. A data race is undefined behavior §4.12: the standard gives the program no meaning, so no reasoning about barriers can rescue it.

Limits and common mistakes

A barrier orders; it does not exclude. Two threads can both pass barriers and still update the same data at the same moment. Mutual exclusion needs a mutex §9.5 or an atomic read-modify-write.

Barriers work in pairs. A barrier in the writing thread is useless if the reading thread’s loads can still be reordered; the reader needs its own acquire operation or read barrier.

The plain C version of the flag example is a data race, and so undefined behavior, even with barriers added by hand. Portable C uses atomic variables for the flag.

A barrier does not clean or invalidate a cache. On processors whose data cache is not coherent with DMA, cache maintenance is a separate set of operations, and a DSB is then used to wait until they have completed.

Completion of a memory access is not completion of the device operation it starts. After a DSB, a write to a flash controller’s erase register has completed as a bus access, but the erase continues much longer, and only the controller’s status bit says when it is done.

Volatile is not a barrier. The volatile qualifier §4.34 constrains only how the compiler treats volatile accesses, and it emits no barrier instruction.

A stronger-looking barrier is not automatically the right one. A DSB where an ISB is needed leaves already fetched instructions in the pipeline, and new code written to memory also needs the instruction-side steps described in the instruction-cache coherence entry §19.5.3. Correctness comes from matching the barrier’s contract to the property the code needs.

Questions answered

Which compiler and hardware reorderings does a particular barrier prevent?

A barrier prevents exactly the reorderings that its own specification lists, and no others; the word barrier alone says nothing. Read four things from the specification: which accesses before it are ordered against which accesses after it, as seen by which observers, whether it only orders or also waits for completion, and whether it needs a matching operation in another thread. The common cases are these.

None of these prevents another thread from running at the same time, and none waits for a device to finish the work that an access started.

Related entries: Happens-before relation (§9.10), Volatile qualifier (§4.34), Memory-mapped I/O (MMIO) (§4.35), Direct memory access (DMA) (§4.36), Acquire-release ordering (§9.11), Sequential consistency (§9.12), Instruction-cache coherence and executable-code publication (§19.5.3), Memory protection unit (MPU) (§6.8). Further reading: [78, 80, 81, 247].