Path: blob/master/tools/memory-model/Documentation/ordering.txt
26288 views
This document gives an overview of the categories of memory-ordering1operations provided by the Linux-kernel memory model (LKMM).234Categories of Ordering5======================67This section lists LKMM's three top-level categories of memory-ordering8operations in decreasing order of strength:9101. Barriers (also known as "fences"). A barrier orders some or11all of the CPU's prior operations against some or all of its12subsequent operations.13142. Ordered memory accesses. These operations order themselves15against some or all of the CPU's prior accesses or some or all16of the CPU's subsequent accesses, depending on the subcategory17of the operation.18193. Unordered accesses, as the name indicates, have no ordering20properties except to the extent that they interact with an21operation in the previous categories. This being the real world,22some of these "unordered" operations provide limited ordering23in some special situations.2425Each of the above categories is described in more detail by one of the26following sections.272829Barriers30========3132Each of the following categories of barriers is described in its own33subsection below:3435a. Full memory barriers.3637b. Read-modify-write (RMW) ordering augmentation barriers.3839c. Write memory barrier.4041d. Read memory barrier.4243e. Compiler barrier.4445Note well that many of these primitives generate absolutely no code46in kernels built with CONFIG_SMP=n. Therefore, if you are writing47a device driver, which must correctly order accesses to a physical48device even in kernels built with CONFIG_SMP=n, please use the49ordering primitives provided for that purpose. For example, instead of50smp_mb(), use mb(). See the "Linux Kernel Device Drivers" book or the51https://lwn.net/Articles/698014/ article for more information.525354Full Memory Barriers55--------------------5657The Linux-kernel primitives that provide full ordering include:5859o The smp_mb() full memory barrier.6061o Value-returning RMW atomic operations whose names do not end in62_acquire, _release, or _relaxed.6364o RCU's grace-period primitives.6566First, the smp_mb() full memory barrier orders all of the CPU's prior67accesses against all subsequent accesses from the viewpoint of all CPUs.68In other words, all CPUs will agree that any earlier action taken69by that CPU happened before any later action taken by that same CPU.70For example, consider the following:7172WRITE_ONCE(x, 1);73smp_mb(); // Order store to x before load from y.74r1 = READ_ONCE(y);7576All CPUs will agree that the store to "x" happened before the load77from "y", as indicated by the comment. And yes, please comment your78memory-ordering primitives. It is surprisingly hard to remember their79purpose after even a few months.8081Second, some RMW atomic operations provide full ordering. These82operations include value-returning RMW atomic operations (that is, those83with non-void return types) whose names do not end in _acquire, _release,84or _relaxed. Examples include atomic_add_return(), atomic_dec_and_test(),85cmpxchg(), and xchg(). Note that conditional RMW atomic operations such86as cmpxchg() are only guaranteed to provide ordering when they succeed.87When RMW atomic operations provide full ordering, they partition the88CPU's accesses into three groups:89901. All code that executed prior to the RMW atomic operation.91922. The RMW atomic operation itself.93943. All code that executed after the RMW atomic operation.9596All CPUs will agree that any operation in a given partition happened97before any operation in a higher-numbered partition.9899In contrast, non-value-returning RMW atomic operations (that is, those100with void return types) do not guarantee any ordering whatsoever. Nor do101value-returning RMW atomic operations whose names end in _relaxed.102Examples of the former include atomic_inc() and atomic_dec(),103while examples of the latter include atomic_cmpxchg_relaxed() and104atomic_xchg_relaxed(). Similarly, value-returning non-RMW atomic105operations such as atomic_read() do not guarantee full ordering, and106are covered in the later section on unordered operations.107108Value-returning RMW atomic operations whose names end in _acquire or109_release provide limited ordering, and will be described later in this110document.111112Finally, RCU's grace-period primitives provide full ordering. These113primitives include synchronize_rcu(), synchronize_rcu_expedited(),114synchronize_srcu() and so on. However, these primitives have orders115of magnitude greater overhead than smp_mb(), atomic_xchg(), and so on.116Furthermore, RCU's grace-period primitives can only be invoked in117sleepable contexts. Therefore, RCU's grace-period primitives are118typically instead used to provide ordering against RCU read-side critical119sections, as documented in their comment headers. But of course if you120need a synchronize_rcu() to interact with readers, it costs you nothing121to also rely on its additional full-memory-barrier semantics. Just please122carefully comment this, otherwise your future self will hate you.123124125RMW Ordering Augmentation Barriers126----------------------------------127128As noted in the previous section, non-value-returning RMW operations129such as atomic_inc() and atomic_dec() guarantee no ordering whatsoever.130Nevertheless, a number of popular CPU families, including x86, provide131full ordering for these primitives. One way to obtain full ordering on132all architectures is to add a call to smp_mb():133134WRITE_ONCE(x, 1);135atomic_inc(&my_counter);136smp_mb(); // Inefficient on x86!!!137r1 = READ_ONCE(y);138139This works, but the added smp_mb() adds needless overhead for140x86, on which atomic_inc() provides full ordering all by itself.141The smp_mb__after_atomic() primitive can be used instead:142143WRITE_ONCE(x, 1);144atomic_inc(&my_counter);145smp_mb__after_atomic(); // Order store to x before load from y.146r1 = READ_ONCE(y);147148The smp_mb__after_atomic() primitive emits code only on CPUs whose149atomic_inc() implementations do not guarantee full ordering, thus150incurring no unnecessary overhead on x86. There are a number of151variations on the smp_mb__*() theme:152153o smp_mb__before_atomic(), which provides full ordering prior154to an unordered RMW atomic operation.155156o smp_mb__after_atomic(), which, as shown above, provides full157ordering subsequent to an unordered RMW atomic operation.158159o smp_mb__after_spinlock(), which provides full ordering subsequent160to a successful spinlock acquisition. Note that spin_lock() is161always successful but spin_trylock() might not be.162163o smp_mb__after_srcu_read_unlock(), which provides full ordering164subsequent to an srcu_read_unlock().165166It is bad practice to place code between the smp__*() primitive and the167operation whose ordering that it is augmenting. The reason is that the168ordering of this intervening code will differ from one CPU architecture169to another.170171172Write Memory Barrier173--------------------174175The Linux kernel's write memory barrier is smp_wmb(). If a CPU executes176the following code:177178WRITE_ONCE(x, 1);179smp_wmb();180WRITE_ONCE(y, 1);181182Then any given CPU will see the write to "x" has having happened before183the write to "y". However, you are usually better off using a release184store, as described in the "Release Operations" section below.185186Note that smp_wmb() might fail to provide ordering for unmarked C-language187stores because profile-driven optimization could determine that the188value being overwritten is almost always equal to the new value. Such a189compiler might then reasonably decide to transform "x = 1" and "y = 1"190as follows:191192if (x != 1)193x = 1;194smp_wmb(); // BUG: does not order the reads!!!195if (y != 1)196y = 1;197198Therefore, if you need to use smp_wmb() with unmarked C-language writes,199you will need to make sure that none of the compilers used to build200the Linux kernel carry out this sort of transformation, both now and in201the future.202203204Read Memory Barrier205-------------------206207The Linux kernel's read memory barrier is smp_rmb(). If a CPU executes208the following code:209210r0 = READ_ONCE(y);211smp_rmb();212r1 = READ_ONCE(x);213214Then any given CPU will see the read from "y" as having preceded the read from215"x". However, you are usually better off using an acquire load, as described216in the "Acquire Operations" section below.217218Compiler Barrier219----------------220221The Linux kernel's compiler barrier is barrier(). This primitive222prohibits compiler code-motion optimizations that might move memory223references across the point in the code containing the barrier(), but224does not constrain hardware memory ordering. For example, this can be225used to prevent the compiler from moving code across an infinite loop:226227WRITE_ONCE(x, 1);228while (dontstop)229barrier();230r1 = READ_ONCE(y);231232Without the barrier(), the compiler would be within its rights to move the233WRITE_ONCE() to follow the loop. This code motion could be problematic234in the case where an interrupt handler terminates the loop. Another way235to handle this is to use READ_ONCE() for the load of "dontstop".236237Note that the barriers discussed previously use barrier() or its low-level238equivalent in their implementations.239240241Ordered Memory Accesses242=======================243244The Linux kernel provides a wide variety of ordered memory accesses:245246a. Release operations.247248b. Acquire operations.249250c. RCU read-side ordering.251252d. Control dependencies.253254Each of the above categories has its own section below.255256257Release Operations258------------------259260Release operations include smp_store_release(), atomic_set_release(),261rcu_assign_pointer(), and value-returning RMW operations whose names262end in _release. These operations order their own store against all263of the CPU's prior memory accesses. Release operations often provide264improved readability and performance compared to explicit barriers.265For example, use of smp_store_release() saves a line compared to the266smp_wmb() example above:267268WRITE_ONCE(x, 1);269smp_store_release(&y, 1);270271More important, smp_store_release() makes it easier to connect up the272different pieces of the concurrent algorithm. The variable stored to273by the smp_store_release(), in this case "y", will normally be used in274an acquire operation in other parts of the concurrent algorithm.275276To see the performance advantages, suppose that the above example reads277from "x" instead of writing to it. Then an smp_wmb() could not guarantee278ordering, and an smp_mb() would be needed instead:279280r1 = READ_ONCE(x);281smp_mb();282WRITE_ONCE(y, 1);283284But smp_mb() often incurs much higher overhead than does285smp_store_release(), which still provides the needed ordering of "x"286against "y". On x86, the version using smp_store_release() might compile287to a simple load instruction followed by a simple store instruction.288In contrast, the smp_mb() compiles to an expensive instruction that289provides the needed ordering.290291There is a wide variety of release operations:292293o Store operations, including not only the aforementioned294smp_store_release(), but also atomic_set_release(), and295atomic_long_set_release().296297o RCU's rcu_assign_pointer() operation. This is the same as298smp_store_release() except that: (1) It takes the pointer to299be assigned to instead of a pointer to that pointer, (2) It300is intended to be used in conjunction with rcu_dereference()301and similar rather than smp_load_acquire(), and (3) It checks302for an RCU-protected pointer in "sparse" runs.303304o Value-returning RMW operations whose names end in _release,305such as atomic_fetch_add_release() and cmpxchg_release().306Note that release ordering is guaranteed only against the307memory-store portion of the RMW operation, and not against the308memory-load portion. Note also that conditional operations such309as cmpxchg_release() are only guaranteed to provide ordering310when they succeed.311312As mentioned earlier, release operations are often paired with acquire313operations, which are the subject of the next section.314315316Acquire Operations317------------------318319Acquire operations include smp_load_acquire(), atomic_read_acquire(),320and value-returning RMW operations whose names end in _acquire. These321operations order their own load against all of the CPU's subsequent322memory accesses. Acquire operations often provide improved performance323and readability compared to explicit barriers. For example, use of324smp_load_acquire() saves a line compared to the smp_rmb() example above:325326r0 = smp_load_acquire(&y);327r1 = READ_ONCE(x);328329As with smp_store_release(), this also makes it easier to connect330the different pieces of the concurrent algorithm by looking for the331smp_store_release() that stores to "y". In addition, smp_load_acquire()332improves upon smp_rmb() by ordering against subsequent stores as well333as against subsequent loads.334335There are a couple of categories of acquire operations:336337o Load operations, including not only the aforementioned338smp_load_acquire(), but also atomic_read_acquire(), and339atomic64_read_acquire().340341o Value-returning RMW operations whose names end in _acquire,342such as atomic_xchg_acquire() and atomic_cmpxchg_acquire().343Note that acquire ordering is guaranteed only against the344memory-load portion of the RMW operation, and not against the345memory-store portion. Note also that conditional operations346such as atomic_cmpxchg_acquire() are only guaranteed to provide347ordering when they succeed.348349Symmetry being what it is, acquire operations are often paired with the350release operations covered earlier. For example, consider the following351example, where task0() and task1() execute concurrently:352353void task0(void)354{355WRITE_ONCE(x, 1);356smp_store_release(&y, 1);357}358359void task1(void)360{361r0 = smp_load_acquire(&y);362r1 = READ_ONCE(x);363}364365If "x" and "y" are both initially zero, then either r0's final value366will be zero or r1's final value will be one, thus providing the required367ordering.368369370RCU Read-Side Ordering371----------------------372373This category includes read-side markers such as rcu_read_lock()374and rcu_read_unlock() as well as pointer-traversal primitives such as375rcu_dereference() and srcu_dereference().376377Compared to locking primitives and RMW atomic operations, markers378for RCU read-side critical sections incur very low overhead because379they interact only with the corresponding grace-period primitives.380For example, the rcu_read_lock() and rcu_read_unlock() markers interact381with synchronize_rcu(), synchronize_rcu_expedited(), and call_rcu().382The way this works is that if a given call to synchronize_rcu() cannot383prove that it started before a given call to rcu_read_lock(), then384that synchronize_rcu() must block until the matching rcu_read_unlock()385is reached. For more information, please see the synchronize_rcu()386docbook header comment and the material in Documentation/RCU.387388RCU's pointer-traversal primitives, including rcu_dereference() and389srcu_dereference(), order their load (which must be a pointer) against any390of the CPU's subsequent memory accesses whose address has been calculated391from the value loaded. There is said to be an *address dependency*392from the value returned by the rcu_dereference() or srcu_dereference()393to that subsequent memory access.394395A call to rcu_dereference() for a given RCU-protected pointer is396usually paired with a call to rcu_assign_pointer() for that same pointer397in much the same way that a call to smp_load_acquire() is paired with398a call to smp_store_release(). Calls to rcu_dereference() and399rcu_assign_pointer() are often buried in other APIs, for example,400the RCU list API members defined in include/linux/rculist.h. For more401information, please see the docbook headers in that file, the most402recent LWN article on the RCU API (https://lwn.net/Articles/988638/),403and of course the material in Documentation/RCU.404405If the pointer value is manipulated between the rcu_dereference()406that returned it and a later rcu_dereference(), please read407Documentation/RCU/rcu_dereference.rst. It can also be quite helpful to408review uses in the Linux kernel.409410411Control Dependencies412--------------------413414A control dependency extends from a marked load (READ_ONCE() or stronger)415through an "if" condition to a marked store (WRITE_ONCE() or stronger)416that is executed only by one of the legs of that "if" statement.417Control dependencies are so named because they are mediated by418control-flow instructions such as comparisons and conditional branches.419420In short, you can use a control dependency to enforce ordering between421an READ_ONCE() and a WRITE_ONCE() when there is an "if" condition422between them. The canonical example is as follows:423424q = READ_ONCE(a);425if (q)426WRITE_ONCE(b, 1);427428In this case, all CPUs would see the read from "a" as happening before429the write to "b".430431However, control dependencies are easily destroyed by compiler432optimizations, so any use of control dependencies must take into account433all of the compilers used to build the Linux kernel. Please see the434"control-dependencies.txt" file for more information.435436437Unordered Accesses438==================439440Each of these two categories of unordered accesses has a section below:441442a. Unordered marked operations.443444b. Unmarked C-language accesses.445446447Unordered Marked Operations448---------------------------449450Unordered operations to different variables are just that, unordered.451However, if a group of CPUs apply these operations to a single variable,452all the CPUs will agree on the operation order. Of course, the ordering453of unordered marked accesses can also be constrained using the mechanisms454described earlier in this document.455456These operations come in three categories:457458o Marked writes, such as WRITE_ONCE() and atomic_set(). These459primitives require the compiler to emit the corresponding store460instructions in the expected execution order, thus suppressing461a number of destructive optimizations. However, they provide no462hardware ordering guarantees, and in fact many CPUs will happily463reorder marked writes with each other or with other unordered464operations, unless these operations are to the same variable.465466o Marked reads, such as READ_ONCE() and atomic_read(). These467primitives require the compiler to emit the corresponding load468instructions in the expected execution order, thus suppressing469a number of destructive optimizations. However, they provide no470hardware ordering guarantees, and in fact many CPUs will happily471reorder marked reads with each other or with other unordered472operations, unless these operations are to the same variable.473474o Unordered RMW atomic operations. These are non-value-returning475RMW atomic operations whose names do not end in _acquire or476_release, and also value-returning RMW operations whose names477end in _relaxed. Examples include atomic_add(), atomic_or(),478and atomic64_fetch_xor_relaxed(). These operations do carry479out the specified RMW operation atomically, for example, five480concurrent atomic_inc() operations applied to a given variable481will reliably increase the value of that variable by five.482However, many CPUs will happily reorder these operations with483each other or with other unordered operations.484485This category of operations can be efficiently ordered using486smp_mb__before_atomic() and smp_mb__after_atomic(), as was487discussed in the "RMW Ordering Augmentation Barriers" section.488489In short, these operations can be freely reordered unless they are all490operating on a single variable or unless they are constrained by one of491the operations called out earlier in this document.492493494Unmarked C-Language Accesses495----------------------------496497Unmarked C-language accesses are normal variable accesses to normal498variables, that is, to variables that are not "volatile" and are not499C11 atomic variables. These operations provide no ordering guarantees,500and further do not guarantee "atomic" access. For example, the compiler501might (and sometimes does) split a plain C-language store into multiple502smaller stores. A load from that same variable running on some other503CPU while such a store is executing might see a value that is a mashup504of the old value and the new value.505506Unmarked C-language accesses are unordered, and are also subject to507any number of compiler optimizations, many of which can break your508concurrent code. It is possible to use unmarked C-language accesses for509shared variables that are subject to concurrent access, but great care510is required on an ongoing basis. The compiler-constraining barrier()511primitive can be helpful, as can the various ordering primitives discussed512in this document. It nevertheless bears repeating that use of unmarked513C-language accesses requires careful attention to not just your code,514but to all the compilers that might be used to build it. Such compilers515might replace a series of loads with a single load, and might replace516a series of stores with a single store. Some compilers will even split517a single store into multiple smaller stores.518519But there are some ways of using unmarked C-language accesses for shared520variables without such worries:521522o Guard all accesses to a given variable by a particular lock,523so that there are never concurrent conflicting accesses to524that variable. (There are "conflicting accesses" when525(1) at least one of the concurrent accesses to a variable is an526unmarked C-language access and (2) when at least one of those527accesses is a write, whether marked or not.)528529o As above, but using other synchronization primitives such530as reader-writer locks or sequence locks.531532o Use locking or other means to ensure that all concurrent accesses533to a given variable are reads.534535o Restrict use of a given variable to statistics or heuristics536where the occasional bogus value can be tolerated.537538o Declare the accessed variables as C11 atomics.539https://lwn.net/Articles/691128/540541o Declare the accessed variables as "volatile".542543If you need to live more dangerously, please do take the time to544understand the compilers. One place to start is these two LWN545articles:546547Who's afraid of a big bad optimizing compiler?548https://lwn.net/Articles/793253549Calibrating your fear of big bad optimizing compilers550https://lwn.net/Articles/799218551552Used properly, unmarked C-language accesses can reduce overhead on553fastpaths. However, the price is great care and continual attention554to your compiler as new versions come out and as new optimizations555are enabled.556557558