ordering.txt 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. This document gives an overview of the categories of memory-ordering
  2. operations provided by the Linux-kernel memory model (LKMM).
  3. Categories of Ordering
  4. ======================
  5. This section lists LKMM's three top-level categories of memory-ordering
  6. operations in decreasing order of strength:
  7. 1. Barriers (also known as "fences"). A barrier orders some or
  8. all of the CPU's prior operations against some or all of its
  9. subsequent operations.
  10. 2. Ordered memory accesses. These operations order themselves
  11. against some or all of the CPU's prior accesses or some or all
  12. of the CPU's subsequent accesses, depending on the subcategory
  13. of the operation.
  14. 3. Unordered accesses, as the name indicates, have no ordering
  15. properties except to the extent that they interact with an
  16. operation in the previous categories. This being the real world,
  17. some of these "unordered" operations provide limited ordering
  18. in some special situations.
  19. Each of the above categories is described in more detail by one of the
  20. following sections.
  21. Barriers
  22. ========
  23. Each of the following categories of barriers is described in its own
  24. subsection below:
  25. a. Full memory barriers.
  26. b. Read-modify-write (RMW) ordering augmentation barriers.
  27. c. Write memory barrier.
  28. d. Read memory barrier.
  29. e. Compiler barrier.
  30. Note well that many of these primitives generate absolutely no code
  31. in kernels built with CONFIG_SMP=n. Therefore, if you are writing
  32. a device driver, which must correctly order accesses to a physical
  33. device even in kernels built with CONFIG_SMP=n, please use the
  34. ordering primitives provided for that purpose. For example, instead of
  35. smp_mb(), use mb(). See the "Linux Kernel Device Drivers" book or the
  36. https://lwn.net/Articles/698014/ article for more information.
  37. Full Memory Barriers
  38. --------------------
  39. The Linux-kernel primitives that provide full ordering include:
  40. o The smp_mb() full memory barrier.
  41. o Value-returning RMW atomic operations whose names do not end in
  42. _acquire, _release, or _relaxed.
  43. o RCU's grace-period primitives.
  44. First, the smp_mb() full memory barrier orders all of the CPU's prior
  45. accesses against all subsequent accesses from the viewpoint of all CPUs.
  46. In other words, all CPUs will agree that any earlier action taken
  47. by that CPU happened before any later action taken by that same CPU.
  48. For example, consider the following:
  49. WRITE_ONCE(x, 1);
  50. smp_mb(); // Order store to x before load from y.
  51. r1 = READ_ONCE(y);
  52. All CPUs will agree that the store to "x" happened before the load
  53. from "y", as indicated by the comment. And yes, please comment your
  54. memory-ordering primitives. It is surprisingly hard to remember their
  55. purpose after even a few months.
  56. Second, some RMW atomic operations provide full ordering. These
  57. operations include value-returning RMW atomic operations (that is, those
  58. with non-void return types) whose names do not end in _acquire, _release,
  59. or _relaxed. Examples include atomic_add_return(), atomic_dec_and_test(),
  60. cmpxchg(), and xchg(). Note that conditional RMW atomic operations such
  61. as cmpxchg() are only guaranteed to provide ordering when they succeed.
  62. When RMW atomic operations provide full ordering, they partition the
  63. CPU's accesses into three groups:
  64. 1. All code that executed prior to the RMW atomic operation.
  65. 2. The RMW atomic operation itself.
  66. 3. All code that executed after the RMW atomic operation.
  67. All CPUs will agree that any operation in a given partition happened
  68. before any operation in a higher-numbered partition.
  69. In contrast, non-value-returning RMW atomic operations (that is, those
  70. with void return types) do not guarantee any ordering whatsoever. Nor do
  71. value-returning RMW atomic operations whose names end in _relaxed.
  72. Examples of the former include atomic_inc() and atomic_dec(),
  73. while examples of the latter include atomic_cmpxchg_relaxed() and
  74. atomic_xchg_relaxed(). Similarly, value-returning non-RMW atomic
  75. operations such as atomic_read() do not guarantee full ordering, and
  76. are covered in the later section on unordered operations.
  77. Value-returning RMW atomic operations whose names end in _acquire or
  78. _release provide limited ordering, and will be described later in this
  79. document.
  80. Finally, RCU's grace-period primitives provide full ordering. These
  81. primitives include synchronize_rcu(), synchronize_rcu_expedited(),
  82. synchronize_srcu() and so on. However, these primitives have orders
  83. of magnitude greater overhead than smp_mb(), atomic_xchg(), and so on.
  84. Furthermore, RCU's grace-period primitives can only be invoked in
  85. sleepable contexts. Therefore, RCU's grace-period primitives are
  86. typically instead used to provide ordering against RCU read-side critical
  87. sections, as documented in their comment headers. But of course if you
  88. need a synchronize_rcu() to interact with readers, it costs you nothing
  89. to also rely on its additional full-memory-barrier semantics. Just please
  90. carefully comment this, otherwise your future self will hate you.
  91. RMW Ordering Augmentation Barriers
  92. ----------------------------------
  93. As noted in the previous section, non-value-returning RMW operations
  94. such as atomic_inc() and atomic_dec() guarantee no ordering whatsoever.
  95. Nevertheless, a number of popular CPU families, including x86, provide
  96. full ordering for these primitives. One way to obtain full ordering on
  97. all architectures is to add a call to smp_mb():
  98. WRITE_ONCE(x, 1);
  99. atomic_inc(&my_counter);
  100. smp_mb(); // Inefficient on x86!!!
  101. r1 = READ_ONCE(y);
  102. This works, but the added smp_mb() adds needless overhead for
  103. x86, on which atomic_inc() provides full ordering all by itself.
  104. The smp_mb__after_atomic() primitive can be used instead:
  105. WRITE_ONCE(x, 1);
  106. atomic_inc(&my_counter);
  107. smp_mb__after_atomic(); // Order store to x before load from y.
  108. r1 = READ_ONCE(y);
  109. The smp_mb__after_atomic() primitive emits code only on CPUs whose
  110. atomic_inc() implementations do not guarantee full ordering, thus
  111. incurring no unnecessary overhead on x86. There are a number of
  112. variations on the smp_mb__*() theme:
  113. o smp_mb__before_atomic(), which provides full ordering prior
  114. to an unordered RMW atomic operation.
  115. o smp_mb__after_atomic(), which, as shown above, provides full
  116. ordering subsequent to an unordered RMW atomic operation.
  117. o smp_mb__after_spinlock(), which provides full ordering subsequent
  118. to a successful spinlock acquisition. Note that spin_lock() is
  119. always successful but spin_trylock() might not be.
  120. o smp_mb__after_srcu_read_unlock(), which provides full ordering
  121. subsequent to an srcu_read_unlock().
  122. It is bad practice to place code between the smp__*() primitive and the
  123. operation whose ordering that it is augmenting. The reason is that the
  124. ordering of this intervening code will differ from one CPU architecture
  125. to another.
  126. Write Memory Barrier
  127. --------------------
  128. The Linux kernel's write memory barrier is smp_wmb(). If a CPU executes
  129. the following code:
  130. WRITE_ONCE(x, 1);
  131. smp_wmb();
  132. WRITE_ONCE(y, 1);
  133. Then any given CPU will see the write to "x" has having happened before
  134. the write to "y". However, you are usually better off using a release
  135. store, as described in the "Release Operations" section below.
  136. Note that smp_wmb() might fail to provide ordering for unmarked C-language
  137. stores because profile-driven optimization could determine that the
  138. value being overwritten is almost always equal to the new value. Such a
  139. compiler might then reasonably decide to transform "x = 1" and "y = 1"
  140. as follows:
  141. if (x != 1)
  142. x = 1;
  143. smp_wmb(); // BUG: does not order the reads!!!
  144. if (y != 1)
  145. y = 1;
  146. Therefore, if you need to use smp_wmb() with unmarked C-language writes,
  147. you will need to make sure that none of the compilers used to build
  148. the Linux kernel carry out this sort of transformation, both now and in
  149. the future.
  150. Read Memory Barrier
  151. -------------------
  152. The Linux kernel's read memory barrier is smp_rmb(). If a CPU executes
  153. the following code:
  154. r0 = READ_ONCE(y);
  155. smp_rmb();
  156. r1 = READ_ONCE(x);
  157. Then any given CPU will see the read from "y" as having preceded the read from
  158. "x". However, you are usually better off using an acquire load, as described
  159. in the "Acquire Operations" section below.
  160. Compiler Barrier
  161. ----------------
  162. The Linux kernel's compiler barrier is barrier(). This primitive
  163. prohibits compiler code-motion optimizations that might move memory
  164. references across the point in the code containing the barrier(), but
  165. does not constrain hardware memory ordering. For example, this can be
  166. used to prevent to compiler from moving code across an infinite loop:
  167. WRITE_ONCE(x, 1);
  168. while (dontstop)
  169. barrier();
  170. r1 = READ_ONCE(y);
  171. Without the barrier(), the compiler would be within its rights to move the
  172. WRITE_ONCE() to follow the loop. This code motion could be problematic
  173. in the case where an interrupt handler terminates the loop. Another way
  174. to handle this is to use READ_ONCE() for the load of "dontstop".
  175. Note that the barriers discussed previously use barrier() or its low-level
  176. equivalent in their implementations.
  177. Ordered Memory Accesses
  178. =======================
  179. The Linux kernel provides a wide variety of ordered memory accesses:
  180. a. Release operations.
  181. b. Acquire operations.
  182. c. RCU read-side ordering.
  183. d. Control dependencies.
  184. Each of the above categories has its own section below.
  185. Release Operations
  186. ------------------
  187. Release operations include smp_store_release(), atomic_set_release(),
  188. rcu_assign_pointer(), and value-returning RMW operations whose names
  189. end in _release. These operations order their own store against all
  190. of the CPU's prior memory accesses. Release operations often provide
  191. improved readability and performance compared to explicit barriers.
  192. For example, use of smp_store_release() saves a line compared to the
  193. smp_wmb() example above:
  194. WRITE_ONCE(x, 1);
  195. smp_store_release(&y, 1);
  196. More important, smp_store_release() makes it easier to connect up the
  197. different pieces of the concurrent algorithm. The variable stored to
  198. by the smp_store_release(), in this case "y", will normally be used in
  199. an acquire operation in other parts of the concurrent algorithm.
  200. To see the performance advantages, suppose that the above example read
  201. from "x" instead of writing to it. Then an smp_wmb() could not guarantee
  202. ordering, and an smp_mb() would be needed instead:
  203. r1 = READ_ONCE(x);
  204. smp_mb();
  205. WRITE_ONCE(y, 1);
  206. But smp_mb() often incurs much higher overhead than does
  207. smp_store_release(), which still provides the needed ordering of "x"
  208. against "y". On x86, the version using smp_store_release() might compile
  209. to a simple load instruction followed by a simple store instruction.
  210. In contrast, the smp_mb() compiles to an expensive instruction that
  211. provides the needed ordering.
  212. There is a wide variety of release operations:
  213. o Store operations, including not only the aforementioned
  214. smp_store_release(), but also atomic_set_release(), and
  215. atomic_long_set_release().
  216. o RCU's rcu_assign_pointer() operation. This is the same as
  217. smp_store_release() except that: (1) It takes the pointer to
  218. be assigned to instead of a pointer to that pointer, (2) It
  219. is intended to be used in conjunction with rcu_dereference()
  220. and similar rather than smp_load_acquire(), and (3) It checks
  221. for an RCU-protected pointer in "sparse" runs.
  222. o Value-returning RMW operations whose names end in _release,
  223. such as atomic_fetch_add_release() and cmpxchg_release().
  224. Note that release ordering is guaranteed only against the
  225. memory-store portion of the RMW operation, and not against the
  226. memory-load portion. Note also that conditional operations such
  227. as cmpxchg_release() are only guaranteed to provide ordering
  228. when they succeed.
  229. As mentioned earlier, release operations are often paired with acquire
  230. operations, which are the subject of the next section.
  231. Acquire Operations
  232. ------------------
  233. Acquire operations include smp_load_acquire(), atomic_read_acquire(),
  234. and value-returning RMW operations whose names end in _acquire. These
  235. operations order their own load against all of the CPU's subsequent
  236. memory accesses. Acquire operations often provide improved performance
  237. and readability compared to explicit barriers. For example, use of
  238. smp_load_acquire() saves a line compared to the smp_rmb() example above:
  239. r0 = smp_load_acquire(&y);
  240. r1 = READ_ONCE(x);
  241. As with smp_store_release(), this also makes it easier to connect
  242. the different pieces of the concurrent algorithm by looking for the
  243. smp_store_release() that stores to "y". In addition, smp_load_acquire()
  244. improves upon smp_rmb() by ordering against subsequent stores as well
  245. as against subsequent loads.
  246. There are a couple of categories of acquire operations:
  247. o Load operations, including not only the aforementioned
  248. smp_load_acquire(), but also atomic_read_acquire(), and
  249. atomic64_read_acquire().
  250. o Value-returning RMW operations whose names end in _acquire,
  251. such as atomic_xchg_acquire() and atomic_cmpxchg_acquire().
  252. Note that acquire ordering is guaranteed only against the
  253. memory-load portion of the RMW operation, and not against the
  254. memory-store portion. Note also that conditional operations
  255. such as atomic_cmpxchg_acquire() are only guaranteed to provide
  256. ordering when they succeed.
  257. Symmetry being what it is, acquire operations are often paired with the
  258. release operations covered earlier. For example, consider the following
  259. example, where task0() and task1() execute concurrently:
  260. void task0(void)
  261. {
  262. WRITE_ONCE(x, 1);
  263. smp_store_release(&y, 1);
  264. }
  265. void task1(void)
  266. {
  267. r0 = smp_load_acquire(&y);
  268. r1 = READ_ONCE(x);
  269. }
  270. If "x" and "y" are both initially zero, then either r0's final value
  271. will be zero or r1's final value will be one, thus providing the required
  272. ordering.
  273. RCU Read-Side Ordering
  274. ----------------------
  275. This category includes read-side markers such as rcu_read_lock()
  276. and rcu_read_unlock() as well as pointer-traversal primitives such as
  277. rcu_dereference() and srcu_dereference().
  278. Compared to locking primitives and RMW atomic operations, markers
  279. for RCU read-side critical sections incur very low overhead because
  280. they interact only with the corresponding grace-period primitives.
  281. For example, the rcu_read_lock() and rcu_read_unlock() markers interact
  282. with synchronize_rcu(), synchronize_rcu_expedited(), and call_rcu().
  283. The way this works is that if a given call to synchronize_rcu() cannot
  284. prove that it started before a given call to rcu_read_lock(), then
  285. that synchronize_rcu() must block until the matching rcu_read_unlock()
  286. is reached. For more information, please see the synchronize_rcu()
  287. docbook header comment and the material in Documentation/RCU.
  288. RCU's pointer-traversal primitives, including rcu_dereference() and
  289. srcu_dereference(), order their load (which must be a pointer) against any
  290. of the CPU's subsequent memory accesses whose address has been calculated
  291. from the value loaded. There is said to be an *address dependency*
  292. from the value returned by the rcu_dereference() or srcu_dereference()
  293. to that subsequent memory access.
  294. A call to rcu_dereference() for a given RCU-protected pointer is
  295. usually paired with a call to a call to rcu_assign_pointer() for that
  296. same pointer in much the same way that a call to smp_load_acquire() is
  297. paired with a call to smp_store_release(). Calls to rcu_dereference()
  298. and rcu_assign_pointer are often buried in other APIs, for example,
  299. the RCU list API members defined in include/linux/rculist.h. For more
  300. information, please see the docbook headers in that file, the most
  301. recent LWN article on the RCU API (https://lwn.net/Articles/777036/),
  302. and of course the material in Documentation/RCU.
  303. If the pointer value is manipulated between the rcu_dereference()
  304. that returned it and a later dereference(), please read
  305. Documentation/RCU/rcu_dereference.rst. It can also be quite helpful to
  306. review uses in the Linux kernel.
  307. Control Dependencies
  308. --------------------
  309. A control dependency extends from a marked load (READ_ONCE() or stronger)
  310. through an "if" condition to a marked store (WRITE_ONCE() or stronger)
  311. that is executed only by one of the legs of that "if" statement.
  312. Control dependencies are so named because they are mediated by
  313. control-flow instructions such as comparisons and conditional branches.
  314. In short, you can use a control dependency to enforce ordering between
  315. an READ_ONCE() and a WRITE_ONCE() when there is an "if" condition
  316. between them. The canonical example is as follows:
  317. q = READ_ONCE(a);
  318. if (q)
  319. WRITE_ONCE(b, 1);
  320. In this case, all CPUs would see the read from "a" as happening before
  321. the write to "b".
  322. However, control dependencies are easily destroyed by compiler
  323. optimizations, so any use of control dependencies must take into account
  324. all of the compilers used to build the Linux kernel. Please see the
  325. "control-dependencies.txt" file for more information.
  326. Unordered Accesses
  327. ==================
  328. Each of these two categories of unordered accesses has a section below:
  329. a. Unordered marked operations.
  330. b. Unmarked C-language accesses.
  331. Unordered Marked Operations
  332. ---------------------------
  333. Unordered operations to different variables are just that, unordered.
  334. However, if a group of CPUs apply these operations to a single variable,
  335. all the CPUs will agree on the operation order. Of course, the ordering
  336. of unordered marked accesses can also be constrained using the mechanisms
  337. described earlier in this document.
  338. These operations come in three categories:
  339. o Marked writes, such as WRITE_ONCE() and atomic_set(). These
  340. primitives required the compiler to emit the corresponding store
  341. instructions in the expected execution order, thus suppressing
  342. a number of destructive optimizations. However, they provide no
  343. hardware ordering guarantees, and in fact many CPUs will happily
  344. reorder marked writes with each other or with other unordered
  345. operations, unless these operations are to the same variable.
  346. o Marked reads, such as READ_ONCE() and atomic_read(). These
  347. primitives required the compiler to emit the corresponding load
  348. instructions in the expected execution order, thus suppressing
  349. a number of destructive optimizations. However, they provide no
  350. hardware ordering guarantees, and in fact many CPUs will happily
  351. reorder marked reads with each other or with other unordered
  352. operations, unless these operations are to the same variable.
  353. o Unordered RMW atomic operations. These are non-value-returning
  354. RMW atomic operations whose names do not end in _acquire or
  355. _release, and also value-returning RMW operations whose names
  356. end in _relaxed. Examples include atomic_add(), atomic_or(),
  357. and atomic64_fetch_xor_relaxed(). These operations do carry
  358. out the specified RMW operation atomically, for example, five
  359. concurrent atomic_inc() operations applied to a given variable
  360. will reliably increase the value of that variable by five.
  361. However, many CPUs will happily reorder these operations with
  362. each other or with other unordered operations.
  363. This category of operations can be efficiently ordered using
  364. smp_mb__before_atomic() and smp_mb__after_atomic(), as was
  365. discussed in the "RMW Ordering Augmentation Barriers" section.
  366. In short, these operations can be freely reordered unless they are all
  367. operating on a single variable or unless they are constrained by one of
  368. the operations called out earlier in this document.
  369. Unmarked C-Language Accesses
  370. ----------------------------
  371. Unmarked C-language accesses are normal variable accesses to normal
  372. variables, that is, to variables that are not "volatile" and are not
  373. C11 atomic variables. These operations provide no ordering guarantees,
  374. and further do not guarantee "atomic" access. For example, the compiler
  375. might (and sometimes does) split a plain C-language store into multiple
  376. smaller stores. A load from that same variable running on some other
  377. CPU while such a store is executing might see a value that is a mashup
  378. of the old value and the new value.
  379. Unmarked C-language accesses are unordered, and are also subject to
  380. any number of compiler optimizations, many of which can break your
  381. concurrent code. It is possible to used unmarked C-language accesses for
  382. shared variables that are subject to concurrent access, but great care
  383. is required on an ongoing basis. The compiler-constraining barrier()
  384. primitive can be helpful, as can the various ordering primitives discussed
  385. in this document. It nevertheless bears repeating that use of unmarked
  386. C-language accesses requires careful attention to not just your code,
  387. but to all the compilers that might be used to build it. Such compilers
  388. might replace a series of loads with a single load, and might replace
  389. a series of stores with a single store. Some compilers will even split
  390. a single store into multiple smaller stores.
  391. But there are some ways of using unmarked C-language accesses for shared
  392. variables without such worries:
  393. o Guard all accesses to a given variable by a particular lock,
  394. so that there are never concurrent conflicting accesses to
  395. that variable. (There are "conflicting accesses" when
  396. (1) at least one of the concurrent accesses to a variable is an
  397. unmarked C-language access and (2) when at least one of those
  398. accesses is a write, whether marked or not.)
  399. o As above, but using other synchronization primitives such
  400. as reader-writer locks or sequence locks.
  401. o Use locking or other means to ensure that all concurrent accesses
  402. to a given variable are reads.
  403. o Restrict use of a given variable to statistics or heuristics
  404. where the occasional bogus value can be tolerated.
  405. o Declare the accessed variables as C11 atomics.
  406. https://lwn.net/Articles/691128/
  407. o Declare the accessed variables as "volatile".
  408. If you need to live more dangerously, please do take the time to
  409. understand the compilers. One place to start is these two LWN
  410. articles:
  411. Who's afraid of a big bad optimizing compiler?
  412. https://lwn.net/Articles/793253
  413. Calibrating your fear of big bad optimizing compilers
  414. https://lwn.net/Articles/799218
  415. Used properly, unmarked C-language accesses can reduce overhead on
  416. fastpaths. However, the price is great care and continual attention
  417. to your compiler as new versions come out and as new optimizations
  418. are enabled.