Lines Matching +full:in +full:- +full:memory

2 			 LINUX KERNEL MEMORY BARRIERS
16 meant as a guide to using the various memory barriers provided by Linux, but
17 in case of any doubt (and there are many) please ask. Some doubts may be
18 resolved by referring to the formal memory consistency model and related
19 documentation at tools/memory-model/. Nevertheless, even this memory
37 Note also that it is possible that a barrier may be a no-op for an
39 unnecessary in that case.
46 (*) Abstract memory access model.
48 - Device operations.
49 - Guarantees.
51 (*) What are memory barriers?
53 - Varieties of memory barrier.
54 - What may not be assumed about memory barriers?
55 - Address-dependency barriers (historical).
56 - Control dependencies.
57 - SMP barrier pairing.
58 - Examples of memory barrier sequences.
59 - Read memory barriers vs load speculation.
60 - Multicopy atomicity.
64 - Compiler barrier.
65 - CPU memory barriers.
67 (*) Implicit kernel memory barriers.
69 - Lock acquisition functions.
70 - Interrupt disabling functions.
71 - Sleep and wake-up functions.
72 - Miscellaneous functions.
74 (*) Inter-CPU acquiring barrier effects.
76 - Acquires vs memory accesses.
78 (*) Where are memory barriers needed?
80 - Interprocessor interaction.
81 - Atomic operations.
82 - Accessing devices.
83 - Interrupts.
91 - Cache coherency vs DMA.
92 - Cache coherency vs MMIO.
96 - And then there's the Alpha.
97 - Virtual Machine Guests.
101 - Circular buffers.
107 ABSTRACT MEMORY ACCESS MODEL
115 +-------+ : +--------+ : +-------+
118 | CPU 1 |<----->| Memory |<----->| CPU 2 |
121 +-------+ : +--------+ : +-------+
126 | : +--------+ : |
129 +---------->| Device |<----------+
132 : +--------+ :
135 Each CPU executes a program that generates memory access operations. In the
136 abstract CPU, memory operation ordering is very relaxed, and a CPU may actually
137 perform the memory operations in any order it likes, provided program causality
139 instructions it emits in any order it likes, provided it doesn't affect the
142 So in the above diagram, the effects of the memory operations performed by a
155 The set of accesses as seen by the memory system in the middle can be arranged
156 in 24 different combinations:
158 STORE A=3, STORE B=4, y=LOAD A->3, x=LOAD B->4
159 STORE A=3, STORE B=4, x=LOAD B->4, y=LOAD A->3
160 STORE A=3, y=LOAD A->3, STORE B=4, x=LOAD B->4
161 STORE A=3, y=LOAD A->3, x=LOAD B->2, STORE B=4
162 STORE A=3, x=LOAD B->2, STORE B=4, y=LOAD A->3
163 STORE A=3, x=LOAD B->2, y=LOAD A->3, STORE B=4
164 STORE B=4, STORE A=3, y=LOAD A->3, x=LOAD B->4
168 and can thus result in four different combinations of values:
176 Furthermore, the stores committed by a CPU to the memory system may not be
177 perceived by the loads made by another CPU in the same order as the stores were
202 -----------------
204 Some devices present their control interfaces as collections of memory
205 locations, but the order in which the control registers are accessed is very
219 the second of which will almost certainly result in a malfunction, since it set
224 ----------
228 (*) On any given CPU, dependent memory accesses will be issued in order, with
233 the CPU will issue the following memory operations:
237 and always in that order. However, on DEC Alpha, READ_ONCE() also
238 emits a memory-barrier instruction, so that a DEC Alpha CPU will
239 instead issue the following memory operations:
251 the CPU will only issue the following sequence of memory operations:
264 memory).
269 with memory references that are not protected by READ_ONCE() and
271 do all sorts of "creative" transformations, which are covered in
275 in the order given. This means that for:
288 (*) It _must_ be assumed that overlapping memory accesses may be merged or
309 And there are anti-guarantees:
312 generate code to modify these using non-atomic read-modify-write
316 (*) Even in cases where bitfields are protected by locks, all fields
317 in a given bitfield must be protected by one lock. If two fields
318 in a given bitfield are protected by different locks, the compiler's
319 non-atomic read-modify-write sequences can cause an update to one
326 "char", two-byte alignment for "short", four-byte alignment for
327 "int", and either four-byte or eight-byte alignment for "long",
328 on 32-bit and 64-bit systems, respectively. Note that these
330 using older pre-C11 compilers (for example, gcc 4.6). The portion
332 defines "memory location" as follows:
334 memory location
336 of adjacent bit-fields all having nonzero width
339 separate memory locations without interfering with
342 NOTE 2: A bit-field and an adjacent non-bit-field member
343 are in separate memory locations. The same applies
344 to two bit-fields, if one is declared inside a nested
346 are separated by a zero-length bit-field declaration,
347 or if they are separated by a non-bit-field member
349 bit-fields in the same structure if all members declared
350 between them are also bit-fields, no matter what the
351 sizes of those intervening bit-fields happen to be.
355 WHAT ARE MEMORY BARRIERS?
358 As can be seen above, independent memory operations are effectively performed
359 in random order, but this can be a problem for CPU-CPU interaction and for I/O.
363 Memory barriers are such interventions. They impose a perceived partial
364 ordering over the memory operations on either side of the barrier.
366 Such enforcement is important because the CPUs and other devices in a system
368 deferral and combination of memory operations; speculative loads; speculative
369 branch prediction and various types of caching. Memory barriers are used to
374 VARIETIES OF MEMORY BARRIER
375 ---------------------------
377 Memory barriers come in four basic varieties:
379 (1) Write (or store) memory barriers.
381 A write memory barrier gives a guarantee that all the STORE operations
390 memory system as time progresses. All stores _before_ a write barrier
394 address-dependency barriers; see the "SMP barrier pairing" subsection.
397 (2) Address-dependency barriers (historical).
398 [!] This section is marked as HISTORICAL: it covers the long-obsolete
400 implicit in all marked accesses. For more up-to-date information,
404 An address-dependency barrier is a weaker form of read barrier. In the
407 the second load will be directed), an address-dependency barrier would
411 An address-dependency barrier is a partial ordering on interdependent
415 As mentioned in (1), the other CPUs in the system can be viewed as
416 committing sequences of stores to the memory system that the CPU being
417 considered can then perceive. An address-dependency barrier issued by
422 the address-dependency barrier.
424 See the "Examples of memory barrier sequences" subsection for diagrams
434 [!] Note that address-dependency barriers should normally be paired with
437 [!] Kernel release v5.9 removed kernel APIs for explicit address-
440 address-dependency barriers.
442 (3) Read (or load) memory barriers.
444 A read barrier is an address-dependency barrier plus a guarantee that all
452 Read memory barriers imply address-dependency barriers, and so can
459 (4) General memory barriers.
461 A general memory barrier gives a guarantee that all the LOAD and STORE
466 A general memory barrier is a partial ordering over both loads and stores.
468 General memory barriers imply both read and write memory barriers, and so
476 This acts as a one-way permeable barrier. It guarantees that all memory
482 Memory operations that occur before an ACQUIRE operation may appear to
491 This also acts as a one-way permeable barrier. It guarantees that all
492 memory operations before the RELEASE operation will appear to happen
497 Memory operations that occur after a RELEASE operation may appear to
501 for other sorts of memory barrier. In addition, a RELEASE+ACQUIRE pair is
502 -not- guaranteed to act as a full memory barrier. However, after an
503 ACQUIRE on a given variable, all memory accesses preceding any prior
504 RELEASE on that same variable are guaranteed to be visible. In other
512 A subset of the atomic operations described in atomic_t.txt have ACQUIRE and
513 RELEASE variants in addition to fully-ordered and relaxed (no barrier
518 Memory barriers are only required where there's a possibility of interaction
520 there won't be any such interaction in any particular piece of code, then
521 memory barriers are unnecessary in that piece of code.
529 WHAT MAY NOT BE ASSUMED ABOUT MEMORY BARRIERS?
530 ----------------------------------------------
532 There are certain things that the Linux kernel memory barriers do not guarantee:
534 (*) There is no guarantee that any of the memory accesses specified before a
535 memory barrier will be _complete_ by the completion of a memory barrier
536 instruction; the barrier can be considered to draw a line in that CPU's
539 (*) There is no guarantee that issuing a memory barrier on one CPU will have
540 any direct effect on another CPU or any other hardware in the system. The
541 indirect effect will be the order in which the second CPU sees the effects
545 from a second CPU's accesses, even _if_ the second CPU uses a memory
546 barrier, unless the first CPU _also_ uses a matching memory barrier (see
549 (*) There is no guarantee that some intervening piece of off-the-CPU
550 hardware[*] will not reorder the memory accesses. CPU cache coherency
551 mechanisms should propagate the indirect effects of a memory barrier
552 between CPUs, but might not do so in order.
556 Documentation/driver-api/pci/pci.rst
557 Documentation/core-api/dma-api-howto.rst
558 Documentation/core-api/dma-api.rst
561 ADDRESS-DEPENDENCY BARRIERS (HISTORICAL)
562 ----------------------------------------
563 [!] This section is marked as HISTORICAL: it covers the long-obsolete
565 in all marked accesses. For more up-to-date information, including
571 to this section are those working on DEC Alpha architecture-specific code
573 those who are interested in the history, here is the story of
574 address-dependency barriers.
576 [!] While address dependencies are observed in both load-to-load and
577 load-to-store relations, address-dependency barriers are not necessary
578 for load-to-store situations.
580 The requirement of address-dependency barriers is a little subtle, and
593 [!] READ_ONCE_OLD() corresponds to READ_ONCE() of pre-4.15 kernel, which
594 doesn't imply an address-dependency barrier.
611 To deal with this, READ_ONCE() provides an implicit address-dependency barrier
621 <implicit address-dependency barrier>
630 even-numbered cache lines and the other bank processes odd-numbered cache
631 lines. The pointer P might be stored in an odd-numbered cache line, and the
632 variable B might be stored in an even-numbered cache line. Then, if the
633 even-numbered bank of the reading CPU's cache is extremely busy while the
634 odd-numbered bank is idle, one can see the new value of the pointer P (&B),
638 An address-dependency barrier is not required to order dependent writes
644 dependencies in a great many highly creative ways.
655 Therefore, no address-dependency barrier is required to order the read into
656 Q with the store into *Q. In other words, this outcome is prohibited,
657 even without an implicit address-dependency barrier of modern READ_ONCE():
662 of dependency ordering is to -prevent- writes to the data structure, along
673 The address-dependency barrier is very important to the RCU system,
674 for example. See rcu_assign_pointer() and rcu_dereference() in
681 --------------------
687 A load-load control dependency requires a full read memory barrier, not
688 simply an (implicit) address-dependency barrier to make it work correctly.
692 <implicit address-dependency barrier>
699 dependency, but rather a control dependency that the CPU may short-circuit
700 by attempting to predict the outcome in advance, so that other CPUs see
701 the load from b as having happened before the load from a. In such a case
710 However, stores are not speculated. This means that ordering -is- provided
711 for load-store control dependencies, as in the following example:
723 Either can result in highly counterintuitive effects on ordering.
726 variable 'a' is always non-zero, it would be well within its rights
756 /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
759 /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
765 The conditional is absolutely required, and must be present in the
767 Therefore, if you need ordering in this example, you need explicit
768 memory barriers, for example, smp_store_release():
779 In contrast, without explicit memory barriers, two-legged-if control
794 In addition, you need to be careful what you do with the local variable 'q',
808 equal to zero, in which case the compiler is within its rights to
836 You must also be careful not to rely too much on boolean short-circuit
851 out-guess your code. More generally, although READ_ONCE() does force
855 In addition, control dependencies apply only to the then-clause and
856 else-clause of the if-statement in question. In particular, it does
857 not necessarily apply to code following the if-statement:
867 It is tempting to argue that there in fact is ordering because the
871 conditional-move instructions, as in this fanciful pseudo-assembly
884 In short, control dependencies apply only to the stores in the then-clause
885 and else-clause of the if-statement in question (including functions
886 invoked by those two clauses), not to code following that if-statement.
894 In summary:
897 However, they do -not- guarantee any other sort of ordering:
900 use smp_rmb(), smp_wmb(), or, in the case of prior stores and
906 to carry out the stores. Please note that it is -not- sufficient
912 (*) Control dependencies require at least one run-time conditional
924 (*) Control dependencies apply only to the then-clause and else-clause
925 of the if-statement containing the control dependency, including
927 do -not- apply to code following the if-statement containing the
932 (*) Control dependencies do -not- provide multicopy atomicity. If you
940 -------------------
942 When dealing with CPU-CPU interactions, certain types of memory barrier should
949 with an address-dependency barrier, a control dependency, an acquire barrier,
951 read barrier, control dependency, or an address-dependency barrier pairs
970 <implicit address-dependency barrier>
990 match the loads after the read barrier or the address-dependency barrier, and
995 WRITE_ONCE(a, 1); }---- --->{ v = READ_ONCE(c);
999 WRITE_ONCE(d, 4); }---- --->{ y = READ_ONCE(b);
1002 EXAMPLES OF MEMORY BARRIER SEQUENCES
1003 ------------------------------------
1017 This sequence of events is committed to the memory coherence system in an order
1022 +-------+ : :
1023 | | +------+
1024 | |------>| C=3 | } /\
1025 | | : +------+ }----- \ -----> Events perceptible to
1027 | | : +------+ }
1029 | | +------+ }
1030 | | wwwwwwwwwwwwwwww } <--- At this point the write barrier
1031 | | +------+ } requires all stores prior to the
1033 | | : +------+ } further stores may take place
1034 | |------>| D=4 | }
1035 | | +------+
1036 +-------+ : :
1038 | Sequence in which stores are committed to the
1039 | memory system by CPU 1
1043 Secondly, address-dependency barriers act as partial orderings on address-
1056 Without intervention, CPU 2 may perceive the events on CPU 1 in some
1059 +-------+ : : : :
1060 | | +------+ +-------+ | Sequence of update
1061 | |------>| B=2 |----- --->| Y->8 | | of perception on
1062 | | : +------+ \ +-------+ | CPU 2
1063 | CPU 1 | : | A=1 | \ --->| C->&Y | V
1064 | | +------+ | +-------+
1066 | | +------+ | : :
1067 | | : | C=&B |--- | : : +-------+
1068 | | : +------+ \ | +-------+ | |
1069 | |------>| D=4 | ----------->| C->&B |------>| |
1070 | | +------+ | +-------+ | |
1071 +-------+ : : | : : | |
1074 | +-------+ | |
1075 Apparently incorrect ---> | | B->7 |------>| |
1076 perception of B (!) | +-------+ | |
1078 | +-------+ | |
1079 The load of X holds ---> \ | X->9 |------>| |
1080 up the maintenance \ +-------+ | |
1081 of coherence of B ----->| B->2 | +-------+
1082 +-------+
1086 In the above example, CPU 2 perceives that B is 7, despite the load of *C
1089 If, however, an address-dependency barrier were to be placed between the load
1100 <address-dependency barrier>
1105 +-------+ : : : :
1106 | | +------+ +-------+
1107 | |------>| B=2 |----- --->| Y->8 |
1108 | | : +------+ \ +-------+
1109 | CPU 1 | : | A=1 | \ --->| C->&Y |
1110 | | +------+ | +-------+
1112 | | +------+ | : :
1113 | | : | C=&B |--- | : : +-------+
1114 | | : +------+ \ | +-------+ | |
1115 | |------>| D=4 | ----------->| C->&B |------>| |
1116 | | +------+ | +-------+ | |
1117 +-------+ : : | : : | |
1120 | +-------+ | |
1121 | | X->9 |------>| |
1122 | +-------+ | |
1123 Makes sure all effects ---> \ aaaaaaaaaaaaaaaaa | |
1124 prior to the store of C \ +-------+ | |
1125 are perceptible to ----->| B->2 |------>| |
1126 subsequent loads +-------+ | |
1127 : : +-------+
1142 Without intervention, CPU 2 may then choose to perceive the events on CPU 1 in
1145 +-------+ : : : :
1146 | | +------+ +-------+
1147 | |------>| A=1 |------ --->| A->0 |
1148 | | +------+ \ +-------+
1149 | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
1150 | | +------+ | +-------+
1151 | |------>| B=2 |--- | : :
1152 | | +------+ \ | : : +-------+
1153 +-------+ : : \ | +-------+ | |
1154 ---------->| B->2 |------>| |
1155 | +-------+ | CPU 2 |
1156 | | A->0 |------>| |
1157 | +-------+ | |
1158 | : : +-------+
1160 \ +-------+
1161 ---->| A->1 |
1162 +-------+
1182 +-------+ : : : :
1183 | | +------+ +-------+
1184 | |------>| A=1 |------ --->| A->0 |
1185 | | +------+ \ +-------+
1186 | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
1187 | | +------+ | +-------+
1188 | |------>| B=2 |--- | : :
1189 | | +------+ \ | : : +-------+
1190 +-------+ : : \ | +-------+ | |
1191 ---------->| B->2 |------>| |
1192 | +-------+ | CPU 2 |
1195 At this point the read ----> \ rrrrrrrrrrrrrrrrr | |
1196 barrier causes all effects \ +-------+ | |
1197 prior to the storage of B ---->| A->1 |------>| |
1198 to be perceptible to CPU 2 +-------+ | |
1199 : : +-------+
1219 +-------+ : : : :
1220 | | +------+ +-------+
1221 | |------>| A=1 |------ --->| A->0 |
1222 | | +------+ \ +-------+
1223 | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
1224 | | +------+ | +-------+
1225 | |------>| B=2 |--- | : :
1226 | | +------+ \ | : : +-------+
1227 +-------+ : : \ | +-------+ | |
1228 ---------->| B->2 |------>| |
1229 | +-------+ | CPU 2 |
1232 | +-------+ | |
1233 | | A->0 |------>| 1st |
1234 | +-------+ | |
1235 At this point the read ----> \ rrrrrrrrrrrrrrrrr | |
1236 barrier causes all effects \ +-------+ | |
1237 prior to the storage of B ---->| A->1 |------>| 2nd |
1238 to be perceptible to CPU 2 +-------+ | |
1239 : : +-------+
1245 +-------+ : : : :
1246 | | +------+ +-------+
1247 | |------>| A=1 |------ --->| A->0 |
1248 | | +------+ \ +-------+
1249 | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
1250 | | +------+ | +-------+
1251 | |------>| B=2 |--- | : :
1252 | | +------+ \ | : : +-------+
1253 +-------+ : : \ | +-------+ | |
1254 ---------->| B->2 |------>| |
1255 | +-------+ | CPU 2 |
1258 \ +-------+ | |
1259 ---->| A->1 |------>| 1st |
1260 +-------+ | |
1262 +-------+ | |
1263 | A->1 |------>| 2nd |
1264 +-------+ | |
1265 : : +-------+
1273 READ MEMORY BARRIERS VS LOAD SPECULATION
1274 ----------------------------------------
1277 item from memory, and they find a time where they're not using the bus for any
1278 other loads, and so do the load in advance - even though they haven't actually
1279 got to that point in the instruction execution flow yet. This permits the
1283 It may turn out that the CPU didn't actually need the value - perhaps because a
1284 branch circumvented the load - in which case it can discard the value or just
1298 : : +-------+
1299 +-------+ | |
1300 --->| B->2 |------>| |
1301 +-------+ | CPU 2 |
1303 +-------+ | |
1304 The CPU being busy doing a ---> --->| A->0 |~~~~ | |
1305 division speculates on the +-------+ ~ | |
1309 Once the divisions are complete --> : : ~-->| |
1311 LOAD with immediate effect : : +-------+
1314 Placing a read barrier or an address-dependency barrier just before the second
1327 speculated memory location, then the speculated value will just be used:
1329 : : +-------+
1330 +-------+ | |
1331 --->| B->2 |------>| |
1332 +-------+ | CPU 2 |
1334 +-------+ | |
1335 The CPU being busy doing a ---> --->| A->0 |~~~~ | |
1336 division speculates on the +-------+ ~ | |
1343 : : ~-->| |
1345 : : +-------+
1351 : : +-------+
1352 +-------+ | |
1353 --->| B->2 |------>| |
1354 +-------+ | CPU 2 |
1356 +-------+ | |
1357 The CPU being busy doing a ---> --->| A->0 |~~~~ | |
1358 division speculates on the +-------+ ~ | |
1364 +-------+ | |
1365 The speculation is discarded ---> --->| A->1 |------>| |
1366 and an updated value is +-------+ | |
1367 retrieved : : +-------+
1371 --------------------
1376 CPUs agree on the order in which all stores become visible. However,
1380 time to all -other- CPUs. The remainder of this document discusses this
1395 CPU 3's load from Y. In addition, the memory barriers guarantee that
1399 Because CPU 3's load from X in some sense comes after CPU 2's load, it
1404 multicopy-atomic systems, CPU B's load must return either the same value
1408 The use of a general memory barrier in the example above compensates
1409 for any lack of multicopy atomicity. In the example, if CPU 2's load
1414 able to compensate for non-multicopy atomicity. For example, suppose
1425 This substitution allows non-multicopy atomicity to run rampant: in
1431 example runs on a non-multicopy-atomic system where CPUs 1 and 2 share a
1436 General barriers can compensate not only for non-multicopy atomicity,
1437 but can also generate additional ordering that can ensure that -all-
1438 CPUs will perceive the same order of -all- operations. In contrast, a
1439 chain of release-acquire pairs do not provide this additional ordering,
1442 in deference to the ghost of Herman Hollerith:
1474 Because cpu0(), cpu1(), and cpu2() participate in a chain of
1480 Furthermore, because of the release-acquire relationship between cpu0()
1486 However, the ordering provided by a release-acquire chain is local
1487 to the CPUs participating in that chain and does not apply to cpu3(),
1497 writes in order, CPUs not involved in the release-acquire chain might
1499 the weak memory-barrier instructions used to implement smp_load_acquire()
1501 subsequent loads in all cases. This means that cpu3() can see cpu0()'s
1502 store to u as happening -after- cpu1()'s load from v, even though
1503 both cpu0() and cpu1() agree that these two operations occurred in the
1506 However, please keep in mind that smp_load_acquire() is not magic.
1507 In particular, it simply reads from its argument with ordering. It does
1508 -not- ensure that any particular value will be read. Therefore, the
1529 (*) CPU memory barriers.
1533 ----------------
1536 compiler from moving the memory accesses either side of it to the other side:
1540 This is a general barrier -- there are no read-read or write-write
1550 interrupt-handler code and the code that was interrupted.
1553 in that loop's conditional on each pass through that loop.
1556 optimizations that, while perfectly safe in single-threaded code, can
1557 be fatal in concurrent code. Here are some examples of these sorts
1561 to the same variable, and in some cases, the CPU is within its
1568 Might result in an older value of x stored in a[1] than in a[0].
1574 In short, READ_ONCE() and WRITE_ONCE() provide cache coherence for
1584 into the following code, which, although in some sense legitimate
1585 for single-threaded code, is almost certainly not what the developer
1598 in cases where high register pressure prevents the compiler from
1599 keeping all data of interest in registers. The compiler might
1605 This could result in the following code, which is perfectly safe in
1606 single-threaded code, but can be fatal in concurrent code:
1611 For example, the optimized version of this code could result in
1612 passing a zero to do_something_with() in the case where the variable
1624 single-threaded code, so you need to tell the compiler about cases
1638 This transformation is a win for single-threaded code because it
1657 the code into near-nonexistence. (It will still load from the
1673 surprise if some other CPU might have stored to variable 'a' in the
1683 (*) The compiler is within its rights to reorder memory accesses unless
1685 between process-level code and an interrupt handler:
1700 process_level() to the following, in fact, this might well be a
1701 win for single-threaded code:
1725 Note that the READ_ONCE() and WRITE_ONCE() wrappers in
1729 and WRITE_ONCE() are not needed in interrupt_handler() other than
1731 do not typically occur in modern Linux kernels, in fact, if an
1742 indicated memory locations, while with barrier() the compiler must
1743 discard the value of all memory locations that it has currently
1744 cached in any machine registers. Of course, the compiler must also
1745 respect the order in which the READ_ONCE()s and WRITE_ONCE()s occur,
1749 as in the following example:
1762 In single-threaded code, this is not only safe, but also saves
1763 a branch. Unfortunately, in concurrent code, this optimization
1764 could cause some other CPU to see a spurious value of 42 -- even
1765 if variable 'a' was never zero -- when loading variable 'b'.
1774 damaging, but they can result in cache-line bouncing and thus in
1778 (*) For aligned memory locations whose size allows them to be accessed
1779 with a single memory-reference instruction, prevents "load tearing"
1780 and "store tearing," in which a single large access is replaced by
1782 16-bit store instructions with 7-bit immediate fields, the compiler
1783 might be tempted to use two 16-bit store-immediate instructions to
1784 implement the following 32-bit store:
1791 This optimization can therefore be a win in single-threaded code.
1792 In fact, a recent bug (since fixed) caused GCC to incorrectly use
1793 this optimization in a volatile store. In the absence of such bugs,
1794 use of WRITE_ONCE() prevents store tearing in the following example:
1798 Use of packed structures can also result in load and store tearing,
1799 as in this example:
1815 implement these three assignment statements as a pair of 32-bit
1816 loads followed by a pair of 32-bit stores. This would result in
1818 and WRITE_ONCE() again prevent tearing in this example:
1835 CPU MEMORY BARRIERS
1836 -------------------
1838 The Linux kernel has seven basic CPU memory barriers:
1848 All memory barriers except the address-dependency barriers imply a compiler
1851 Aside: In the case of address dependencies, the compiler would be expected
1852 to issue the loads in the correct order (eg. `a[b]` would have to load
1853 the value of b before loading a[b]), however there is no guarantee in
1861 SMP memory barriers are reduced to compiler barriers on uniprocessor compiled
1862 systems because it is assumed that a CPU will appear to be self-consistent,
1866 [!] Note that SMP memory barriers _must_ be used to control the ordering of
1867 references to shared memory on SMP systems, though the use of locking instead
1872 however, be used to control MMIO effects on accesses through relaxed memory I/O
1873 windows. These barriers are required even on non-SMP systems as they affect
1874 the order in which memory operations appear to a device by prohibiting both the
1882 This assigns the value to the variable and then inserts a full memory
1884 compiler barrier in a UP compilation.
1890 These are for use with atomic RMW functions that do not imply memory
1891 barriers, but where the code needs a memory barrier. Examples for atomic
1892 RMW functions that do not imply a memory barrier are e.g. add,
1894 but not atomic_read or atomic_set. A common example where a memory
1899 memory barrier (such as set_bit and clear_bit).
1904 obj->dead = 1;
1906 atomic_dec(&obj->ref_count);
1918 These are for use with consistent memory to guarantee the ordering
1919 of writes or reads of shared memory accessible to both the CPU and a
1920 DMA capable device. See Documentation/core-api/dma-api.rst file for more
1921 information about consistent memory.
1923 For example, consider a device driver that shares memory with a device
1928 if (desc->status != DEVICE_OWN) {
1933 read_data = desc->data;
1934 desc->data = write_data;
1940 desc->status = DEVICE_OWN;
1960 This is for use with persistent memory to ensure that stores for which
1964 For example, after a non-temporal write to pmem region, we use pmem_wmb()
1968 in addition to the ordering done by wmb().
1970 For load from persistent memory, existing read memory barriers are sufficient
1975 For memory accesses with write-combining attributes (e.g. those returned
1978 write-combining memory accesses before this macro with those after it when
1982 IMPLICIT KERNEL MEMORY BARRIERS
1985 Some of the other functions in the linux kernel imply memory barriers, amongst
1994 --------------------------
2004 In all cases there are variants on "ACQUIRE" operations and "RELEASE" operations
2009 Memory operations issued after the ACQUIRE will be completed after the
2012 Memory operations issued before the ACQUIRE may be completed after
2017 Memory operations issued before the RELEASE will be completed before the
2020 Memory operations issued after the RELEASE may be completed before the
2041 one-way barriers is that the effects of instructions outside of a critical
2044 An ACQUIRE followed by a RELEASE may not be assumed to be full memory barrier
2061 another CPU not holding that lock. In short, a ACQUIRE followed by an
2062 RELEASE may -not- be assumed to be a full memory barrier.
2065 not imply a full memory barrier. Therefore, the CPU's execution of the
2087 -could- occur.
2089 But suppose the CPU reordered the operations. In this case,
2090 the unlock precedes the lock in the assembly code. The CPU
2095 in the assembly code), which will unravel the potential deadlock,
2098 But what if the lock is a sleeplock? In that case, the code will
2100 a memory barrier, which will force the earlier unlock operation
2102 a sleep-unlock race, but the locking primitive needs to resolve
2103 such races properly in any case.
2106 systems, and so cannot be counted on in such a situation to actually achieve
2107 anything at all - especially with respect to I/O accesses - unless combined
2110 See also the section on "Inter-CPU acquiring barrier effects".
2140 -----------------------------
2143 (RELEASE equivalent) will act as compiler barriers only. So if memory or I/O
2144 barriers are required in such a situation, they must be provided from some
2148 SLEEP AND WAKE-UP FUNCTIONS
2149 ---------------------------
2151 Sleeping and waking on an event flagged in global data can be viewed as an
2154 these appear to happen in the right order, the primitives to begin the process
2167 A general memory barrier is interpolated automatically by set_current_state()
2174 STORE current->state
2183 which therefore also imply a general memory barrier after setting the state.
2184 The whole sequence above is available in various canned forms, all of which
2185 interpolate the memory barrier in the right place:
2207 A general memory barrier is executed by wake_up() if it wakes something up.
2208 If it doesn't wake anything up then a memory barrier may or may not be
2210 is accessed, in particular, it sits between the STORE to indicate the event
2217 STORE current->state ...
2219 LOAD event_indicated if ((LOAD task->state) & TASK_NORMAL)
2220 STORE task->state
2224 To repeat, a general memory barrier is guaranteed to be executed by wake_up()
2238 wake_up_process() always executes a general memory barrier. The barrier again
2239 occurs before the task state is accessed. In particular, if the wake_up() in
2261 In terms of memory ordering, these functions all provide the same guarantees of
2264 [!] Note that the memory barriers implied by the sleeper and the waker do _not_
2265 order multiple stores before the wake-up with respect to loads of those stored
2282 the sleeper as coming after the change to my_data. In such a circumstance, the
2283 code on both sides must interpolate its own memory barriers between the
2301 -----------------------
2305 (*) schedule() and similar imply full memory barriers.
2309 INTER-CPU ACQUIRING BARRIER EFFECTS
2313 that does affect memory access ordering on other CPUs, within the context of
2317 ACQUIRES VS MEMORY ACCESSES
2318 ---------------------------
2333 through *H occur in, other than the constraints imposed by the separate locks
2347 WHERE ARE MEMORY BARRIERS NEEDED?
2350 Under normal operation, memory operation reordering is generally not going to
2351 be a problem as a single-threaded linear piece of code will still appear to
2352 work correctly, even if it's in an SMP kernel. There are, however, four
2353 circumstances in which reordering definitely _could_ be a problem:
2365 --------------------------
2367 When there's a system with more than one processor, more than one CPU in the
2371 operate without the use of a lock if at all possible. In such a case
2403 In other words, it has to perform this sequence of events:
2405 LOAD waiter->list.next;
2406 LOAD waiter->task;
2407 STORE waiter->task;
2417 if the task pointer is cleared _before_ the next pointer in the list is read,
2429 LOAD waiter->task;
2430 STORE waiter->task;
2438 LOAD waiter->list.next;
2439 --- OOPS ---
2444 The way to deal with this is to insert a general SMP memory barrier:
2446 LOAD waiter->list.next;
2447 LOAD waiter->task;
2449 STORE waiter->task;
2453 In this case, the barrier makes a guarantee that all memory accesses before the
2454 barrier will appear to happen before all the memory accesses after the barrier
2456 the memory accesses before the barrier will be complete by the time the barrier
2459 On a UP system - where this wouldn't be a problem - the smp_mb() is just a
2460 compiler barrier, thus making sure the compiler emits the instructions in the
2461 right order without actually intervening in the CPU. Since there's only one
2466 -----------------
2469 operations are noted specially as some of them imply full memory barriers and
2477 -----------------
2479 Many devices can be memory mapped, and so appear to the CPU as if they're just
2480 a set of memory locations. To control such a device, the driver usually has to
2481 make the right memory accesses in exactly the right order.
2484 in that the carefully sequenced accesses in the driver code won't reach the
2485 device in the requisite order if the CPU or the compiler thinks it is more
2486 efficient to reorder, combine or merge accesses - something that would cause
2490 routines - such as inb() or writel() - which know how to make such accesses
2492 use of memory barriers unnecessary, if the accessor functions are used to refer
2493 to an I/O memory window with relaxed memory access properties, then _mandatory_
2494 memory barriers are required to enforce ordering.
2496 See Documentation/driver-api/device-io.rst for more information.
2500 ----------
2506 This may be alleviated - at least in part - by disabling local interrupts (a
2508 the interrupt-disabled section in the driver. While the driver's interrupt
2515 under interrupt-disablement and then the driver's interrupt handler is invoked:
2534 accesses performed in an interrupt - and vice versa - unless implicit or
2544 likely, then interrupt-disabling locks should be used to guarantee ordering.
2552 specific. Therefore, drivers which are inherently non-portable may rely on
2553 specific behaviours of their target systems in order to achieve synchronization
2554 in the most lightweight manner possible. For drivers intending to be portable
2568 by the same CPU thread to a particular device will arrive in program
2575 a spinlock will arrive in an order consistent with acquisitions of
2579 completion of all prior writes to memory either issued by, or
2586 any subsequent reads from memory by the same thread can begin. This
2604 The ordering properties of __iomem pointers obtained with non-default
2611 These are similar to readX() and writeX(), but provide weaker memory
2613 respect to locking, normal memory accesses or delay() loops (i.e.
2614 bullets 2-5 above) but they are still guaranteed to be ordered with
2622 register-based, memory-mapped FIFOs residing on peripherals that are not
2628 The inX() and outX() accessors are intended to access legacy port-mapped
2634 internal virtual memory mapping, the portable ordering guarantees
2639 Device drivers may expect outX() to emit a non-posted write transaction
2657 little-endian and will therefore perform byte-swapping operations on big-endian
2665 It has to be assumed that the conceptual CPU is weakly-ordered but that it will
2669 of arch-specific code.
2672 stream in any order it feels like - or even in parallel - provided that if an
2673 instruction in the stream depends on an earlier instruction, then that
2675 instruction may proceed; in other words: provided that the appearance of
2678 [*] Some instructions have more than one effect - such as changing the
2679 condition codes, changing registers or changing memory - and different
2688 stream in any way it sees fit, again provided the appearance of causality is
2696 The way cached memory operations are perceived across the system is affected to
2697 a certain extent by the caches that lie between CPUs and memory, and by the
2698 memory coherence system that maintains the consistency of state in the system.
2701 caches goes, the memory system has to include the CPU's caches, and memory
2703 (memory barriers logically act on the dotted line in the following diagram):
2705 <--- CPU ---> : <----------- Memory ----------->
2707 +--------+ +--------+ : +--------+ +-----------+
2708 | | | | : | | | | +--------+
2709 | CPU | | Memory | : | CPU | | | | |
2710 | Core |--->| Access |----->| Cache |<-->| | | |
2711 | | | Queue | : | | | |--->| Memory |
2713 +--------+ +--------+ : +--------+ | | | |
2714 : | Cache | +--------+
2716 : | Mechanism | +--------+
2717 +--------+ +--------+ : +--------+ | | | |
2719 | CPU | | Memory | : | CPU | | |--->| Device |
2720 | Core |--->| Access |----->| Cache |<-->| | | |
2722 | | | | : | | | | +--------+
2723 +--------+ +--------+ : +--------+ +-----------+
2729 it will still appear as if the full memory access had taken place as far as the
2733 The CPU core may execute instructions in any order it deems fit, provided the
2735 generate load and store operations which then go into the queue of memory
2736 accesses to be performed. The core may place these in the queue in any order
2740 What memory barriers are concerned with is controlling the order in which
2741 accesses cross from the CPU side of things to the memory side of things, and
2742 the order in which the effects are perceived to happen by the other observers
2743 in the system.
2745 [!] Memory barriers are _not_ needed within a given CPU, as CPUs always see
2746 their own loads and stores as if they had happened in program order.
2749 the properties of the memory window through which devices are accessed and/or
2754 ----------------------
2756 Not all systems maintain cache coherency with respect to devices doing DMA. In
2758 dirty cache lines may be resident in the caches of various CPUs, and may not
2763 In addition, the data DMA'd to RAM by a device may be overwritten by dirty
2765 installed its own data, or cache lines present in the CPU's cache may simply
2771 See Documentation/core-api/cachetlb.rst for more information on cache
2776 -----------------------
2778 Memory mapped I/O usually takes place through memory locations that are part of
2779 a window in the CPU's memory space that has different properties assigned than
2784 may, in effect, overtake accesses to cached memory that were emitted earlier.
2785 A memory barrier isn't sufficient in such a case, but rather the cache must be
2786 flushed between the cached memory write and the MMIO access if the two are in
2794 A programmer might take it for granted that the CPU will perform memory
2795 operations in exactly the order specified, so that if the CPU is, for example,
2804 they would then expect that the CPU will complete the memory operation for each
2806 operations as seen by external observers in the system:
2822 at the wrong time in the expected sequence of events;
2824 (*) the order of the memory accesses may be rearranged to promote better use
2828 memory or I/O hardware that can do batched accesses of adjacent locations,
2829 thus cutting down on transaction setup costs (memory and PCI devices may
2832 (*) the CPU's data cache may affect the ordering, and while cache-coherency
2833 mechanisms may alleviate this - once the store has actually hit the cache
2834 - there's no guarantee that the coherency management will be propagated in
2845 However, it is guaranteed that a CPU will be self-consistent: it will see its
2846 _own_ accesses appear to be correctly ordered, without the need for a memory
2864 The code above may cause the CPU to generate the full sequence of memory
2869 in that order, but, without intervention, the sequence may have almost any
2872 are -not- optional in the above example, as there are architectures
2897 may, without a memory barrier or an READ_ONCE() and WRITE_ONCE(), be
2907 --------------------------
2911 two semantically-related cache lines updated at separate times. This is where
2912 the address-dependency barrier really becomes necessary as this synchronises
2913 both caches with the memory coherence system, thus making it seem like pointer
2914 changes vs new data occur in the right order.
2916 The Alpha defines the Linux kernel's memory model, although as of v4.15
2918 reduced its impact on the memory model.
2922 ----------------------
2927 barriers for this use-case would be possible but is often suboptimal.
2929 To handle this case optimally, low-level virt_mb() etc macros are available.
2931 identical code for SMP and non-SMP systems. For example, virtual machine guests
2935 These are equivalent to smp_mb() etc counterparts in all other respects,
2936 in particular, they do not control MMIO effects: to control
2945 ----------------
2947 Memory barriers can be used to implement circular buffering without the need
2950 Documentation/core-api/circular-buffers.rst
2967 Chapter 7.1: Memory-Access Ordering
2968 Chapter 7.4: Buffering and Combining Memory Writes
2970 ARM Architecture Reference Manual (ARMv8, for ARMv8-A architecture profile)
2971 Chapter B2: The AArch64 Application Level Memory Model
2973 IA-32 Intel Architecture Software Developer's Manual, Volume 3:
2976 Chapter 7.2: Memory Ordering
2980 Chapter 8: Memory Models
2981 Appendix D: Formal Specification of the Memory Models
2982 Appendix J: Programming with the Memory Models
2984 Storage in the PowerPC (Stone and Fitzgerald)
2987 Chapter 5: Memory Accesses and Cacheability
2988 Chapter 15: Sparc-V9 Memory Models
2991 Chapter 9: Memory Models
2994 Chapter 8: Memory Models
2997 Chapter 9: Memory
2998 Appendix D: Formal Specifications of the Memory Models
3001 Chapter 8: Memory Models
3004 Solaris Internals, Core Kernel Architecture, p63-68:
3010 Chapter 13: Other Memory Models
3014 Section 4.4: Memory Access