Back to home page

OSCL-LXR

 
 

    


0001 This document gives an overview of the categories of memory-ordering
0002 operations provided by the Linux-kernel memory model (LKMM).
0003 
0004 
0005 Categories of Ordering
0006 ======================
0007 
0008 This section lists LKMM's three top-level categories of memory-ordering
0009 operations in decreasing order of strength:
0010 
0011 1.      Barriers (also known as "fences").  A barrier orders some or
0012         all of the CPU's prior operations against some or all of its
0013         subsequent operations.
0014 
0015 2.      Ordered memory accesses.  These operations order themselves
0016         against some or all of the CPU's prior accesses or some or all
0017         of the CPU's subsequent accesses, depending on the subcategory
0018         of the operation.
0019 
0020 3.      Unordered accesses, as the name indicates, have no ordering
0021         properties except to the extent that they interact with an
0022         operation in the previous categories.  This being the real world,
0023         some of these "unordered" operations provide limited ordering
0024         in some special situations.
0025 
0026 Each of the above categories is described in more detail by one of the
0027 following sections.
0028 
0029 
0030 Barriers
0031 ========
0032 
0033 Each of the following categories of barriers is described in its own
0034 subsection below:
0035 
0036 a.      Full memory barriers.
0037 
0038 b.      Read-modify-write (RMW) ordering augmentation barriers.
0039 
0040 c.      Write memory barrier.
0041 
0042 d.      Read memory barrier.
0043 
0044 e.      Compiler barrier.
0045 
0046 Note well that many of these primitives generate absolutely no code
0047 in kernels built with CONFIG_SMP=n.  Therefore, if you are writing
0048 a device driver, which must correctly order accesses to a physical
0049 device even in kernels built with CONFIG_SMP=n, please use the
0050 ordering primitives provided for that purpose.  For example, instead of
0051 smp_mb(), use mb().  See the "Linux Kernel Device Drivers" book or the
0052 https://lwn.net/Articles/698014/ article for more information.
0053 
0054 
0055 Full Memory Barriers
0056 --------------------
0057 
0058 The Linux-kernel primitives that provide full ordering include:
0059 
0060 o       The smp_mb() full memory barrier.
0061 
0062 o       Value-returning RMW atomic operations whose names do not end in
0063         _acquire, _release, or _relaxed.
0064 
0065 o       RCU's grace-period primitives.
0066 
0067 First, the smp_mb() full memory barrier orders all of the CPU's prior
0068 accesses against all subsequent accesses from the viewpoint of all CPUs.
0069 In other words, all CPUs will agree that any earlier action taken
0070 by that CPU happened before any later action taken by that same CPU.
0071 For example, consider the following:
0072 
0073         WRITE_ONCE(x, 1);
0074         smp_mb(); // Order store to x before load from y.
0075         r1 = READ_ONCE(y);
0076 
0077 All CPUs will agree that the store to "x" happened before the load
0078 from "y", as indicated by the comment.  And yes, please comment your
0079 memory-ordering primitives.  It is surprisingly hard to remember their
0080 purpose after even a few months.
0081 
0082 Second, some RMW atomic operations provide full ordering.  These
0083 operations include value-returning RMW atomic operations (that is, those
0084 with non-void return types) whose names do not end in _acquire, _release,
0085 or _relaxed.  Examples include atomic_add_return(), atomic_dec_and_test(),
0086 cmpxchg(), and xchg().  Note that conditional RMW atomic operations such
0087 as cmpxchg() are only guaranteed to provide ordering when they succeed.
0088 When RMW atomic operations provide full ordering, they partition the
0089 CPU's accesses into three groups:
0090 
0091 1.      All code that executed prior to the RMW atomic operation.
0092 
0093 2.      The RMW atomic operation itself.
0094 
0095 3.      All code that executed after the RMW atomic operation.
0096 
0097 All CPUs will agree that any operation in a given partition happened
0098 before any operation in a higher-numbered partition.
0099 
0100 In contrast, non-value-returning RMW atomic operations (that is, those
0101 with void return types) do not guarantee any ordering whatsoever.  Nor do
0102 value-returning RMW atomic operations whose names end in _relaxed.
0103 Examples of the former include atomic_inc() and atomic_dec(),
0104 while examples of the latter include atomic_cmpxchg_relaxed() and
0105 atomic_xchg_relaxed().  Similarly, value-returning non-RMW atomic
0106 operations such as atomic_read() do not guarantee full ordering, and
0107 are covered in the later section on unordered operations.
0108 
0109 Value-returning RMW atomic operations whose names end in _acquire or
0110 _release provide limited ordering, and will be described later in this
0111 document.
0112 
0113 Finally, RCU's grace-period primitives provide full ordering.  These
0114 primitives include synchronize_rcu(), synchronize_rcu_expedited(),
0115 synchronize_srcu() and so on.  However, these primitives have orders
0116 of magnitude greater overhead than smp_mb(), atomic_xchg(), and so on.
0117 Furthermore, RCU's grace-period primitives can only be invoked in
0118 sleepable contexts.  Therefore, RCU's grace-period primitives are
0119 typically instead used to provide ordering against RCU read-side critical
0120 sections, as documented in their comment headers.  But of course if you
0121 need a synchronize_rcu() to interact with readers, it costs you nothing
0122 to also rely on its additional full-memory-barrier semantics.  Just please
0123 carefully comment this, otherwise your future self will hate you.
0124 
0125 
0126 RMW Ordering Augmentation Barriers
0127 ----------------------------------
0128 
0129 As noted in the previous section, non-value-returning RMW operations
0130 such as atomic_inc() and atomic_dec() guarantee no ordering whatsoever.
0131 Nevertheless, a number of popular CPU families, including x86, provide
0132 full ordering for these primitives.  One way to obtain full ordering on
0133 all architectures is to add a call to smp_mb():
0134 
0135         WRITE_ONCE(x, 1);
0136         atomic_inc(&my_counter);
0137         smp_mb(); // Inefficient on x86!!!
0138         r1 = READ_ONCE(y);
0139 
0140 This works, but the added smp_mb() adds needless overhead for
0141 x86, on which atomic_inc() provides full ordering all by itself.
0142 The smp_mb__after_atomic() primitive can be used instead:
0143 
0144         WRITE_ONCE(x, 1);
0145         atomic_inc(&my_counter);
0146         smp_mb__after_atomic(); // Order store to x before load from y.
0147         r1 = READ_ONCE(y);
0148 
0149 The smp_mb__after_atomic() primitive emits code only on CPUs whose
0150 atomic_inc() implementations do not guarantee full ordering, thus
0151 incurring no unnecessary overhead on x86.  There are a number of
0152 variations on the smp_mb__*() theme:
0153 
0154 o       smp_mb__before_atomic(), which provides full ordering prior
0155         to an unordered RMW atomic operation.
0156 
0157 o       smp_mb__after_atomic(), which, as shown above, provides full
0158         ordering subsequent to an unordered RMW atomic operation.
0159 
0160 o       smp_mb__after_spinlock(), which provides full ordering subsequent
0161         to a successful spinlock acquisition.  Note that spin_lock() is
0162         always successful but spin_trylock() might not be.
0163 
0164 o       smp_mb__after_srcu_read_unlock(), which provides full ordering
0165         subsequent to an srcu_read_unlock().
0166 
0167 It is bad practice to place code between the smp__*() primitive and the
0168 operation whose ordering that it is augmenting.  The reason is that the
0169 ordering of this intervening code will differ from one CPU architecture
0170 to another.
0171 
0172 
0173 Write Memory Barrier
0174 --------------------
0175 
0176 The Linux kernel's write memory barrier is smp_wmb().  If a CPU executes
0177 the following code:
0178 
0179         WRITE_ONCE(x, 1);
0180         smp_wmb();
0181         WRITE_ONCE(y, 1);
0182 
0183 Then any given CPU will see the write to "x" has having happened before
0184 the write to "y".  However, you are usually better off using a release
0185 store, as described in the "Release Operations" section below.
0186 
0187 Note that smp_wmb() might fail to provide ordering for unmarked C-language
0188 stores because profile-driven optimization could determine that the
0189 value being overwritten is almost always equal to the new value.  Such a
0190 compiler might then reasonably decide to transform "x = 1" and "y = 1"
0191 as follows:
0192 
0193         if (x != 1)
0194                 x = 1;
0195         smp_wmb(); // BUG: does not order the reads!!!
0196         if (y != 1)
0197                 y = 1;
0198 
0199 Therefore, if you need to use smp_wmb() with unmarked C-language writes,
0200 you will need to make sure that none of the compilers used to build
0201 the Linux kernel carry out this sort of transformation, both now and in
0202 the future.
0203 
0204 
0205 Read Memory Barrier
0206 -------------------
0207 
0208 The Linux kernel's read memory barrier is smp_rmb().  If a CPU executes
0209 the following code:
0210 
0211         r0 = READ_ONCE(y);
0212         smp_rmb();
0213         r1 = READ_ONCE(x);
0214 
0215 Then any given CPU will see the read from "y" as having preceded the read from
0216 "x".  However, you are usually better off using an acquire load, as described
0217 in the "Acquire Operations" section below.
0218 
0219 Compiler Barrier
0220 ----------------
0221 
0222 The Linux kernel's compiler barrier is barrier().  This primitive
0223 prohibits compiler code-motion optimizations that might move memory
0224 references across the point in the code containing the barrier(), but
0225 does not constrain hardware memory ordering.  For example, this can be
0226 used to prevent to compiler from moving code across an infinite loop:
0227 
0228         WRITE_ONCE(x, 1);
0229         while (dontstop)
0230                 barrier();
0231         r1 = READ_ONCE(y);
0232 
0233 Without the barrier(), the compiler would be within its rights to move the
0234 WRITE_ONCE() to follow the loop.  This code motion could be problematic
0235 in the case where an interrupt handler terminates the loop.  Another way
0236 to handle this is to use READ_ONCE() for the load of "dontstop".
0237 
0238 Note that the barriers discussed previously use barrier() or its low-level
0239 equivalent in their implementations.
0240 
0241 
0242 Ordered Memory Accesses
0243 =======================
0244 
0245 The Linux kernel provides a wide variety of ordered memory accesses:
0246 
0247 a.      Release operations.
0248 
0249 b.      Acquire operations.
0250 
0251 c.      RCU read-side ordering.
0252 
0253 d.      Control dependencies.
0254 
0255 Each of the above categories has its own section below.
0256 
0257 
0258 Release Operations
0259 ------------------
0260 
0261 Release operations include smp_store_release(), atomic_set_release(),
0262 rcu_assign_pointer(), and value-returning RMW operations whose names
0263 end in _release.  These operations order their own store against all
0264 of the CPU's prior memory accesses.  Release operations often provide
0265 improved readability and performance compared to explicit barriers.
0266 For example, use of smp_store_release() saves a line compared to the
0267 smp_wmb() example above:
0268 
0269         WRITE_ONCE(x, 1);
0270         smp_store_release(&y, 1);
0271 
0272 More important, smp_store_release() makes it easier to connect up the
0273 different pieces of the concurrent algorithm.  The variable stored to
0274 by the smp_store_release(), in this case "y", will normally be used in
0275 an acquire operation in other parts of the concurrent algorithm.
0276 
0277 To see the performance advantages, suppose that the above example read
0278 from "x" instead of writing to it.  Then an smp_wmb() could not guarantee
0279 ordering, and an smp_mb() would be needed instead:
0280 
0281         r1 = READ_ONCE(x);
0282         smp_mb();
0283         WRITE_ONCE(y, 1);
0284 
0285 But smp_mb() often incurs much higher overhead than does
0286 smp_store_release(), which still provides the needed ordering of "x"
0287 against "y".  On x86, the version using smp_store_release() might compile
0288 to a simple load instruction followed by a simple store instruction.
0289 In contrast, the smp_mb() compiles to an expensive instruction that
0290 provides the needed ordering.
0291 
0292 There is a wide variety of release operations:
0293 
0294 o       Store operations, including not only the aforementioned
0295         smp_store_release(), but also atomic_set_release(), and
0296         atomic_long_set_release().
0297 
0298 o       RCU's rcu_assign_pointer() operation.  This is the same as
0299         smp_store_release() except that: (1) It takes the pointer to
0300         be assigned to instead of a pointer to that pointer, (2) It
0301         is intended to be used in conjunction with rcu_dereference()
0302         and similar rather than smp_load_acquire(), and (3) It checks
0303         for an RCU-protected pointer in "sparse" runs.
0304 
0305 o       Value-returning RMW operations whose names end in _release,
0306         such as atomic_fetch_add_release() and cmpxchg_release().
0307         Note that release ordering is guaranteed only against the
0308         memory-store portion of the RMW operation, and not against the
0309         memory-load portion.  Note also that conditional operations such
0310         as cmpxchg_release() are only guaranteed to provide ordering
0311         when they succeed.
0312 
0313 As mentioned earlier, release operations are often paired with acquire
0314 operations, which are the subject of the next section.
0315 
0316 
0317 Acquire Operations
0318 ------------------
0319 
0320 Acquire operations include smp_load_acquire(), atomic_read_acquire(),
0321 and value-returning RMW operations whose names end in _acquire.   These
0322 operations order their own load against all of the CPU's subsequent
0323 memory accesses.  Acquire operations often provide improved performance
0324 and readability compared to explicit barriers.  For example, use of
0325 smp_load_acquire() saves a line compared to the smp_rmb() example above:
0326 
0327         r0 = smp_load_acquire(&y);
0328         r1 = READ_ONCE(x);
0329 
0330 As with smp_store_release(), this also makes it easier to connect
0331 the different pieces of the concurrent algorithm by looking for the
0332 smp_store_release() that stores to "y".  In addition, smp_load_acquire()
0333 improves upon smp_rmb() by ordering against subsequent stores as well
0334 as against subsequent loads.
0335 
0336 There are a couple of categories of acquire operations:
0337 
0338 o       Load operations, including not only the aforementioned
0339         smp_load_acquire(), but also atomic_read_acquire(), and
0340         atomic64_read_acquire().
0341 
0342 o       Value-returning RMW operations whose names end in _acquire,
0343         such as atomic_xchg_acquire() and atomic_cmpxchg_acquire().
0344         Note that acquire ordering is guaranteed only against the
0345         memory-load portion of the RMW operation, and not against the
0346         memory-store portion.  Note also that conditional operations
0347         such as atomic_cmpxchg_acquire() are only guaranteed to provide
0348         ordering when they succeed.
0349 
0350 Symmetry being what it is, acquire operations are often paired with the
0351 release operations covered earlier.  For example, consider the following
0352 example, where task0() and task1() execute concurrently:
0353 
0354         void task0(void)
0355         {
0356                 WRITE_ONCE(x, 1);
0357                 smp_store_release(&y, 1);
0358         }
0359 
0360         void task1(void)
0361         {
0362                 r0 = smp_load_acquire(&y);
0363                 r1 = READ_ONCE(x);
0364         }
0365 
0366 If "x" and "y" are both initially zero, then either r0's final value
0367 will be zero or r1's final value will be one, thus providing the required
0368 ordering.
0369 
0370 
0371 RCU Read-Side Ordering
0372 ----------------------
0373 
0374 This category includes read-side markers such as rcu_read_lock()
0375 and rcu_read_unlock() as well as pointer-traversal primitives such as
0376 rcu_dereference() and srcu_dereference().
0377 
0378 Compared to locking primitives and RMW atomic operations, markers
0379 for RCU read-side critical sections incur very low overhead because
0380 they interact only with the corresponding grace-period primitives.
0381 For example, the rcu_read_lock() and rcu_read_unlock() markers interact
0382 with synchronize_rcu(), synchronize_rcu_expedited(), and call_rcu().
0383 The way this works is that if a given call to synchronize_rcu() cannot
0384 prove that it started before a given call to rcu_read_lock(), then
0385 that synchronize_rcu() must block until the matching rcu_read_unlock()
0386 is reached.  For more information, please see the synchronize_rcu()
0387 docbook header comment and the material in Documentation/RCU.
0388 
0389 RCU's pointer-traversal primitives, including rcu_dereference() and
0390 srcu_dereference(), order their load (which must be a pointer) against any
0391 of the CPU's subsequent memory accesses whose address has been calculated
0392 from the value loaded.  There is said to be an *address dependency*
0393 from the value returned by the rcu_dereference() or srcu_dereference()
0394 to that subsequent memory access.
0395 
0396 A call to rcu_dereference() for a given RCU-protected pointer is
0397 usually paired with a call to a call to rcu_assign_pointer() for that
0398 same pointer in much the same way that a call to smp_load_acquire() is
0399 paired with a call to smp_store_release().  Calls to rcu_dereference()
0400 and rcu_assign_pointer are often buried in other APIs, for example,
0401 the RCU list API members defined in include/linux/rculist.h.  For more
0402 information, please see the docbook headers in that file, the most
0403 recent LWN article on the RCU API (https://lwn.net/Articles/777036/),
0404 and of course the material in Documentation/RCU.
0405 
0406 If the pointer value is manipulated between the rcu_dereference()
0407 that returned it and a later dereference(), please read
0408 Documentation/RCU/rcu_dereference.rst.  It can also be quite helpful to
0409 review uses in the Linux kernel.
0410 
0411 
0412 Control Dependencies
0413 --------------------
0414 
0415 A control dependency extends from a marked load (READ_ONCE() or stronger)
0416 through an "if" condition to a marked store (WRITE_ONCE() or stronger)
0417 that is executed only by one of the legs of that "if" statement.
0418 Control dependencies are so named because they are mediated by
0419 control-flow instructions such as comparisons and conditional branches.
0420 
0421 In short, you can use a control dependency to enforce ordering between
0422 an READ_ONCE() and a WRITE_ONCE() when there is an "if" condition
0423 between them.  The canonical example is as follows:
0424 
0425         q = READ_ONCE(a);
0426         if (q)
0427                 WRITE_ONCE(b, 1);
0428 
0429 In this case, all CPUs would see the read from "a" as happening before
0430 the write to "b".
0431 
0432 However, control dependencies are easily destroyed by compiler
0433 optimizations, so any use of control dependencies must take into account
0434 all of the compilers used to build the Linux kernel.  Please see the
0435 "control-dependencies.txt" file for more information.
0436 
0437 
0438 Unordered Accesses
0439 ==================
0440 
0441 Each of these two categories of unordered accesses has a section below:
0442 
0443 a.      Unordered marked operations.
0444 
0445 b.      Unmarked C-language accesses.
0446 
0447 
0448 Unordered Marked Operations
0449 ---------------------------
0450 
0451 Unordered operations to different variables are just that, unordered.
0452 However, if a group of CPUs apply these operations to a single variable,
0453 all the CPUs will agree on the operation order.  Of course, the ordering
0454 of unordered marked accesses can also be constrained using the mechanisms
0455 described earlier in this document.
0456 
0457 These operations come in three categories:
0458 
0459 o       Marked writes, such as WRITE_ONCE() and atomic_set().  These
0460         primitives required the compiler to emit the corresponding store
0461         instructions in the expected execution order, thus suppressing
0462         a number of destructive optimizations.  However, they provide no
0463         hardware ordering guarantees, and in fact many CPUs will happily
0464         reorder marked writes with each other or with other unordered
0465         operations, unless these operations are to the same variable.
0466 
0467 o       Marked reads, such as READ_ONCE() and atomic_read().  These
0468         primitives required the compiler to emit the corresponding load
0469         instructions in the expected execution order, thus suppressing
0470         a number of destructive optimizations.  However, they provide no
0471         hardware ordering guarantees, and in fact many CPUs will happily
0472         reorder marked reads with each other or with other unordered
0473         operations, unless these operations are to the same variable.
0474 
0475 o       Unordered RMW atomic operations.  These are non-value-returning
0476         RMW atomic operations whose names do not end in _acquire or
0477         _release, and also value-returning RMW operations whose names
0478         end in _relaxed.  Examples include atomic_add(), atomic_or(),
0479         and atomic64_fetch_xor_relaxed().  These operations do carry
0480         out the specified RMW operation atomically, for example, five
0481         concurrent atomic_inc() operations applied to a given variable
0482         will reliably increase the value of that variable by five.
0483         However, many CPUs will happily reorder these operations with
0484         each other or with other unordered operations.
0485 
0486         This category of operations can be efficiently ordered using
0487         smp_mb__before_atomic() and smp_mb__after_atomic(), as was
0488         discussed in the "RMW Ordering Augmentation Barriers" section.
0489 
0490 In short, these operations can be freely reordered unless they are all
0491 operating on a single variable or unless they are constrained by one of
0492 the operations called out earlier in this document.
0493 
0494 
0495 Unmarked C-Language Accesses
0496 ----------------------------
0497 
0498 Unmarked C-language accesses are normal variable accesses to normal
0499 variables, that is, to variables that are not "volatile" and are not
0500 C11 atomic variables.  These operations provide no ordering guarantees,
0501 and further do not guarantee "atomic" access.  For example, the compiler
0502 might (and sometimes does) split a plain C-language store into multiple
0503 smaller stores.  A load from that same variable running on some other
0504 CPU while such a store is executing might see a value that is a mashup
0505 of the old value and the new value.
0506 
0507 Unmarked C-language accesses are unordered, and are also subject to
0508 any number of compiler optimizations, many of which can break your
0509 concurrent code.  It is possible to used unmarked C-language accesses for
0510 shared variables that are subject to concurrent access, but great care
0511 is required on an ongoing basis.  The compiler-constraining barrier()
0512 primitive can be helpful, as can the various ordering primitives discussed
0513 in this document.  It nevertheless bears repeating that use of unmarked
0514 C-language accesses requires careful attention to not just your code,
0515 but to all the compilers that might be used to build it.  Such compilers
0516 might replace a series of loads with a single load, and might replace
0517 a series of stores with a single store.  Some compilers will even split
0518 a single store into multiple smaller stores.
0519 
0520 But there are some ways of using unmarked C-language accesses for shared
0521 variables without such worries:
0522 
0523 o       Guard all accesses to a given variable by a particular lock,
0524         so that there are never concurrent conflicting accesses to
0525         that variable.  (There are "conflicting accesses" when
0526         (1) at least one of the concurrent accesses to a variable is an
0527         unmarked C-language access and (2) when at least one of those
0528         accesses is a write, whether marked or not.)
0529 
0530 o       As above, but using other synchronization primitives such
0531         as reader-writer locks or sequence locks.
0532 
0533 o       Use locking or other means to ensure that all concurrent accesses
0534         to a given variable are reads.
0535 
0536 o       Restrict use of a given variable to statistics or heuristics
0537         where the occasional bogus value can be tolerated.
0538 
0539 o       Declare the accessed variables as C11 atomics.
0540         https://lwn.net/Articles/691128/
0541 
0542 o       Declare the accessed variables as "volatile".
0543 
0544 If you need to live more dangerously, please do take the time to
0545 understand the compilers.  One place to start is these two LWN
0546 articles:
0547 
0548 Who's afraid of a big bad optimizing compiler?
0549         https://lwn.net/Articles/793253
0550 Calibrating your fear of big bad optimizing compilers
0551         https://lwn.net/Articles/799218
0552 
0553 Used properly, unmarked C-language accesses can reduce overhead on
0554 fastpaths.  However, the price is great care and continual attention
0555 to your compiler as new versions come out and as new optimizations
0556 are enabled.