============================ LINUX KERNEL MEMORY BARRIERS ============================ By: David Howells Paul E. McKenney Contents: (*) Abstract memory access model. - Device operations. - Guarantees. (*) What are memory barriers? - Varieties of memory barrier. - What may not be assumed about memory barriers? - Data dependency barriers. - Control dependencies. - SMP barrier pairing. - Examples of memory barrier sequences. - Read memory barriers vs load speculation. - Transitivity (*) Explicit kernel barriers. - Compiler barrier. - CPU memory barriers. - MMIO write barrier. (*) Implicit kernel memory barriers. - Locking functions. - Interrupt disabling functions. - Sleep and wake-up functions. - Miscellaneous functions. (*) Inter-CPU locking barrier effects. - Locks vs memory accesses. - Locks vs I/O accesses. (*) Where are memory barriers needed? - Interprocessor interaction. - Atomic operations. - Accessing devices. - Interrupts. (*) Kernel I/O barrier effects. (*) Assumed minimum execution ordering model. (*) The effects of the cpu cache. - Cache coherency. - Cache coherency vs DMA. - Cache coherency vs MMIO. (*) The things CPUs get up to. - And then there's the Alpha. (*) Example uses. - Circular buffers. (*) References. ============================ ABSTRACT MEMORY ACCESS MODEL ============================ Consider the following abstract model of the system: : : : : : : +-------+ : +--------+ : +-------+ | | : | | : | | | | : | | : | | | CPU 1 |<----->| Memory |<----->| CPU 2 | | | : | | : | | | | : | | : | | +-------+ : +--------+ : +-------+ ^ : ^ : ^ | : | : | | : | : | | : v : | | : +--------+ : | | : | | : | | : | | : | +---------->| Device |<----------+ : | | : : | | : : +--------+ : : : Each CPU executes a program that generates memory access operations. In the abstract CPU, memory operation ordering is very relaxed, and a CPU may actually perform the memory operations in any order it likes, provided program causality appears to be maintained. Similarly, the compiler may also arrange the instructions it emits in any order it likes, provided it doesn't affect the apparent operation of the program. So in the above diagram, the effects of the memory operations performed by a CPU are perceived by the rest of the system as the operations cross the interface between the CPU and rest of the system (the dotted lines). For example, consider the following sequence of events: CPU 1 CPU 2 =============== =============== { A == 1; B == 2 } A = 3; x = B; B = 4; y = A; The set of accesses as seen by the memory system in the middle can be arranged in 24 different combinations: STORE A=3, STORE B=4, y=LOAD A->3, x=LOAD B->4 STORE A=3, STORE B=4, x=LOAD B->4, y=LOAD A->3 STORE A=3, y=LOAD A->3, STORE B=4, x=LOAD B->4 STORE A=3, y=LOAD A->3, x=LOAD B->2, STORE B=4 STORE A=3, x=LOAD B->2, STORE B=4, y=LOAD A->3 STORE A=3, x=LOAD B->2, y=LOAD A->3, STORE B=4 STORE B=4, STORE A=3, y=LOAD A->3, x=LOAD B->4 STORE B=4, ... ... and can thus result in four different combinations of values: x == 2, y == 1 x == 2, y == 3 x == 4, y == 1 x == 4, y == 3 Furthermore, the stores committed by a CPU to the memory system may not be perceived by the loads made by another CPU in the same order as the stores were committed. As a further example, consider this sequence of events: CPU 1 CPU 2 =============== =============== { A == 1, B == 2, C = 3, P == &A, Q == &C } B = 4; Q = P; P = &B D = *Q; There is an obvious data dependency here, as the value loaded into D depends on the address retrieved from P by CPU 2. At the end of the sequence, any of the following results are possible: (Q == &A) and (D == 1) (Q == &B) and (D == 2) (Q == &B) and (D == 4) Note that CPU 2 will never try and load C into D because the CPU will load P into Q before issuing the load of *Q. DEVICE OPERATIONS ----------------- Some devices present their control interfaces as collections of memory locations, but the order in which the control registers are accessed is very important. For instance, imagine an ethernet card with a set of internal registers that are accessed through an address port register (A) and a data port register (D). To read internal register 5, the following code might then be used: *A = 5; x = *D; but this might show up as either of the following two sequences: STORE *A = 5, x = LOAD *D x = LOAD *D, STORE *A = 5 the second of which will almost certainly result in a malfunction, since it set the address _after_ attempting to read the register. GUARANTEES ---------- There are some minimal guarantees that may be expected of a CPU: (*) On any given CPU, dependent memory accesses will be issued in order, with respect to itself. This means that for: ACCESS_ONCE(Q) = P; smp_read_barrier_depends(); D = ACCESS_ONCE(*Q); the CPU will issue the following memory operations: Q = LOAD P, D = LOAD *Q and always in that order. On most systems, smp_read_barrier_depends() does nothing, but it is required for DEC Alpha. The ACCESS_ONCE() is required to prevent compiler mischief. Please note that you should normally use something like rcu_dereference() instead of open-coding smp_read_barrier_depends(). (*) Overlapping loads and stores within a particular CPU will appear to be ordered within that CPU. This means that for: a = ACCESS_ONCE(*X); ACCESS_ONCE(*X) = b; the CPU will only issue the following sequence of memory operations: a = LOAD *X, STORE *X = b And for: ACCESS_ONCE(*X) = c; d = ACCESS_ONCE(*X); the CPU will only issue: STORE *X = c, d = LOAD *X (Loads and stores overlap if they are targeted at overlapping pieces of memory). And there are a number of things that _must_ or _must_not_ be assumed: (*) It _must_not_ be assumed that the compiler will do what you want with memory references that are not protected by ACCESS_ONCE(). Without ACCESS_ONCE(), the compiler is within its rights to do all sorts of "creative" transformations, which are covered in the Compiler Barrier section. (*) It _must_not_ be assumed that independent loads and stores will be issued in the order given. This means that for: X = *A; Y = *B; *D = Z; we may get any of the following sequences: X = LOAD *A, Y = LOAD *B, STORE *D = Z X = LOAD *A, STORE *D = Z, Y = LOAD *B Y = LOAD *B, X = LOAD *A, STORE *D = Z Y = LOAD *B, STORE *D = Z, X = LOAD *A STORE *D = Z, X = LOAD *A, Y = LOAD *B STORE *D = Z, Y = LOAD *B, X = LOAD *A (*) It _must_ be assumed that overlapping memory accesses may be merged or discarded. This means that for: X = *A; Y = *(A + 4); we may get any one of the following sequences: X = LOAD *A; Y = LOAD *(A + 4); Y = LOAD *(A + 4); X = LOAD *A; {X, Y} = LOAD {*A, *(A + 4) }; And for: *A = X; *(A + 4) = Y; we may get any of: STORE *A = X; STORE *(A + 4) = Y; STORE *(A + 4) = Y; STORE *A = X; STORE {*A, *(A + 4) } = {X, Y}; And there are anti-guarantees: (*) These guarantees do not apply to bitfields, because compilers often generate code to modify these using non-atomic read-modify-write sequences. Do not attempt to use bitfields to synchronize parallel algorithms. (*) Even in cases where bitfields are protected by locks, all fields in a given bitfield must be protected by one lock. If two fields in a given bitfield are protected by different locks, the compiler's non-atomic read-modify-write sequences can cause an update to one field to corrupt the value of an adjacent field. (*) These guarantees apply only to properly aligned and sized scalar variables. "Properly sized" currently means variables that are the same size as "char", "short", "int" and "long". "Properly aligned" means the natural alignment, thus no constraints for "char", two-byte alignment for "short", four-byte alignment for "int", and either four-byte or eight-byte alignment for "long", on 32-bit and 64-bit systems, respectively. Note that these guarantees were introduced into the C11 standard, so beware when using older pre-C11 compilers (for example, gcc 4.6). The portion of the standard containing this guarantee is Section 3.14, which defines "memory location" as follows: memory location either an object of scalar type, or a maximal sequence of adjacent bit-fields all having nonzero width NOTE 1: Two threads of execution can update and access separate memory locations without interfering with each other. NOTE 2: A bit-field and an adjacent non-bit-field member are in separate memory locations. The same applies to two bit-fields, if one is declared inside a nested structure declaration and the other is not, or if the two are separated by a zero-length bit-field declaration, or if they are separated by a non-bit-field member declaration. It is not safe to concurrently update two bit-fields in the same structure if all members declared between them are also bit-fields, no matter what the sizes of those intervening bit-fields happen to be. ========================= WHAT ARE MEMORY BARRIERS? ========================= As can be seen above, independent memory operations are effectively performed in random order, but this can be a problem for CPU-CPU interaction and for I/O. What is required is some way of intervening to instruct the compiler and the CPU to restrict the order. Memory barriers are such interventions. They impose a perceived partial ordering over the memory operations on either side of the barrier. Such enforcement is important because the CPUs and other devices in a system can use a variety of tricks to improve performance, including reordering, deferral and combination of memory operations; speculative loads; speculative branch prediction and various types of caching. Memory barriers are used to override or suppress these tricks, allowing the code to sanely control the interaction of multiple CPUs and/or devices. VARIETIES OF MEMORY BARRIER --------------------------- Memory barriers come in four basic varieties: (1) Write (or store) memory barriers. A write memory barrier gives a guarantee that all the STORE operations specified before the barrier will appear to happen before all the STORE operations specified after the barrier with respect to the other components of the system. A write barrier is a partial ordering on stores only; it is not required to have any effect on loads. A CPU can be viewed as committing a sequence of store operations to the memory system as time progresses. All stores before a write barrier will occur in the sequence _before_ all the stores after the write barrier. [!] Note that write barriers should normally be paired with read or data dependency barriers; see the "SMP barrier pairing" subsection. (2) Data dependency barriers. A data dependency barrier is a weaker form of read barrier. In the case where two loads are performed such that the second depends on the result of the first (eg: the first load retrieves the address to which the second load will be directed), a data dependency barrier would be required to make sure that the target of the second load is updated before the address obtained by the first load is accessed. A data dependency barrier is a partial ordering on interdependent loads only; it is not required to have any effect on stores, independent loads or overlapping loads. As mentioned in (1), the other CPUs in the system can be viewed as committing sequences of stores to the memory system that the CPU being considered can then perceive. A data dependency barrier issued by the CPU under consideration guarantees that for any load preceding it, if that load touches one of a sequence of stores from another CPU, then by the time the barrier completes, the effects of all the stores prior to that touched by the load will be perceptible to any loads issued after the data dependency barrier. See the "Examples of memory barrier sequences" subsection for diagrams showing the ordering constraints. [!] Note that the first load really has to have a _data_ dependency and not a control dependency. If the address for the second load is dependent on the first load, but the dependency is through a conditional rather than actually loading the address itself, then it's a _control_ dependency and a full read barrier or better is required. See the "Control dependencies" subsection for more information. [!] Note that data dependency barriers should normally be paired with write barriers; see the "SMP barrier pairing" subsection. (3) Read (or load) memory barriers. A read barrier is a data dependency barrier plus a guarantee that all the LOAD operations specified before the barrier will appear to happen before all the LOAD operations specified after the barrier with respect to the other components of the system. A read barrier is a partial ordering on loads only; it is not required to have any effect on stores. Read memory barriers imply data dependency barriers, and so can substitute for them. [!] Note that read barriers should normally be paired with write barriers; see the "SMP barrier pairing" subsection. (4) General memory barriers. A general memory barrier gives a guarantee that all the LOAD and STORE operations specified before the barrier will appear to happen before all the LOAD and STORE operations specified after the barrier with respect to the other components of the system. A general memory barrier is a partial ordering over both loads and stores. General memory barriers imply both read and write memory barriers, and so can substitute for either. And a couple of implicit varieties: (5) ACQUIRE operations. This acts as a one-way permeable barrier. It guarantees that all memory operations after the ACQUIRE operation will appear to happen after the ACQUIRE operation with respect to the other components of the system. ACQUIRE operations include LOCK operations and smp_load_acquire() operations. Memory operations that occur before an ACQUIRE operation may appear to happen after it completes. An ACQUIRE operation should almost always be paired with a RELEASE operation. (6) RELEASE operations. This also acts as a one-way permeable barrier. It guarantees that all memory operations before the RELEASE operation will appear to happen before the RELEASE operation with respect to the other components of the system. RELEASE operations include UNLOCK operations and smp_store_release() operations. Memory operations that occur after a RELEASE operation may appear to happen before it completes. The use of ACQUIRE and RELEASE operations generally precludes the need for other sorts of memory barrier (but note the exceptions mentioned in the subsection "MMIO write barrier"). In addition, a RELEASE+ACQUIRE pair is -not- guaranteed to act as a full memory barrier. However, after an ACQUIRE on a given variable, all memory accesses preceding any prior RELEASE on that same variable are guaranteed to be visible. In other words, within a given variable's critical section, all accesses of all previous critical sections for that variable are guaranteed to have completed. This means that ACQUIRE acts as a minimal "acquire" operation and RELEASE acts as a minimal "release" operation. Memory barriers are only required where there's a possibility of interaction between two CPUs or between a CPU and a device. If it can be guaranteed that there won't be any such interaction in any particular piece of code, then memory barriers are unnecessary in that piece of code. Note that these are the _minimum_ guarantees. Different architectures may give more substantial guarantees, but they may _not_ be relied upon outside of arch specific code. WHAT MAY NOT BE ASSUMED ABOUT MEMORY BARRIERS? ---------------------------------------------- There are certain things that the Linux kernel memory barriers do not guarantee: (*) There is no guarantee that any of the memory accesses specified before a memory barrier will be _complete_ by the completion of a memory barrier instruction; the barrier can be considered to draw a line in that CPU's access queue that accesses of the appropriate type may not cross. (*) There is no guarantee that issuing a memory barrier on one CPU will have any direct effect on another CPU or any other hardware in the system. The indirect effect will be the order in which the second CPU sees the effects of the first CPU's accesses occur, but see the next point: (*) There is no guarantee that a CPU will see the correct order of effects from a second CPU's accesses, even _if_ the second CPU uses a memory barrier, unless the first CPU _also_ uses a matching memory barrier (see the subsection on "SMP Barrier Pairing"). (*) There is no guarantee that some intervening piece of off-the-CPU hardware[*] will not reorder the memory accesses. CPU cache coherency mechanisms should propagate the indirect effects of a memory barrier between CPUs, but might not do so in order. [*] For information on bus mastering DMA and coherency please read: Documentation/PCI/pci.txt Documentation/DMA-API-HOWTO.txt Documentation/DMA-API.txt DATA DEPENDENCY BARRIERS ------------------------ The usage requirements of data dependency barriers are a little subtle, and it's not always obvious that they're needed. To illustrate, consider the following sequence of events: CPU 1 CPU 2 =============== =============== { A == 1, B == 2, C = 3, P == &A, Q == &C } B = 4; ACCESS_ONCE(P) = &B Q = ACCESS_ONCE(P); D = *Q; There's a clear data dependency here, and it would seem that by the end of the sequence, Q must be either &A or &B, and that: (Q == &A) implies (D == 1) (Q == &B) implies (D == 4) But! CPU 2's perception of P may be updated _before_ its perception of B, thus leading to the following situation: (Q == &B) and (D == 2) ???? Whilst this may seem like a failure of coherency or causality maintenance, it isn't, and this behaviour can be observed on certain real CPUs (such as the DEC Alpha). To deal with this, a data dependency barrier or better must be inserted between the address load and the data load: CPU 1 CPU 2 =============== =============== { A == 1, B == 2, C = 3, P == &A, Q == &C } B = 4; ACCESS_ONCE(P) = &B Q = ACCESS_ONCE(P); D = *Q; This enforces the occurrence of one of the two implications, and prevents the third possibility from arising. [!] Note that this extremely counterintuitive situation arises most easily on machines with split caches, so that, for example, one cache bank processes even-numbered cache lines and the other bank processes odd-numbered cache lines. The pointer P might be stored in an odd-numbered cache line, and the variable B might be stored in an even-numbered cache line. Then, if the even-numbered bank of the reading CPU's cache is extremely busy while the odd-numbered bank is idle, one can see the new value of the pointer P (&B), but the old value of the variable B (2). Another example of where data dependency barriers might be required is where a number is read from memory and then used to calculate the index for an array access: CPU 1 CPU 2 =============== =============== { M[0] == 1, M[1] == 2, M[3] = 3, P == 0, Q == 3 } M[1] = 4; ACCESS_ONCE(P) = 1 Q = ACCESS_ONCE(P); D = M[Q]; The data dependency barrier is very important to the RCU system, for example. See rcu_assign_pointer() and rcu_dereference() in include/linux/rcupdate.h. This permits the current target of an RCU'd pointer to be replaced with a new modified target, without the replacement target appearing to be incompletely initialised. See also the subsection on "Cache Coherency" for a more thorough example. CONTROL DEPENDENCIES -------------------- A control dependency requires a full read memory barrier, not simply a data dependency barrier to make it work correctly. Consider the following bit of code: q = ACCESS_ONCE(a); if (q) { /* BUG: No data dependency!!! */ p = ACCESS_ONCE(b); } This will not have the desired effect because there is no actual data dependency, but rather a control dependency that the CPU may short-circuit by attempting to predict the outcome in advance, so that other CPUs see the load from b as having happened before the load from a. In such a case what's actually required is: q = ACCESS_ONCE(a); if (q) { p = ACCESS_ONCE(b); } However, stores are not speculated. This means that ordering -is- provided in the following example: q = ACCESS_ONCE(a); if (q) { ACCESS_ONCE(b) = p; } Please note that ACCESS_ONCE() is not optional! Without the ACCESS_ONCE(), might combine the load from 'a' with other loads from 'a', and the store to 'b' with other stores to 'b', with possible highly counterintuitive effects on ordering. Worse yet, if the compiler is able to prove (say) that the value of variable 'a' is always non-zero, it would be well within its rights to optimize the original example by eliminating the "if" statement as follows: q = a; b = p; /* BUG: Compiler and CPU can both reorder!!! */ So don't leave out the ACCESS_ONCE(). It is tempting to try to enforce ordering on identical stores on both branches of the "if" statement as follows: q = ACCESS_ONCE(a); if (q) { barrier(); ACCESS_ONCE(b) = p; do_something(); } else { barrier(); ACCESS_ONCE(b) = p; do_something_else(); } Unfortunately, current compilers will transform this as follows at high optimization levels: q = ACCESS_ONCE(a); barrier(); ACCESS_ONCE(b) = p; /* BUG: No ordering vs. load from a!!! */ if (q) { /* ACCESS_ONCE(b) = p; -- moved up, BUG!!! */ do_something(); } else { /* ACCESS_ONCE(b) = p; -- moved up, BUG!!! */ do_something_else(); } Now there is no conditional between the load from 'a' and the store to 'b', which means that the CPU is within its rights to reorder them: The conditional is absolutely required, and must be present in the assembly code even after all compiler optimizations have been applied. Therefore, if you need ordering in this example, you need explicit memory barriers, for example, smp_store_release(): q = ACCESS_ONCE(a); if (q) { smp_store_release(&b, p); do_something(); } else { smp_store_release(&b, p); do_something_else(); } In contrast, without explicit memory barriers, two-legged-if control ordering is guaranteed only when the stores differ, for example: q = ACCESS_ONCE(a); if (q) { ACCESS_ONCE(b) = p; do_something(); } else { ACCESS_ONCE(b) = r; do_something_else(); } The initial ACCESS_ONCE() is still required to prevent the compiler from proving the value of 'a'. In addition, you need to be careful what you do with the local variable 'q', otherwise the compiler might be able to guess the value and again remove the needed conditional. For example: q = ACCESS_ONCE(a); if (q % MAX) { ACCESS_ONCE(b) = p; do_something(); } else { ACCESS_ONCE(b) = r; do_something_else(); } If MAX is defined to be 1, then the compiler knows that (q % MAX) is equal to zero, in which case the compiler is within its rights to transform the above code into the following: q = ACCESS_ONCE(a); ACCESS_ONCE(b) = p; do_something_else(); Given this transformation, the CPU is not required to respect the ordering between the load from variable 'a' and the store to variable 'b'. It is tempting to add a barrier(), but this does not help. The conditional is gone, and the barrier won't bring it back. Therefore, if you are relying on this ordering, you should make sure that MAX is greater than one, perhaps as follows: q = ACCESS_ONCE(a); BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */ if (q % MAX) { ACCESS_ONCE(b) = p; do_something(); } else { ACCESS_ONCE(b) = r; do_something_else(); } Please note once again that the stores to 'b' differ. If they were identical, as noted earlier, the compiler could pull this store outside of the 'if' statement. You must also be careful not to rely too much on boolean short-circuit evaluation. Consider this example: q = ACCESS_ONCE(a); if (a || 1 > 0) ACCESS_ONCE(b) = 1; Because the second condition is always true, the compiler can transform this example as following, defeating control dependency: q = ACCESS_ONCE(a); ACCESS_ONCE(b) = 1; This example underscores the need to ensure that the compiler cannot out-guess your code. More generally, although ACCESS_ONCE() does force the compiler to actually emit code for a given load, it does not force the compiler to use the results. Finally, control dependencies do -not- provide transitivity. This is demonstrated by two related examples, with the initial values of x and y both being zero: CPU 0 CPU 1 ===================== ===================== r1 = ACCESS_ONCE(x); r2 = ACCESS_ONCE(y); if (r1 > 0) if (r2 > 0) ACCESS_ONCE(y) = 1; ACCESS_ONCE(x) = 1; assert(!(r1 == 1 && r2 == 1)); The above two-CPU example will never trigger the assert(). However, if control dependencies guaranteed transitivity (which they do not), then adding the following CPU would guarantee a related assertion: CPU 2 ===================== ACCESS_ONCE(x) = 2; assert(!(r1 == 2 && r2 == 1 && x == 2)); /* FAILS!!! */ But because control dependencies do -not- provide transitivity, the above assertion can fail after the combined three-CPU example completes. If you need the three-CPU example to provide ordering, you will need smp_mb() between the loads and stores in the CPU 0 and CPU 1 code fragments, that is, just before or just after the "if" statements. These two examples are the LB and WWC litmus tests from this paper: http://www.cl.cam.ac.uk/users/pes20/ppc-supplemental/test6.pdf and this site: https://www.cl.cam.ac.uk/~pes20/ppcmem/index.html. In summary: (*) Control dependencies can order prior loads against later stores. However, they do -not- guarantee any other sort of ordering: Not prior loads against later loads, nor prior stores against later anything. If you need these other forms of ordering, use smp_rmb(), smp_wmb(), or, in the case of prior stores and later loads, smp_mb(). (*) If both legs of the "if" statement begin with identical stores to the same variable, a barrier() statement is required at the beginning of each leg of the "if" statement. (*) Control dependencies require at least one run-time conditional between the prior load and the subsequent store, and this conditional must involve the prior load. If the compiler is able to optimize the conditional away, it will have also optimized away the ordering. Careful use of ACCESS_ONCE() can help to preserve the needed conditional. (*) Control dependencies require that the compiler avoid reordering the dependency into nonexistence. Careful use of ACCESS_ONCE() or barrier() can help to preserve your control dependency. Please see the Compiler Barrier section for more information. (*) Control dependencies do -not- provide transitivity. If you need transitivity, use smp_mb(). SMP BARRIER PAIRING ------------------- When dealing with CPU-CPU interactions, certain types of memory barrier should always be paired. A lack of appropriate pairing is almost certainly an error. General barriers pair with each other, though they also pair with most other types of barriers, albeit without transitivity. An acquire barrier pairs with a release barrier, but both may also pair with other barriers, including of course general barriers. A write barrier pairs with a data dependency barrier, an acquire barrier, a release barrier, a read barrier, or a general barrier. Similarly a read barrier or a data dependency barrier pairs with a write barrier, an acquire barrier, a release barrier, or a general barrier: CPU 1 CPU 2 =============== =============== ACCESS_ONCE(a) = 1; ACCESS_ONCE(b) = 2; x = ACCESS_ONCE(b); y = ACCESS_ONCE(a); Or: CPU 1 CPU 2 =============== =============================== a = 1; ACCESS_ONCE(b) = &a; x = ACCESS_ONCE(b); y = *x; Basically, the read barrier always has to be there, even though it can be of the "weaker" type. [!] Note that the stores before the write barrier would normally be expected to match the loads after the read barrier or the data dependency barrier, and vice versa: CPU 1 CPU 2 =================== =================== ACCESS_ONCE(a) = 1; }---- --->{ v = ACCESS_ONCE(c); ACCESS_ONCE(b) = 2; } \ / { w = ACCESS_ONCE(d); \ ACCESS_ONCE(c) = 3; } / \ { x = ACCESS_ONCE(a); ACCESS_ONCE(d) = 4; }---- --->{ y = ACCESS_ONCE(b); EXAMPLES OF MEMORY BARRIER SEQUENCES ------------------------------------ Firstly, write barriers act as partial orderings on store operations. Consider the following sequence of events: CPU 1 ======================= STORE A = 1 STORE B = 2 STORE C = 3 STORE D = 4 STORE E = 5 This sequence of events is committed to the memory coherence system in an order that the rest of the system might perceive as the unordered set of { STORE A, STORE B, STORE C } all occurring before the unordered set of { STORE D, STORE E }: +-------+ : : | | +------+ | |------>| C=3 | } /\ | | : +------+ }----- \ -----> Events perceptible to | | : | A=1 | } \/ the rest of the system | | : +------+ } | CPU 1 | : | B=2 | } | | +------+ } | | wwwwwwwwwwwwwwww } <--- At this point the write barrier | | +------+ } requires all stores prior to the | | : | E=5 | } barrier to be committed before | | : +------+ } further stores may take place | |------>| D=4 | } | | +------+ +-------+ : : | | Sequence in which stores are committed to the | memory system by CPU 1 V Secondly, data dependency barriers act as partial orderings on data-dependent loads. Consider the following sequence of events: CPU 1 CPU 2 ======================= ======================= { B = 7; X = 9; Y = 8; C = &Y } STORE A = 1 STORE B = 2 STORE C = &B LOAD X STORE D = 4 LOAD C (gets &B) LOAD *C (reads B) Without intervention, CPU 2 may perceive the events on CPU 1 in some effectively random order, despite the write barrier issued by CPU 1: +-------+ : : : : | | +------+ +-------+ | Sequence of update | |------>| B=2 |----- --->| Y->8 | | of perception on | | : +------+ \ +-------+ | CPU 2 | CPU 1 | : | A=1 | \ --->| C->&Y | V | | +------+ | +-------+ | | wwwwwwwwwwwwwwww | : : | | +------+ | : : | | : | C=&B |--- | : : +-------+ | | : +------+ \ | +-------+ | | | |------>| D=4 | ----------->| C->&B |------>| | | | +------+ | +-------+ | | +-------+ : : | : : | | | : : | | | : : | CPU 2 | | +-------+ | | Apparently incorrect ---> | | B->7 |------>| | perception of B (!) | +-------+ | | | : : | | | +-------+ | | The load of X holds ---> \ | X->9 |------>| | up the maintenance \ +-------+ | | of coherence of B ----->| B->2 | +-------+ +-------+ : : In the above example, CPU 2 perceives that B is 7, despite the load of *C (which would be B) coming after the LOAD of C. If, however, a data dependency barrier were to be placed between the load of C and the load of *C (ie: B) on CPU 2: CPU 1 CPU 2 ======================= ======================= { B = 7; X = 9; Y = 8; C = &Y } STORE A = 1 STORE B = 2 STORE C = &B LOAD X STORE D = 4 LOAD C (gets &B) LOAD *C (reads B) then the following will occur: +-------+ : : : : | | +------+ +-------+ | |------>| B=2 |----- --->| Y->8 | | | : +------+ \ +-------+ | CPU 1 | : | A=1 | \ --->| C->&Y | | | +------+ | +-------+ | | wwwwwwwwwwwwwwww | : : | | +------+ | : : | | : | C=&B |--- | : : +-------+ | | : +------+ \ | +-------+ | | | |------>| D=4 | ----------->| C->&B |------>| | | | +------+ | +-------+ | | +-------+ : : | : : | | | : : | | | : : | CPU 2 | | +-------+ | | | | X->9 |------>| | | +-------+ | | Makes sure all effects ---> \ ddddddddddddddddd | | prior to the store of C \ +-------+ | | are perceptible to ----->| B->2 |------>| | subsequent loads +-------+ | | : : +-------+ And thirdly, a read barrier acts as a partial order on loads. Consider the following sequence of events: CPU 1 CPU 2 ======================= ======================= { A = 0, B = 9 } STORE A=1 STORE B=2 LOAD B LOAD A Without intervention, CPU 2 may then choose to perceive the events on CPU 1 in some effectively random order, despite the write barrier issued by CPU 1: +-------+ : : : : | | +------+ +-------+ | |------>| A=1 |------ --->| A->0 | | | +------+ \ +-------+ | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 | | | +------+ | +-------+ | |------>| B=2 |--- | : : | | +------+ \ | : : +-------+ +-------+ : : \ | +-------+ | | ---------->| B->2 |------>| | | +-------+ | CPU 2 | | | A->0 |------>| | | +-------+ | | | : : +-------+ \ : : \ +-------+ ---->| A->1 | +-------+ : : If, however, a read barrier were to be placed between the load of B and the load of A on CPU 2: CPU 1 CPU 2 ======================= ======================= { A = 0, B = 9 } STORE A=1 STORE B=2 LOAD B LOAD A then the partial ordering imposed by CPU 1 will be perceived correctly by CPU 2: +-------+ : : : : | | +------+ +-------+ | |------>| A=1 |------ --->| A->0 | | | +------+ \ +-------+ | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 | | | +------+ | +-------+ | |------>| B=2 |--- | : : | | +------+ \ | : : +-------+ +-------+ : : \ | +-------+ | | ---------->| B->2 |------>| | | +-------+ | CPU 2 | | : : | | | : : | | At this point the read ----> \ rrrrrrrrrrrrrrrrr | | barrier causes all effects \ +-------+ | | prior to the storage of B ---->| A->1 |------>| | to be perceptible to CPU 2 +-------+ | | : : +-------+ To illustrate this more completely, consider what could happen if the code contained a load of A either side of the read barrier: CPU 1 CPU 2 ======================= ======================= { A = 0, B = 9 } STORE A=1 STORE B=2 LOAD B LOAD A [first load of A] LOAD A [second load of A] Even though the two loads of A both occur after the load of B, they may both come up with different values: +-------+ : : : : | | +------+ +-------+ | |------>| A=1 |------ --->| A->0 | | | +------+ \ +-------+ | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 | | | +------+ | +-------+ | |------>| B=2 |--- | : : | | +------+ \ | : : +-------+ +-------+ : : \ | +-------+ | | ---------->| B->2 |------>| | | +-------+ | CPU 2 | | : : | | | : : | | | +-------+ | | | | A->0 |------>| 1st | | +-------+ | | At this point the read ----> \ rrrrrrrrrrrrrrrrr | | barrier causes all effects \ +-------+ | | prior to the storage of B ---->| A->1 |------>| 2nd | to be perceptible to CPU 2 +-------+ | | : : +-------+ But it may be that the update to A from CPU 1 becomes perceptible to CPU 2 before the read barrier completes anyway: +-------+ : : : : | | +------+ +-------+ | |------>| A=1 |------ --->| A->0 | | | +------+ \ +-------+ | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 | | | +------+ | +-------+ | |------>| B=2 |--- | : : | | +------+ \ | : : +-------+ +-------+ : : \ | +-------+ | | ---------->| B->2 |------>| | | +-------+ | CPU 2 | | : : | | \ : : | | \ +-------+ | | ---->| A->1 |------>| 1st | +-------+ | | rrrrrrrrrrrrrrrrr | | +-------+ | | | A->1 |------>| 2nd | +-------+ | | : : +-------+ The guarantee is that the second load will always come up with A == 1 if the load of B came up with B == 2. No such guarantee exists for the first load of A; that may come up with either A == 0 or A == 1. READ MEMORY BARRIERS VS LOAD SPECULATION ---------------------------------------- Many CPUs speculate with loads: that is they see that they will need to load an item from memory, and they find a time where they're not using the bus for any other loads, and so do the load in advance - even though they haven't actually got to that point in the instruction execution flow yet. This permits the actual load instruction to potentially complete immediately because the CPU already has the value to hand. It may turn out that the CPU didn't actually need the value - perhaps because a branch circumvented the load - in which case it can discard the value or just cache it for later use. Consider: CPU 1 CPU 2 ======================= ======================= LOAD B DIVIDE } Divide instructions generally DIVIDE } take a long time to perform LOAD A Which might appear as this: : : +-------+ +-------+ | | --->| B->2 |------>| | +-------+ | CPU 2 | : :DIVIDE | | +-------+ | | The CPU being busy doing a ---> --->| A->0 |~~~~ | | division speculates on the +-------+ ~ | | LOAD of A : : ~ | | : :DIVIDE | | : : ~ | | Once the divisions are complete --> : : ~-->| | the CPU can then perform the : : | | LOAD with immediate effect : : +-------+ Placing a read barrier or a data dependency barrier just before the second load: CPU 1 CPU 2 ======================= ======================= LOAD B DIVIDE DIVIDE LOAD A will force any value speculatively obtained to be reconsidered to an extent dependent on the type of barrier used. If there was no change made to the speculated memory location, then the speculated value will just be used: : : +-------+ +-------+ | | --->| B->2 |------>| | +-------+ | CPU 2 | : :DIVIDE | | +-------+ | | The CPU being busy doing a ---> --->| A->0 |~~~~ | | division speculates on the +-------+ ~ | | LOAD of A : : ~ | | : :DIVIDE | | : : ~ | | : : ~ | | rrrrrrrrrrrrrrrr~ | | : : ~ | | : : ~-->| | : : | | : : +-------+ but if there was an update or an invalidation from another CPU pending, then the speculation will be cancelled and the value reloaded: : : +-------+ +-------+ | | --->| B->2 |------>| | +-------+ | CPU 2 | : :DIVIDE | | +-------+ | | The CPU being busy doing a ---> --->| A->0 |~~~~ | | division speculates on the +-------+ ~ | | LOAD of A : : ~ | | : :DIVIDE | | : : ~ | | : : ~ | | rrrrrrrrrrrrrrrrr | | +-------+ | | The speculation is discarded ---> --->| A->1 |------>| | and an updated value is +-------+ | | retrieved : : +-------+ TRANSITIVITY ------------ Transitivity is a deeply intuitive notion about ordering that is not always provided by real computer systems. The following example demonstrates transitivity (also called "cumulativity"): CPU 1 CPU 2 CPU 3 ======================= ======================= ======================= { X = 0, Y = 0 } STORE X=1 LOAD X STORE Y=1 LOAD Y LOAD X Suppose that CPU 2's load from X returns 1 and its load from Y returns 0. This indicates that CPU 2's load from X in some sense follows CPU 1's store to X and that CPU 2's load from Y in some sense preceded CPU 3's store to Y. The question is then "Can CPU 3's load from X return 0?" Because CPU 2's load from X in some sense came after CPU 1's store, it is natural to expect that CPU 3's load from X must therefore return 1. This expectation is an example of transitivity: if a load executing on CPU A follows a load from the same variable executing on CPU B, then CPU A's load must either return the same value that CPU B's load did, or must return some later value. In the Linux kernel, use of general memory barriers guarantees transitivity. Therefore, in the above example, if CPU 2's load from X returns 1 and its load from Y returns 0, then CPU 3's load from X must also return 1. However, transitivity is -not- guaranteed for read or write barriers. For example, suppose that CPU 2's general barrier in the above example is changed to a read barrier as shown below: CPU 1 CPU 2 CPU 3 ======================= ======================= ======================= { X = 0, Y = 0 } STORE X=1 LOAD X STORE Y=1 LOAD Y LOAD X This substitution destroys transitivity: in this example, it is perfectly legal for CPU 2's load from X to return 1, its load from Y to return 0, and CPU 3's load from X to return 0. The key point is that although CPU 2's read barrier orders its pair of loads, it does not guarantee to order CPU 1's store. Therefore, if this example runs on a system where CPUs 1 and 2 share a store buffer or a level of cache, CPU 2 might have early access to CPU 1's writes. General barriers are therefore required to ensure that all CPUs agree on the combined order of CPU 1's and CPU 2's accesses. To reiterate, if your code requires transitivity, use general barriers throughout. ======================== EXPLICIT KERNEL BARRIERS ======================== The Linux kernel has a variety of different barriers that act at different levels: (*) Compiler barrier. (*) CPU memory barriers. (*) MMIO write barrier. COMPILER BARRIER ---------------- The Linux kernel has an explicit compiler barrier function that prevents the compiler from moving the memory accesses either side of it to the other side: barrier(); This is a general barrier -- there are no read-read or write-write variants of barrier(). However, ACCESS_ONCE() can be thought of as a weak form for barrier() that affects only the specific accesses flagged by the ACCESS_ONCE(). The barrier() function has the following effects: (*) Prevents the compiler from reordering accesses following the barrier() to precede any accesses preceding the barrier(). One example use for this property is to ease communication between interrupt-handler code and the code that was interrupted. (*) Within a loop, forces the compiler to load the variables used in that loop's conditional on each pass through that loop. The ACCESS_ONCE() function can prevent any number of optimizations that, while perfectly safe in single-threaded code, can be fatal in concurrent code. Here are some examples of these sorts of optimizations: (*) The compiler is within its rights to reorder loads and stores to the same variable, and in some cases, the CPU is within its rights to reorder loads to the same variable. This means that the following code: a[0] = x; a[1] = x; Might result in an older value of x stored in a[1] than in a[0]. Prevent both the compiler and the CPU from doing this as follows: a[0] = ACCESS_ONCE(x); a[1] = ACCESS_ONCE(x); In short, ACCESS_ONCE() provides cache coherence for accesses from multiple CPUs to a single variable. (*) The compiler is within its rights to merge successive loads from the same variable. Such merging can cause the compiler to "optimize" the following code: while (tmp = a) do_something_with(tmp); into the following code, which, although in some sense legitimate for single-threaded code, is almost certainly not what the developer intended: if (tmp = a) for (;;) do_something_with(tmp); Use ACCESS_ONCE() to prevent the compiler from doing this to you: while (tmp = ACCESS_ONCE(a)) do_something_with(tmp); (*) The compiler is within its rights to reload a variable, for example, in cases where high register pressure prevents the compiler from keeping all data of interest in registers. The compiler might therefore optimize the variable 'tmp' out of our previous example: while (tmp = a) do_something_with(tmp); This could result in the following code, which is perfectly safe in single-threaded code, but can be fatal in concurrent code: while (a) do_something_with(a); For example, the optimized version of this code could result in passing a zero to do_something_with() in the case where the variable a was modified by some other CPU between the "while" statement and the call to do_something_with(). Again, use ACCESS_ONCE() to prevent the compiler from doing this: while (tmp = ACCESS_ONCE(a)) do_something_with(tmp); Note that if the compiler runs short of registers, it might save tmp onto the stack. The overhead of this saving and later restoring is why compilers reload variables. Doing so is perfectly safe for single-threaded code, so you need to tell the compiler about cases where it is not safe. (*) The compiler is within its rights to omit a load entirely if it knows what the value will be. For example, if the compiler can prove that the value of variable 'a' is always zero, it can optimize this code: while (tmp = a) do_something_with(tmp); Into this: do { } while (0); This transformation is a win for single-threaded code because it gets rid of a load and a branch. The problem is that the compiler will carry out its proof assuming that the current CPU is the only one updating variable 'a'. If variable 'a' is shared, then the compiler's proof will be erroneous. Use ACCESS_ONCE() to tell the compiler that it doesn't know as much as it thinks it does: while (tmp = ACCESS_ONCE(a)) do_something_with(tmp); But please note that the compiler is also closely watching what you do with the value after the ACCESS_ONCE(). For example, suppose you do the following and MAX is a preprocessor macro with the value 1: while ((tmp = ACCESS_ONCE(a)) % MAX) do_something_with(tmp); Then the compiler knows that the result of the "%" operator applied to MAX will always be zero, again allowing the compiler to optimize the code into near-nonexistence. (It will still load from the variable 'a'.) (*) Similarly, the compiler is within its rights to omit a store entirely if it knows that the variable already has the value being stored. Again, the compiler assumes that the current CPU is the only one storing into the variable, which can cause the compiler to do the wrong thing for shared variables. For example, suppose you have the following: a = 0; /* Code that does not store to variable a. */ a = 0; The compiler sees that the value of variable 'a' is already zero, so it might well omit the second store. This would come as a fatal surprise if some other CPU might have stored to variable 'a' in the meantime. Use ACCESS_ONCE() to prevent the compiler from making this sort of wrong guess: ACCESS_ONCE(a) = 0; /* Code that does not store to variable a. */ ACCESS_ONCE(a) = 0; (*) The compiler is within its rights to reorder memory accesses unless you tell it not to. For example, consider the following interaction between process-level code and an interrupt handler: void process_level(void) { msg = get_message(); flag = true; } void interrupt_handler(void) { if (flag) process_message(msg); } There is nothing to prevent the compiler from transforming process_level() to the following, in fact, this might well be a win for single-threaded code: void process_level(void) { flag = true; msg = get_message(); } If the interrupt occurs between these two statement, then interrupt_handler() might be passed a garbled msg. Use ACCESS_ONCE() to prevent this as follows: void process_level(void) { ACCESS_ONCE(msg) = get_message(); ACCESS_ONCE(flag) = true; } void interrupt_handler(void) { if (ACCESS_ONCE(flag)) process_message(ACCESS_ONCE(msg)); } Note that the ACCESS_ONCE() wrappers in interrupt_handler() are needed if this interrupt handler can itself be interrupted by something that also accesses 'flag' and 'msg', for example, a nested interrupt or an NMI. Otherwise, ACCESS_ONCE() is not needed in interrupt_handler() other than for documentation purposes. (Note also that nested interrupts do not typically occur in modern Linux kernels, in fact, if an interrupt handler returns with interrupts enabled, you will get a WARN_ONCE() splat.) You should assume that the compiler can move ACCESS_ONCE() past code not containing ACCESS_ONCE(), barrier(), or similar primitives. This effect could also be achieved using barrier(), but ACCESS_ONCE() is more selective: With ACCESS_ONCE(), the compiler need only forget the contents of the indicated memory locations, while with barrier() the compiler must discard the value of all memory locations that it has currented cached in any machine registers. Of course, the compiler must also respect the order in which the ACCESS_ONCE()s occur, though the CPU of course need not do so. (*) The compiler is within its rights to invent stores to a variable, as in the following example: if (a) b = a; else b = 42; The compiler might save a branch by optimizing this as follows: b = 42; if (a) b = a; In single-threaded code, this is not only safe, but also saves a branch. Unfortunately, in concurrent code, this optimization could cause some other CPU to see a spurious value of 42 -- even if variable 'a' was never zero -- when loading variable 'b'. Use ACCESS_ONCE() to prevent this as follows: if (a) ACCESS_ONCE(b) = a; else ACCESS_ONCE(b) = 42; The compiler can also invent loads. These are usually less damaging, but they can result in cache-line bouncing and thus in poor performance and scalability. Use ACCESS_ONCE() to prevent invented loads. (*) For aligned memory locations whose size allows them to be accessed with a single memory-reference instruction, prevents "load tearing" and "store tearing," in which a single large access is replaced by multiple smaller accesses. For example, given an architecture having 16-bit store instructions with 7-bit immediate fields, the compiler might be tempted to use two 16-bit store-immediate instructions to implement the following 32-bit store: p = 0x00010002; Please note that GCC really does use this sort of optimization, which is not surprising given that it would likely take more than two instructions to build the constant and then store it. This optimization can therefore be a win in single-threaded code. In fact, a recent bug (since fixed) caused GCC to incorrectly use this optimization in a volatile store. In the absence of such bugs, use of ACCESS_ONCE() prevents store tearing in the following example: ACCESS_ONCE(p) = 0x00010002; Use of packed structures can also result in load and store tearing, as in this example: struct __attribute__((__packed__)) foo { short a; int b; short c; }; struct foo foo1, foo2; ... foo2.a = foo1.a; foo2.b = foo1.b; foo2.c = foo1.c; Because there are no ACCESS_ONCE() wrappers and no volatile markings, the compiler would be well within its rights to implement these three assignment statements as a pair of 32-bit loads followed by a pair of 32-bit stores. This would result in load tearing on 'foo1.b' and store tearing on 'foo2.b'. ACCESS_ONCE() again prevents tearing in this example: foo2.a = foo1.a; ACCESS_ONCE(foo2.b) = ACCESS_ONCE(foo1.b); foo2.c = foo1.c; All that aside, it is never necessary to use ACCESS_ONCE() on a variable that has been marked volatile. For example, because 'jiffies' is marked volatile, it is never necessary to say ACCESS_ONCE(jiffies). The reason for this is that ACCESS_ONCE() is implemented as a volatile cast, which has no effect when its argument is already marked volatile. Please note that these compiler barriers have no direct effect on the CPU, which may then reorder things however it wishes. CPU MEMORY BARRIERS ------------------- The Linux kernel has eight basic CPU memory barriers: TYPE MANDATORY SMP CONDITIONAL =============== ======================= =========================== GENERAL mb() smp_mb() WRITE wmb() smp_wmb() READ rmb() smp_rmb() DATA DEPENDENCY read_barrier_depends() smp_read_barrier_depends() All memory barriers except the data dependency barriers imply a compiler barrier. Data dependencies do not impose any additional compiler ordering. Aside: In the case of data dependencies, the compiler would be expected to issue the loads in the correct order (eg. `a[b]` would have to load the value of b before loading a[b]), however there is no guarantee in the C specification that the compiler may not speculate the value of b (eg. is equal to 1) and load a before b (eg. tmp = a[1]; if (b != 1) tmp = a[b]; ). There is also the problem of a compiler reloading b after having loaded a[b], thus having a newer copy of b than a[b]. A consensus has not yet been reached about these problems, however the ACCESS_ONCE macro is a good place to start looking. SMP memory barriers are reduced to compiler barriers on uniprocessor compiled systems because it is assumed that a CPU will appear to be self-consistent, and will order overlapping accesses correctly with respect to itself. [!] Note that SMP memory barriers _must_ be used to control the ordering of references to shared memory on SMP systems, though the use of locking instead is sufficient. Mandatory barriers should not be used to control SMP effects, since mandatory barriers unnecessarily impose overhead on UP systems. They may, however, be used to control MMIO effects on accesses through relaxed memory I/O windows. These are required even on non-SMP systems as they affect the order in which memory operations appear to a device by prohibiting both the compiler and the CPU from reordering them. There are some more advanced barrier functions: (*) set_mb(var, value) This assigns the value to the variable and then inserts a full memory barrier after it, depending on the function. It isn't guaranteed to insert anything more than a compiler barrier in a UP compilation. (*) smp_mb__before_atomic(); (*) smp_mb__after_atomic(); These are for use with atomic (such as add, subtract, increment and decrement) functions that don't return a value, especially when used for reference counting. These functions do not imply memory barriers. These are also used for atomic bitop functions that do not return a value (such as set_bit and clear_bit). As an example, consider a piece of code that marks an object as being dead and then decrements the object's reference count: obj->dead = 1; smp_mb__before_atomic(); atomic_dec(&obj->ref_count); This makes sure that the death mark on the object is perceived to be set *before* the reference counter is decremented. See Documentation/atomic_ops.txt for more information. See the "Atomic operations" subsection for information on where to use these. (*) dma_wmb(); (*) dma_rmb(); These are for use with consistent memory to guarantee the ordering of writes or reads of shared memory accessible to both the CPU and a DMA capable device. For example, consider a device driver that shares memory with a device and uses a descriptor status value to indicate if the descriptor belongs to the device or the CPU, and a doorbell to notify it when new descriptors are available: if (desc->status != DEVICE_OWN) { /* do not read data until we own descriptor */ dma_rmb(); /* read/modify data */ read_data = desc->data; desc->data = write_data; /* flush modifications before status update */ dma_wmb(); /* assign ownership */ desc->status = DEVICE_OWN; /* force memory to sync before notifying device via MMIO */ wmb(); /* notify device of new descriptors */ writel(DESC_NOTIFY, doorbell); } The dma_rmb() allows us guarantee the device has released ownership before we read the data from the descriptor, and he dma_wmb() allows us to guarantee the data is written to the descriptor before the device can see it now has ownership. The wmb() is needed to guarantee that the cache coherent memory writes have completed before attempting a write to the cache incoherent MMIO region. See Documentation/DMA-API.txt for more information on consistent memory. MMIO WRITE BARRIER ------------------ The Linux kernel also has a special barrier for use with memory-mapped I/O writes: mmiowb(); This is a variation on the mandatory write barrier that caus