explanation.txt 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  1. Explanation of the Linux-Kernel Memory Consistency Model
  2. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3. :Author: Alan Stern <stern@rowland.harvard.edu>
  4. :Created: October 2017
  5. .. Contents
  6. 1. INTRODUCTION
  7. 2. BACKGROUND
  8. 3. A SIMPLE EXAMPLE
  9. 4. A SELECTION OF MEMORY MODELS
  10. 5. ORDERING AND CYCLES
  11. 6. EVENTS
  12. 7. THE PROGRAM ORDER RELATION: po AND po-loc
  13. 8. A WARNING
  14. 9. DEPENDENCY RELATIONS: data, addr, and ctrl
  15. 10. THE READS-FROM RELATION: rf, rfi, and rfe
  16. 11. CACHE COHERENCE AND THE COHERENCE ORDER RELATION: co, coi, and coe
  17. 12. THE FROM-READS RELATION: fr, fri, and fre
  18. 13. AN OPERATIONAL MODEL
  19. 14. PROPAGATION ORDER RELATION: cumul-fence
  20. 15. DERIVATION OF THE LKMM FROM THE OPERATIONAL MODEL
  21. 16. SEQUENTIAL CONSISTENCY PER VARIABLE
  22. 17. ATOMIC UPDATES: rmw
  23. 18. THE PRESERVED PROGRAM ORDER RELATION: ppo
  24. 19. AND THEN THERE WAS ALPHA
  25. 20. THE HAPPENS-BEFORE RELATION: hb
  26. 21. THE PROPAGATES-BEFORE RELATION: pb
  27. 22. RCU RELATIONS: rcu-link, gp, rscs, rcu-fence, and rb
  28. 23. LOCKING
  29. 24. ODDS AND ENDS
  30. INTRODUCTION
  31. ------------
  32. The Linux-kernel memory consistency model (LKMM) is rather complex and
  33. obscure. This is particularly evident if you read through the
  34. linux-kernel.bell and linux-kernel.cat files that make up the formal
  35. version of the model; they are extremely terse and their meanings are
  36. far from clear.
  37. This document describes the ideas underlying the LKMM. It is meant
  38. for people who want to understand how the model was designed. It does
  39. not go into the details of the code in the .bell and .cat files;
  40. rather, it explains in English what the code expresses symbolically.
  41. Sections 2 (BACKGROUND) through 5 (ORDERING AND CYCLES) are aimed
  42. toward beginners; they explain what memory consistency models are and
  43. the basic notions shared by all such models. People already familiar
  44. with these concepts can skim or skip over them. Sections 6 (EVENTS)
  45. through 12 (THE FROM_READS RELATION) describe the fundamental
  46. relations used in many models. Starting in Section 13 (AN OPERATIONAL
  47. MODEL), the workings of the LKMM itself are covered.
  48. Warning: The code examples in this document are not written in the
  49. proper format for litmus tests. They don't include a header line, the
  50. initializations are not enclosed in braces, the global variables are
  51. not passed by pointers, and they don't have an "exists" clause at the
  52. end. Converting them to the right format is left as an exercise for
  53. the reader.
  54. BACKGROUND
  55. ----------
  56. A memory consistency model (or just memory model, for short) is
  57. something which predicts, given a piece of computer code running on a
  58. particular kind of system, what values may be obtained by the code's
  59. load instructions. The LKMM makes these predictions for code running
  60. as part of the Linux kernel.
  61. In practice, people tend to use memory models the other way around.
  62. That is, given a piece of code and a collection of values specified
  63. for the loads, the model will predict whether it is possible for the
  64. code to run in such a way that the loads will indeed obtain the
  65. specified values. Of course, this is just another way of expressing
  66. the same idea.
  67. For code running on a uniprocessor system, the predictions are easy:
  68. Each load instruction must obtain the value written by the most recent
  69. store instruction accessing the same location (we ignore complicating
  70. factors such as DMA and mixed-size accesses.) But on multiprocessor
  71. systems, with multiple CPUs making concurrent accesses to shared
  72. memory locations, things aren't so simple.
  73. Different architectures have differing memory models, and the Linux
  74. kernel supports a variety of architectures. The LKMM has to be fairly
  75. permissive, in the sense that any behavior allowed by one of these
  76. architectures also has to be allowed by the LKMM.
  77. A SIMPLE EXAMPLE
  78. ----------------
  79. Here is a simple example to illustrate the basic concepts. Consider
  80. some code running as part of a device driver for an input device. The
  81. driver might contain an interrupt handler which collects data from the
  82. device, stores it in a buffer, and sets a flag to indicate the buffer
  83. is full. Running concurrently on a different CPU might be a part of
  84. the driver code being executed by a process in the midst of a read(2)
  85. system call. This code tests the flag to see whether the buffer is
  86. ready, and if it is, copies the data back to userspace. The buffer
  87. and the flag are memory locations shared between the two CPUs.
  88. We can abstract out the important pieces of the driver code as follows
  89. (the reason for using WRITE_ONCE() and READ_ONCE() instead of simple
  90. assignment statements is discussed later):
  91. int buf = 0, flag = 0;
  92. P0()
  93. {
  94. WRITE_ONCE(buf, 1);
  95. WRITE_ONCE(flag, 1);
  96. }
  97. P1()
  98. {
  99. int r1;
  100. int r2 = 0;
  101. r1 = READ_ONCE(flag);
  102. if (r1)
  103. r2 = READ_ONCE(buf);
  104. }
  105. Here the P0() function represents the interrupt handler running on one
  106. CPU and P1() represents the read() routine running on another. The
  107. value 1 stored in buf represents input data collected from the device.
  108. Thus, P0 stores the data in buf and then sets flag. Meanwhile, P1
  109. reads flag into the private variable r1, and if it is set, reads the
  110. data from buf into a second private variable r2 for copying to
  111. userspace. (Presumably if flag is not set then the driver will wait a
  112. while and try again.)
  113. This pattern of memory accesses, where one CPU stores values to two
  114. shared memory locations and another CPU loads from those locations in
  115. the opposite order, is widely known as the "Message Passing" or MP
  116. pattern. It is typical of memory access patterns in the kernel.
  117. Please note that this example code is a simplified abstraction. Real
  118. buffers are usually larger than a single integer, real device drivers
  119. usually use sleep and wakeup mechanisms rather than polling for I/O
  120. completion, and real code generally doesn't bother to copy values into
  121. private variables before using them. All that is beside the point;
  122. the idea here is simply to illustrate the overall pattern of memory
  123. accesses by the CPUs.
  124. A memory model will predict what values P1 might obtain for its loads
  125. from flag and buf, or equivalently, what values r1 and r2 might end up
  126. with after the code has finished running.
  127. Some predictions are trivial. For instance, no sane memory model would
  128. predict that r1 = 42 or r2 = -7, because neither of those values ever
  129. gets stored in flag or buf.
  130. Some nontrivial predictions are nonetheless quite simple. For
  131. instance, P1 might run entirely before P0 begins, in which case r1 and
  132. r2 will both be 0 at the end. Or P0 might run entirely before P1
  133. begins, in which case r1 and r2 will both be 1.
  134. The interesting predictions concern what might happen when the two
  135. routines run concurrently. One possibility is that P1 runs after P0's
  136. store to buf but before the store to flag. In this case, r1 and r2
  137. will again both be 0. (If P1 had been designed to read buf
  138. unconditionally then we would instead have r1 = 0 and r2 = 1.)
  139. However, the most interesting possibility is where r1 = 1 and r2 = 0.
  140. If this were to occur it would mean the driver contains a bug, because
  141. incorrect data would get sent to the user: 0 instead of 1. As it
  142. happens, the LKMM does predict this outcome can occur, and the example
  143. driver code shown above is indeed buggy.
  144. A SELECTION OF MEMORY MODELS
  145. ----------------------------
  146. The first widely cited memory model, and the simplest to understand,
  147. is Sequential Consistency. According to this model, systems behave as
  148. if each CPU executed its instructions in order but with unspecified
  149. timing. In other words, the instructions from the various CPUs get
  150. interleaved in a nondeterministic way, always according to some single
  151. global order that agrees with the order of the instructions in the
  152. program source for each CPU. The model says that the value obtained
  153. by each load is simply the value written by the most recently executed
  154. store to the same memory location, from any CPU.
  155. For the MP example code shown above, Sequential Consistency predicts
  156. that the undesired result r1 = 1, r2 = 0 cannot occur. The reasoning
  157. goes like this:
  158. Since r1 = 1, P0 must store 1 to flag before P1 loads 1 from
  159. it, as loads can obtain values only from earlier stores.
  160. P1 loads from flag before loading from buf, since CPUs execute
  161. their instructions in order.
  162. P1 must load 0 from buf before P0 stores 1 to it; otherwise r2
  163. would be 1 since a load obtains its value from the most recent
  164. store to the same address.
  165. P0 stores 1 to buf before storing 1 to flag, since it executes
  166. its instructions in order.
  167. Since an instruction (in this case, P1's store to flag) cannot
  168. execute before itself, the specified outcome is impossible.
  169. However, real computer hardware almost never follows the Sequential
  170. Consistency memory model; doing so would rule out too many valuable
  171. performance optimizations. On ARM and PowerPC architectures, for
  172. instance, the MP example code really does sometimes yield r1 = 1 and
  173. r2 = 0.
  174. x86 and SPARC follow yet a different memory model: TSO (Total Store
  175. Ordering). This model predicts that the undesired outcome for the MP
  176. pattern cannot occur, but in other respects it differs from Sequential
  177. Consistency. One example is the Store Buffer (SB) pattern, in which
  178. each CPU stores to its own shared location and then loads from the
  179. other CPU's location:
  180. int x = 0, y = 0;
  181. P0()
  182. {
  183. int r0;
  184. WRITE_ONCE(x, 1);
  185. r0 = READ_ONCE(y);
  186. }
  187. P1()
  188. {
  189. int r1;
  190. WRITE_ONCE(y, 1);
  191. r1 = READ_ONCE(x);
  192. }
  193. Sequential Consistency predicts that the outcome r0 = 0, r1 = 0 is
  194. impossible. (Exercise: Figure out the reasoning.) But TSO allows
  195. this outcome to occur, and in fact it does sometimes occur on x86 and
  196. SPARC systems.
  197. The LKMM was inspired by the memory models followed by PowerPC, ARM,
  198. x86, Alpha, and other architectures. However, it is different in
  199. detail from each of them.
  200. ORDERING AND CYCLES
  201. -------------------
  202. Memory models are all about ordering. Often this is temporal ordering
  203. (i.e., the order in which certain events occur) but it doesn't have to
  204. be; consider for example the order of instructions in a program's
  205. source code. We saw above that Sequential Consistency makes an
  206. important assumption that CPUs execute instructions in the same order
  207. as those instructions occur in the code, and there are many other
  208. instances of ordering playing central roles in memory models.
  209. The counterpart to ordering is a cycle. Ordering rules out cycles:
  210. It's not possible to have X ordered before Y, Y ordered before Z, and
  211. Z ordered before X, because this would mean that X is ordered before
  212. itself. The analysis of the MP example under Sequential Consistency
  213. involved just such an impossible cycle:
  214. W: P0 stores 1 to flag executes before
  215. X: P1 loads 1 from flag executes before
  216. Y: P1 loads 0 from buf executes before
  217. Z: P0 stores 1 to buf executes before
  218. W: P0 stores 1 to flag.
  219. In short, if a memory model requires certain accesses to be ordered,
  220. and a certain outcome for the loads in a piece of code can happen only
  221. if those accesses would form a cycle, then the memory model predicts
  222. that outcome cannot occur.
  223. The LKMM is defined largely in terms of cycles, as we will see.
  224. EVENTS
  225. ------
  226. The LKMM does not work directly with the C statements that make up
  227. kernel source code. Instead it considers the effects of those
  228. statements in a more abstract form, namely, events. The model
  229. includes three types of events:
  230. Read events correspond to loads from shared memory, such as
  231. calls to READ_ONCE(), smp_load_acquire(), or
  232. rcu_dereference().
  233. Write events correspond to stores to shared memory, such as
  234. calls to WRITE_ONCE(), smp_store_release(), or atomic_set().
  235. Fence events correspond to memory barriers (also known as
  236. fences), such as calls to smp_rmb() or rcu_read_lock().
  237. These categories are not exclusive; a read or write event can also be
  238. a fence. This happens with functions like smp_load_acquire() or
  239. spin_lock(). However, no single event can be both a read and a write.
  240. Atomic read-modify-write accesses, such as atomic_inc() or xchg(),
  241. correspond to a pair of events: a read followed by a write. (The
  242. write event is omitted for executions where it doesn't occur, such as
  243. a cmpxchg() where the comparison fails.)
  244. Other parts of the code, those which do not involve interaction with
  245. shared memory, do not give rise to events. Thus, arithmetic and
  246. logical computations, control-flow instructions, or accesses to
  247. private memory or CPU registers are not of central interest to the
  248. memory model. They only affect the model's predictions indirectly.
  249. For example, an arithmetic computation might determine the value that
  250. gets stored to a shared memory location (or in the case of an array
  251. index, the address where the value gets stored), but the memory model
  252. is concerned only with the store itself -- its value and its address
  253. -- not the computation leading up to it.
  254. Events in the LKMM can be linked by various relations, which we will
  255. describe in the following sections. The memory model requires certain
  256. of these relations to be orderings, that is, it requires them not to
  257. have any cycles.
  258. THE PROGRAM ORDER RELATION: po AND po-loc
  259. -----------------------------------------
  260. The most important relation between events is program order (po). You
  261. can think of it as the order in which statements occur in the source
  262. code after branches are taken into account and loops have been
  263. unrolled. A better description might be the order in which
  264. instructions are presented to a CPU's execution unit. Thus, we say
  265. that X is po-before Y (written as "X ->po Y" in formulas) if X occurs
  266. before Y in the instruction stream.
  267. This is inherently a single-CPU relation; two instructions executing
  268. on different CPUs are never linked by po. Also, it is by definition
  269. an ordering so it cannot have any cycles.
  270. po-loc is a sub-relation of po. It links two memory accesses when the
  271. first comes before the second in program order and they access the
  272. same memory location (the "-loc" suffix).
  273. Although this may seem straightforward, there is one subtle aspect to
  274. program order we need to explain. The LKMM was inspired by low-level
  275. architectural memory models which describe the behavior of machine
  276. code, and it retains their outlook to a considerable extent. The
  277. read, write, and fence events used by the model are close in spirit to
  278. individual machine instructions. Nevertheless, the LKMM describes
  279. kernel code written in C, and the mapping from C to machine code can
  280. be extremely complex.
  281. Optimizing compilers have great freedom in the way they translate
  282. source code to object code. They are allowed to apply transformations
  283. that add memory accesses, eliminate accesses, combine them, split them
  284. into pieces, or move them around. Faced with all these possibilities,
  285. the LKMM basically gives up. It insists that the code it analyzes
  286. must contain no ordinary accesses to shared memory; all accesses must
  287. be performed using READ_ONCE(), WRITE_ONCE(), or one of the other
  288. atomic or synchronization primitives. These primitives prevent a
  289. large number of compiler optimizations. In particular, it is
  290. guaranteed that the compiler will not remove such accesses from the
  291. generated code (unless it can prove the accesses will never be
  292. executed), it will not change the order in which they occur in the
  293. code (within limits imposed by the C standard), and it will not
  294. introduce extraneous accesses.
  295. This explains why the MP and SB examples above used READ_ONCE() and
  296. WRITE_ONCE() rather than ordinary memory accesses. Thanks to this
  297. usage, we can be certain that in the MP example, P0's write event to
  298. buf really is po-before its write event to flag, and similarly for the
  299. other shared memory accesses in the examples.
  300. Private variables are not subject to this restriction. Since they are
  301. not shared between CPUs, they can be accessed normally without
  302. READ_ONCE() or WRITE_ONCE(), and there will be no ill effects. In
  303. fact, they need not even be stored in normal memory at all -- in
  304. principle a private variable could be stored in a CPU register (hence
  305. the convention that these variables have names starting with the
  306. letter 'r').
  307. A WARNING
  308. ---------
  309. The protections provided by READ_ONCE(), WRITE_ONCE(), and others are
  310. not perfect; and under some circumstances it is possible for the
  311. compiler to undermine the memory model. Here is an example. Suppose
  312. both branches of an "if" statement store the same value to the same
  313. location:
  314. r1 = READ_ONCE(x);
  315. if (r1) {
  316. WRITE_ONCE(y, 2);
  317. ... /* do something */
  318. } else {
  319. WRITE_ONCE(y, 2);
  320. ... /* do something else */
  321. }
  322. For this code, the LKMM predicts that the load from x will always be
  323. executed before either of the stores to y. However, a compiler could
  324. lift the stores out of the conditional, transforming the code into
  325. something resembling:
  326. r1 = READ_ONCE(x);
  327. WRITE_ONCE(y, 2);
  328. if (r1) {
  329. ... /* do something */
  330. } else {
  331. ... /* do something else */
  332. }
  333. Given this version of the code, the LKMM would predict that the load
  334. from x could be executed after the store to y. Thus, the memory
  335. model's original prediction could be invalidated by the compiler.
  336. Another issue arises from the fact that in C, arguments to many
  337. operators and function calls can be evaluated in any order. For
  338. example:
  339. r1 = f(5) + g(6);
  340. The object code might call f(5) either before or after g(6); the
  341. memory model cannot assume there is a fixed program order relation
  342. between them. (In fact, if the functions are inlined then the
  343. compiler might even interleave their object code.)
  344. DEPENDENCY RELATIONS: data, addr, and ctrl
  345. ------------------------------------------
  346. We say that two events are linked by a dependency relation when the
  347. execution of the second event depends in some way on a value obtained
  348. from memory by the first. The first event must be a read, and the
  349. value it obtains must somehow affect what the second event does.
  350. There are three kinds of dependencies: data, address (addr), and
  351. control (ctrl).
  352. A read and a write event are linked by a data dependency if the value
  353. obtained by the read affects the value stored by the write. As a very
  354. simple example:
  355. int x, y;
  356. r1 = READ_ONCE(x);
  357. WRITE_ONCE(y, r1 + 5);
  358. The value stored by the WRITE_ONCE obviously depends on the value
  359. loaded by the READ_ONCE. Such dependencies can wind through
  360. arbitrarily complicated computations, and a write can depend on the
  361. values of multiple reads.
  362. A read event and another memory access event are linked by an address
  363. dependency if the value obtained by the read affects the location
  364. accessed by the other event. The second event can be either a read or
  365. a write. Here's another simple example:
  366. int a[20];
  367. int i;
  368. r1 = READ_ONCE(i);
  369. r2 = READ_ONCE(a[r1]);
  370. Here the location accessed by the second READ_ONCE() depends on the
  371. index value loaded by the first. Pointer indirection also gives rise
  372. to address dependencies, since the address of a location accessed
  373. through a pointer will depend on the value read earlier from that
  374. pointer.
  375. Finally, a read event and another memory access event are linked by a
  376. control dependency if the value obtained by the read affects whether
  377. the second event is executed at all. Simple example:
  378. int x, y;
  379. r1 = READ_ONCE(x);
  380. if (r1)
  381. WRITE_ONCE(y, 1984);
  382. Execution of the WRITE_ONCE() is controlled by a conditional expression
  383. which depends on the value obtained by the READ_ONCE(); hence there is
  384. a control dependency from the load to the store.
  385. It should be pretty obvious that events can only depend on reads that
  386. come earlier in program order. Symbolically, if we have R ->data X,
  387. R ->addr X, or R ->ctrl X (where R is a read event), then we must also
  388. have R ->po X. It wouldn't make sense for a computation to depend
  389. somehow on a value that doesn't get loaded from shared memory until
  390. later in the code!
  391. THE READS-FROM RELATION: rf, rfi, and rfe
  392. -----------------------------------------
  393. The reads-from relation (rf) links a write event to a read event when
  394. the value loaded by the read is the value that was stored by the
  395. write. In colloquial terms, the load "reads from" the store. We
  396. write W ->rf R to indicate that the load R reads from the store W. We
  397. further distinguish the cases where the load and the store occur on
  398. the same CPU (internal reads-from, or rfi) and where they occur on
  399. different CPUs (external reads-from, or rfe).
  400. For our purposes, a memory location's initial value is treated as
  401. though it had been written there by an imaginary initial store that
  402. executes on a separate CPU before the program runs.
  403. Usage of the rf relation implicitly assumes that loads will always
  404. read from a single store. It doesn't apply properly in the presence
  405. of load-tearing, where a load obtains some of its bits from one store
  406. and some of them from another store. Fortunately, use of READ_ONCE()
  407. and WRITE_ONCE() will prevent load-tearing; it's not possible to have:
  408. int x = 0;
  409. P0()
  410. {
  411. WRITE_ONCE(x, 0x1234);
  412. }
  413. P1()
  414. {
  415. int r1;
  416. r1 = READ_ONCE(x);
  417. }
  418. and end up with r1 = 0x1200 (partly from x's initial value and partly
  419. from the value stored by P0).
  420. On the other hand, load-tearing is unavoidable when mixed-size
  421. accesses are used. Consider this example:
  422. union {
  423. u32 w;
  424. u16 h[2];
  425. } x;
  426. P0()
  427. {
  428. WRITE_ONCE(x.h[0], 0x1234);
  429. WRITE_ONCE(x.h[1], 0x5678);
  430. }
  431. P1()
  432. {
  433. int r1;
  434. r1 = READ_ONCE(x.w);
  435. }
  436. If r1 = 0x56781234 (little-endian!) at the end, then P1 must have read
  437. from both of P0's stores. It is possible to handle mixed-size and
  438. unaligned accesses in a memory model, but the LKMM currently does not
  439. attempt to do so. It requires all accesses to be properly aligned and
  440. of the location's actual size.
  441. CACHE COHERENCE AND THE COHERENCE ORDER RELATION: co, coi, and coe
  442. ------------------------------------------------------------------
  443. Cache coherence is a general principle requiring that in a
  444. multi-processor system, the CPUs must share a consistent view of the
  445. memory contents. Specifically, it requires that for each location in
  446. shared memory, the stores to that location must form a single global
  447. ordering which all the CPUs agree on (the coherence order), and this
  448. ordering must be consistent with the program order for accesses to
  449. that location.
  450. To put it another way, for any variable x, the coherence order (co) of
  451. the stores to x is simply the order in which the stores overwrite one
  452. another. The imaginary store which establishes x's initial value
  453. comes first in the coherence order; the store which directly
  454. overwrites the initial value comes second; the store which overwrites
  455. that value comes third, and so on.
  456. You can think of the coherence order as being the order in which the
  457. stores reach x's location in memory (or if you prefer a more
  458. hardware-centric view, the order in which the stores get written to
  459. x's cache line). We write W ->co W' if W comes before W' in the
  460. coherence order, that is, if the value stored by W gets overwritten,
  461. directly or indirectly, by the value stored by W'.
  462. Coherence order is required to be consistent with program order. This
  463. requirement takes the form of four coherency rules:
  464. Write-write coherence: If W ->po-loc W' (i.e., W comes before
  465. W' in program order and they access the same location), where W
  466. and W' are two stores, then W ->co W'.
  467. Write-read coherence: If W ->po-loc R, where W is a store and R
  468. is a load, then R must read from W or from some other store
  469. which comes after W in the coherence order.
  470. Read-write coherence: If R ->po-loc W, where R is a load and W
  471. is a store, then the store which R reads from must come before
  472. W in the coherence order.
  473. Read-read coherence: If R ->po-loc R', where R and R' are two
  474. loads, then either they read from the same store or else the
  475. store read by R comes before the store read by R' in the
  476. coherence order.
  477. This is sometimes referred to as sequential consistency per variable,
  478. because it means that the accesses to any single memory location obey
  479. the rules of the Sequential Consistency memory model. (According to
  480. Wikipedia, sequential consistency per variable and cache coherence
  481. mean the same thing except that cache coherence includes an extra
  482. requirement that every store eventually becomes visible to every CPU.)
  483. Any reasonable memory model will include cache coherence. Indeed, our
  484. expectation of cache coherence is so deeply ingrained that violations
  485. of its requirements look more like hardware bugs than programming
  486. errors:
  487. int x;
  488. P0()
  489. {
  490. WRITE_ONCE(x, 17);
  491. WRITE_ONCE(x, 23);
  492. }
  493. If the final value stored in x after this code ran was 17, you would
  494. think your computer was broken. It would be a violation of the
  495. write-write coherence rule: Since the store of 23 comes later in
  496. program order, it must also come later in x's coherence order and
  497. thus must overwrite the store of 17.
  498. int x = 0;
  499. P0()
  500. {
  501. int r1;
  502. r1 = READ_ONCE(x);
  503. WRITE_ONCE(x, 666);
  504. }
  505. If r1 = 666 at the end, this would violate the read-write coherence
  506. rule: The READ_ONCE() load comes before the WRITE_ONCE() store in
  507. program order, so it must not read from that store but rather from one
  508. coming earlier in the coherence order (in this case, x's initial
  509. value).
  510. int x = 0;
  511. P0()
  512. {
  513. WRITE_ONCE(x, 5);
  514. }
  515. P1()
  516. {
  517. int r1, r2;
  518. r1 = READ_ONCE(x);
  519. r2 = READ_ONCE(x);
  520. }
  521. If r1 = 5 (reading from P0's store) and r2 = 0 (reading from the
  522. imaginary store which establishes x's initial value) at the end, this
  523. would violate the read-read coherence rule: The r1 load comes before
  524. the r2 load in program order, so it must not read from a store that
  525. comes later in the coherence order.
  526. (As a minor curiosity, if this code had used normal loads instead of
  527. READ_ONCE() in P1, on Itanium it sometimes could end up with r1 = 5
  528. and r2 = 0! This results from parallel execution of the operations
  529. encoded in Itanium's Very-Long-Instruction-Word format, and it is yet
  530. another motivation for using READ_ONCE() when accessing shared memory
  531. locations.)
  532. Just like the po relation, co is inherently an ordering -- it is not
  533. possible for a store to directly or indirectly overwrite itself! And
  534. just like with the rf relation, we distinguish between stores that
  535. occur on the same CPU (internal coherence order, or coi) and stores
  536. that occur on different CPUs (external coherence order, or coe).
  537. On the other hand, stores to different memory locations are never
  538. related by co, just as instructions on different CPUs are never
  539. related by po. Coherence order is strictly per-location, or if you
  540. prefer, each location has its own independent coherence order.
  541. THE FROM-READS RELATION: fr, fri, and fre
  542. -----------------------------------------
  543. The from-reads relation (fr) can be a little difficult for people to
  544. grok. It describes the situation where a load reads a value that gets
  545. overwritten by a store. In other words, we have R ->fr W when the
  546. value that R reads is overwritten (directly or indirectly) by W, or
  547. equivalently, when R reads from a store which comes earlier than W in
  548. the coherence order.
  549. For example:
  550. int x = 0;
  551. P0()
  552. {
  553. int r1;
  554. r1 = READ_ONCE(x);
  555. WRITE_ONCE(x, 2);
  556. }
  557. The value loaded from x will be 0 (assuming cache coherence!), and it
  558. gets overwritten by the value 2. Thus there is an fr link from the
  559. READ_ONCE() to the WRITE_ONCE(). If the code contained any later
  560. stores to x, there would also be fr links from the READ_ONCE() to
  561. them.
  562. As with rf, rfi, and rfe, we subdivide the fr relation into fri (when
  563. the load and the store are on the same CPU) and fre (when they are on
  564. different CPUs).
  565. Note that the fr relation is determined entirely by the rf and co
  566. relations; it is not independent. Given a read event R and a write
  567. event W for the same location, we will have R ->fr W if and only if
  568. the write which R reads from is co-before W. In symbols,
  569. (R ->fr W) := (there exists W' with W' ->rf R and W' ->co W).
  570. AN OPERATIONAL MODEL
  571. --------------------
  572. The LKMM is based on various operational memory models, meaning that
  573. the models arise from an abstract view of how a computer system
  574. operates. Here are the main ideas, as incorporated into the LKMM.
  575. The system as a whole is divided into the CPUs and a memory subsystem.
  576. The CPUs are responsible for executing instructions (not necessarily
  577. in program order), and they communicate with the memory subsystem.
  578. For the most part, executing an instruction requires a CPU to perform
  579. only internal operations. However, loads, stores, and fences involve
  580. more.
  581. When CPU C executes a store instruction, it tells the memory subsystem
  582. to store a certain value at a certain location. The memory subsystem
  583. propagates the store to all the other CPUs as well as to RAM. (As a
  584. special case, we say that the store propagates to its own CPU at the
  585. time it is executed.) The memory subsystem also determines where the
  586. store falls in the location's coherence order. In particular, it must
  587. arrange for the store to be co-later than (i.e., to overwrite) any
  588. other store to the same location which has already propagated to CPU C.
  589. When a CPU executes a load instruction R, it first checks to see
  590. whether there are any as-yet unexecuted store instructions, for the
  591. same location, that come before R in program order. If there are, it
  592. uses the value of the po-latest such store as the value obtained by R,
  593. and we say that the store's value is forwarded to R. Otherwise, the
  594. CPU asks the memory subsystem for the value to load and we say that R
  595. is satisfied from memory. The memory subsystem hands back the value
  596. of the co-latest store to the location in question which has already
  597. propagated to that CPU.
  598. (In fact, the picture needs to be a little more complicated than this.
  599. CPUs have local caches, and propagating a store to a CPU really means
  600. propagating it to the CPU's local cache. A local cache can take some
  601. time to process the stores that it receives, and a store can't be used
  602. to satisfy one of the CPU's loads until it has been processed. On
  603. most architectures, the local caches process stores in
  604. First-In-First-Out order, and consequently the processing delay
  605. doesn't matter for the memory model. But on Alpha, the local caches
  606. have a partitioned design that results in non-FIFO behavior. We will
  607. discuss this in more detail later.)
  608. Note that load instructions may be executed speculatively and may be
  609. restarted under certain circumstances. The memory model ignores these
  610. premature executions; we simply say that the load executes at the
  611. final time it is forwarded or satisfied.
  612. Executing a fence (or memory barrier) instruction doesn't require a
  613. CPU to do anything special other than informing the memory subsystem
  614. about the fence. However, fences do constrain the way CPUs and the
  615. memory subsystem handle other instructions, in two respects.
  616. First, a fence forces the CPU to execute various instructions in
  617. program order. Exactly which instructions are ordered depends on the
  618. type of fence:
  619. Strong fences, including smp_mb() and synchronize_rcu(), force
  620. the CPU to execute all po-earlier instructions before any
  621. po-later instructions;
  622. smp_rmb() forces the CPU to execute all po-earlier loads
  623. before any po-later loads;
  624. smp_wmb() forces the CPU to execute all po-earlier stores
  625. before any po-later stores;
  626. Acquire fences, such as smp_load_acquire(), force the CPU to
  627. execute the load associated with the fence (e.g., the load
  628. part of an smp_load_acquire()) before any po-later
  629. instructions;
  630. Release fences, such as smp_store_release(), force the CPU to
  631. execute all po-earlier instructions before the store
  632. associated with the fence (e.g., the store part of an
  633. smp_store_release()).
  634. Second, some types of fence affect the way the memory subsystem
  635. propagates stores. When a fence instruction is executed on CPU C:
  636. For each other CPU C', smp_wmb() forces all po-earlier stores
  637. on C to propagate to C' before any po-later stores do.
  638. For each other CPU C', any store which propagates to C before
  639. a release fence is executed (including all po-earlier
  640. stores executed on C) is forced to propagate to C' before the
  641. store associated with the release fence does.
  642. Any store which propagates to C before a strong fence is
  643. executed (including all po-earlier stores on C) is forced to
  644. propagate to all other CPUs before any instructions po-after
  645. the strong fence are executed on C.
  646. The propagation ordering enforced by release fences and strong fences
  647. affects stores from other CPUs that propagate to CPU C before the
  648. fence is executed, as well as stores that are executed on C before the
  649. fence. We describe this property by saying that release fences and
  650. strong fences are A-cumulative. By contrast, smp_wmb() fences are not
  651. A-cumulative; they only affect the propagation of stores that are
  652. executed on C before the fence (i.e., those which precede the fence in
  653. program order).
  654. rcu_read_lock(), rcu_read_unlock(), and synchronize_rcu() fences have
  655. other properties which we discuss later.
  656. PROPAGATION ORDER RELATION: cumul-fence
  657. ---------------------------------------
  658. The fences which affect propagation order (i.e., strong, release, and
  659. smp_wmb() fences) are collectively referred to as cumul-fences, even
  660. though smp_wmb() isn't A-cumulative. The cumul-fence relation is
  661. defined to link memory access events E and F whenever:
  662. E and F are both stores on the same CPU and an smp_wmb() fence
  663. event occurs between them in program order; or
  664. F is a release fence and some X comes before F in program order,
  665. where either X = E or else E ->rf X; or
  666. A strong fence event occurs between some X and F in program
  667. order, where either X = E or else E ->rf X.
  668. The operational model requires that whenever W and W' are both stores
  669. and W ->cumul-fence W', then W must propagate to any given CPU
  670. before W' does. However, for different CPUs C and C', it does not
  671. require W to propagate to C before W' propagates to C'.
  672. DERIVATION OF THE LKMM FROM THE OPERATIONAL MODEL
  673. -------------------------------------------------
  674. The LKMM is derived from the restrictions imposed by the design
  675. outlined above. These restrictions involve the necessity of
  676. maintaining cache coherence and the fact that a CPU can't operate on a
  677. value before it knows what that value is, among other things.
  678. The formal version of the LKMM is defined by five requirements, or
  679. axioms:
  680. Sequential consistency per variable: This requires that the
  681. system obey the four coherency rules.
  682. Atomicity: This requires that atomic read-modify-write
  683. operations really are atomic, that is, no other stores can
  684. sneak into the middle of such an update.
  685. Happens-before: This requires that certain instructions are
  686. executed in a specific order.
  687. Propagation: This requires that certain stores propagate to
  688. CPUs and to RAM in a specific order.
  689. Rcu: This requires that RCU read-side critical sections and
  690. grace periods obey the rules of RCU, in particular, the
  691. Grace-Period Guarantee.
  692. The first and second are quite common; they can be found in many
  693. memory models (such as those for C11/C++11). The "happens-before" and
  694. "propagation" axioms have analogs in other memory models as well. The
  695. "rcu" axiom is specific to the LKMM.
  696. Each of these axioms is discussed below.
  697. SEQUENTIAL CONSISTENCY PER VARIABLE
  698. -----------------------------------
  699. According to the principle of cache coherence, the stores to any fixed
  700. shared location in memory form a global ordering. We can imagine
  701. inserting the loads from that location into this ordering, by placing
  702. each load between the store that it reads from and the following
  703. store. This leaves the relative positions of loads that read from the
  704. same store unspecified; let's say they are inserted in program order,
  705. first for CPU 0, then CPU 1, etc.
  706. You can check that the four coherency rules imply that the rf, co, fr,
  707. and po-loc relations agree with this global ordering; in other words,
  708. whenever we have X ->rf Y or X ->co Y or X ->fr Y or X ->po-loc Y, the
  709. X event comes before the Y event in the global ordering. The LKMM's
  710. "coherence" axiom expresses this by requiring the union of these
  711. relations not to have any cycles. This means it must not be possible
  712. to find events
  713. X0 -> X1 -> X2 -> ... -> Xn -> X0,
  714. where each of the links is either rf, co, fr, or po-loc. This has to
  715. hold if the accesses to the fixed memory location can be ordered as
  716. cache coherence demands.
  717. Although it is not obvious, it can be shown that the converse is also
  718. true: This LKMM axiom implies that the four coherency rules are
  719. obeyed.
  720. ATOMIC UPDATES: rmw
  721. -------------------
  722. What does it mean to say that a read-modify-write (rmw) update, such
  723. as atomic_inc(&x), is atomic? It means that the memory location (x in
  724. this case) does not get altered between the read and the write events
  725. making up the atomic operation. In particular, if two CPUs perform
  726. atomic_inc(&x) concurrently, it must be guaranteed that the final
  727. value of x will be the initial value plus two. We should never have
  728. the following sequence of events:
  729. CPU 0 loads x obtaining 13;
  730. CPU 1 loads x obtaining 13;
  731. CPU 0 stores 14 to x;
  732. CPU 1 stores 14 to x;
  733. where the final value of x is wrong (14 rather than 15).
  734. In this example, CPU 0's increment effectively gets lost because it
  735. occurs in between CPU 1's load and store. To put it another way, the
  736. problem is that the position of CPU 0's store in x's coherence order
  737. is between the store that CPU 1 reads from and the store that CPU 1
  738. performs.
  739. The same analysis applies to all atomic update operations. Therefore,
  740. to enforce atomicity the LKMM requires that atomic updates follow this
  741. rule: Whenever R and W are the read and write events composing an
  742. atomic read-modify-write and W' is the write event which R reads from,
  743. there must not be any stores coming between W' and W in the coherence
  744. order. Equivalently,
  745. (R ->rmw W) implies (there is no X with R ->fr X and X ->co W),
  746. where the rmw relation links the read and write events making up each
  747. atomic update. This is what the LKMM's "atomic" axiom says.
  748. THE PRESERVED PROGRAM ORDER RELATION: ppo
  749. -----------------------------------------
  750. There are many situations where a CPU is obligated to execute two
  751. instructions in program order. We amalgamate them into the ppo (for
  752. "preserved program order") relation, which links the po-earlier
  753. instruction to the po-later instruction and is thus a sub-relation of
  754. po.
  755. The operational model already includes a description of one such
  756. situation: Fences are a source of ppo links. Suppose X and Y are
  757. memory accesses with X ->po Y; then the CPU must execute X before Y if
  758. any of the following hold:
  759. A strong (smp_mb() or synchronize_rcu()) fence occurs between
  760. X and Y;
  761. X and Y are both stores and an smp_wmb() fence occurs between
  762. them;
  763. X and Y are both loads and an smp_rmb() fence occurs between
  764. them;
  765. X is also an acquire fence, such as smp_load_acquire();
  766. Y is also a release fence, such as smp_store_release().
  767. Another possibility, not mentioned earlier but discussed in the next
  768. section, is:
  769. X and Y are both loads, X ->addr Y (i.e., there is an address
  770. dependency from X to Y), and X is a READ_ONCE() or an atomic
  771. access.
  772. Dependencies can also cause instructions to be executed in program
  773. order. This is uncontroversial when the second instruction is a
  774. store; either a data, address, or control dependency from a load R to
  775. a store W will force the CPU to execute R before W. This is very
  776. simply because the CPU cannot tell the memory subsystem about W's
  777. store before it knows what value should be stored (in the case of a
  778. data dependency), what location it should be stored into (in the case
  779. of an address dependency), or whether the store should actually take
  780. place (in the case of a control dependency).
  781. Dependencies to load instructions are more problematic. To begin with,
  782. there is no such thing as a data dependency to a load. Next, a CPU
  783. has no reason to respect a control dependency to a load, because it
  784. can always satisfy the second load speculatively before the first, and
  785. then ignore the result if it turns out that the second load shouldn't
  786. be executed after all. And lastly, the real difficulties begin when
  787. we consider address dependencies to loads.
  788. To be fair about it, all Linux-supported architectures do execute
  789. loads in program order if there is an address dependency between them.
  790. After all, a CPU cannot ask the memory subsystem to load a value from
  791. a particular location before it knows what that location is. However,
  792. the split-cache design used by Alpha can cause it to behave in a way
  793. that looks as if the loads were executed out of order (see the next
  794. section for more details). The kernel includes a workaround for this
  795. problem when the loads come from READ_ONCE(), and therefore the LKMM
  796. includes address dependencies to loads in the ppo relation.
  797. On the other hand, dependencies can indirectly affect the ordering of
  798. two loads. This happens when there is a dependency from a load to a
  799. store and a second, po-later load reads from that store:
  800. R ->dep W ->rfi R',
  801. where the dep link can be either an address or a data dependency. In
  802. this situation we know it is possible for the CPU to execute R' before
  803. W, because it can forward the value that W will store to R'. But it
  804. cannot execute R' before R, because it cannot forward the value before
  805. it knows what that value is, or that W and R' do access the same
  806. location. However, if there is merely a control dependency between R
  807. and W then the CPU can speculatively forward W to R' before executing
  808. R; if the speculation turns out to be wrong then the CPU merely has to
  809. restart or abandon R'.
  810. (In theory, a CPU might forward a store to a load when it runs across
  811. an address dependency like this:
  812. r1 = READ_ONCE(ptr);
  813. WRITE_ONCE(*r1, 17);
  814. r2 = READ_ONCE(*r1);
  815. because it could tell that the store and the second load access the
  816. same location even before it knows what the location's address is.
  817. However, none of the architectures supported by the Linux kernel do
  818. this.)
  819. Two memory accesses of the same location must always be executed in
  820. program order if the second access is a store. Thus, if we have
  821. R ->po-loc W
  822. (the po-loc link says that R comes before W in program order and they
  823. access the same location), the CPU is obliged to execute W after R.
  824. If it executed W first then the memory subsystem would respond to R's
  825. read request with the value stored by W (or an even later store), in
  826. violation of the read-write coherence rule. Similarly, if we had
  827. W ->po-loc W'
  828. and the CPU executed W' before W, then the memory subsystem would put
  829. W' before W in the coherence order. It would effectively cause W to
  830. overwrite W', in violation of the write-write coherence rule.
  831. (Interestingly, an early ARMv8 memory model, now obsolete, proposed
  832. allowing out-of-order writes like this to occur. The model avoided
  833. violating the write-write coherence rule by requiring the CPU not to
  834. send the W write to the memory subsystem at all!)
  835. AND THEN THERE WAS ALPHA
  836. ------------------------
  837. As mentioned above, the Alpha architecture is unique in that it does
  838. not appear to respect address dependencies to loads. This means that
  839. code such as the following:
  840. int x = 0;
  841. int y = -1;
  842. int *ptr = &y;
  843. P0()
  844. {
  845. WRITE_ONCE(x, 1);
  846. smp_wmb();
  847. WRITE_ONCE(ptr, &x);
  848. }
  849. P1()
  850. {
  851. int *r1;
  852. int r2;
  853. r1 = ptr;
  854. r2 = READ_ONCE(*r1);
  855. }
  856. can malfunction on Alpha systems (notice that P1 uses an ordinary load
  857. to read ptr instead of READ_ONCE()). It is quite possible that r1 = &x
  858. and r2 = 0 at the end, in spite of the address dependency.
  859. At first glance this doesn't seem to make sense. We know that the
  860. smp_wmb() forces P0's store to x to propagate to P1 before the store
  861. to ptr does. And since P1 can't execute its second load
  862. until it knows what location to load from, i.e., after executing its
  863. first load, the value x = 1 must have propagated to P1 before the
  864. second load executed. So why doesn't r2 end up equal to 1?
  865. The answer lies in the Alpha's split local caches. Although the two
  866. stores do reach P1's local cache in the proper order, it can happen
  867. that the first store is processed by a busy part of the cache while
  868. the second store is processed by an idle part. As a result, the x = 1
  869. value may not become available for P1's CPU to read until after the
  870. ptr = &x value does, leading to the undesirable result above. The
  871. final effect is that even though the two loads really are executed in
  872. program order, it appears that they aren't.
  873. This could not have happened if the local cache had processed the
  874. incoming stores in FIFO order. By contrast, other architectures
  875. maintain at least the appearance of FIFO order.
  876. In practice, this difficulty is solved by inserting a special fence
  877. between P1's two loads when the kernel is compiled for the Alpha
  878. architecture. In fact, as of version 4.15, the kernel automatically
  879. adds this fence (called smp_read_barrier_depends() and defined as
  880. nothing at all on non-Alpha builds) after every READ_ONCE() and atomic
  881. load. The effect of the fence is to cause the CPU not to execute any
  882. po-later instructions until after the local cache has finished
  883. processing all the stores it has already received. Thus, if the code
  884. was changed to:
  885. P1()
  886. {
  887. int *r1;
  888. int r2;
  889. r1 = READ_ONCE(ptr);
  890. r2 = READ_ONCE(*r1);
  891. }
  892. then we would never get r1 = &x and r2 = 0. By the time P1 executed
  893. its second load, the x = 1 store would already be fully processed by
  894. the local cache and available for satisfying the read request. Thus
  895. we have yet another reason why shared data should always be read with
  896. READ_ONCE() or another synchronization primitive rather than accessed
  897. directly.
  898. The LKMM requires that smp_rmb(), acquire fences, and strong fences
  899. share this property with smp_read_barrier_depends(): They do not allow
  900. the CPU to execute any po-later instructions (or po-later loads in the
  901. case of smp_rmb()) until all outstanding stores have been processed by
  902. the local cache. In the case of a strong fence, the CPU first has to
  903. wait for all of its po-earlier stores to propagate to every other CPU
  904. in the system; then it has to wait for the local cache to process all
  905. the stores received as of that time -- not just the stores received
  906. when the strong fence began.
  907. And of course, none of this matters for any architecture other than
  908. Alpha.
  909. THE HAPPENS-BEFORE RELATION: hb
  910. -------------------------------
  911. The happens-before relation (hb) links memory accesses that have to
  912. execute in a certain order. hb includes the ppo relation and two
  913. others, one of which is rfe.
  914. W ->rfe R implies that W and R are on different CPUs. It also means
  915. that W's store must have propagated to R's CPU before R executed;
  916. otherwise R could not have read the value stored by W. Therefore W
  917. must have executed before R, and so we have W ->hb R.
  918. The equivalent fact need not hold if W ->rfi R (i.e., W and R are on
  919. the same CPU). As we have already seen, the operational model allows
  920. W's value to be forwarded to R in such cases, meaning that R may well
  921. execute before W does.
  922. It's important to understand that neither coe nor fre is included in
  923. hb, despite their similarities to rfe. For example, suppose we have
  924. W ->coe W'. This means that W and W' are stores to the same location,
  925. they execute on different CPUs, and W comes before W' in the coherence
  926. order (i.e., W' overwrites W). Nevertheless, it is possible for W' to
  927. execute before W, because the decision as to which store overwrites
  928. the other is made later by the memory subsystem. When the stores are
  929. nearly simultaneous, either one can come out on top. Similarly,
  930. R ->fre W means that W overwrites the value which R reads, but it
  931. doesn't mean that W has to execute after R. All that's necessary is
  932. for the memory subsystem not to propagate W to R's CPU until after R
  933. has executed, which is possible if W executes shortly before R.
  934. The third relation included in hb is like ppo, in that it only links
  935. events that are on the same CPU. However it is more difficult to
  936. explain, because it arises only indirectly from the requirement of
  937. cache coherence. The relation is called prop, and it links two events
  938. on CPU C in situations where a store from some other CPU comes after
  939. the first event in the coherence order and propagates to C before the
  940. second event executes.
  941. This is best explained with some examples. The simplest case looks
  942. like this:
  943. int x;
  944. P0()
  945. {
  946. int r1;
  947. WRITE_ONCE(x, 1);
  948. r1 = READ_ONCE(x);
  949. }
  950. P1()
  951. {
  952. WRITE_ONCE(x, 8);
  953. }
  954. If r1 = 8 at the end then P0's accesses must have executed in program
  955. order. We can deduce this from the operational model; if P0's load
  956. had executed before its store then the value of the store would have
  957. been forwarded to the load, so r1 would have ended up equal to 1, not
  958. 8. In this case there is a prop link from P0's write event to its read
  959. event, because P1's store came after P0's store in x's coherence
  960. order, and P1's store propagated to P0 before P0's load executed.
  961. An equally simple case involves two loads of the same location that
  962. read from different stores:
  963. int x = 0;
  964. P0()
  965. {
  966. int r1, r2;
  967. r1 = READ_ONCE(x);
  968. r2 = READ_ONCE(x);
  969. }
  970. P1()
  971. {
  972. WRITE_ONCE(x, 9);
  973. }
  974. If r1 = 0 and r2 = 9 at the end then P0's accesses must have executed
  975. in program order. If the second load had executed before the first
  976. then the x = 9 store must have been propagated to P0 before the first
  977. load executed, and so r1 would have been 9 rather than 0. In this
  978. case there is a prop link from P0's first read event to its second,
  979. because P1's store overwrote the value read by P0's first load, and
  980. P1's store propagated to P0 before P0's second load executed.
  981. Less trivial examples of prop all involve fences. Unlike the simple
  982. examples above, they can require that some instructions are executed
  983. out of program order. This next one should look familiar:
  984. int buf = 0, flag = 0;
  985. P0()
  986. {
  987. WRITE_ONCE(buf, 1);
  988. smp_wmb();
  989. WRITE_ONCE(flag, 1);
  990. }
  991. P1()
  992. {
  993. int r1;
  994. int r2;
  995. r1 = READ_ONCE(flag);
  996. r2 = READ_ONCE(buf);
  997. }
  998. This is the MP pattern again, with an smp_wmb() fence between the two
  999. stores. If r1 = 1 and r2 = 0 at the end then there is a prop link
  1000. from P1's second load to its first (backwards!). The reason is
  1001. similar to the previous examples: The value P1 loads from buf gets
  1002. overwritten by P0's store to buf, the fence guarantees that the store
  1003. to buf will propagate to P1 before the store to flag does, and the
  1004. store to flag propagates to P1 before P1 reads flag.
  1005. The prop link says that in order to obtain the r1 = 1, r2 = 0 result,
  1006. P1 must execute its second load before the first. Indeed, if the load
  1007. from flag were executed first, then the buf = 1 store would already
  1008. have propagated to P1 by the time P1's load from buf executed, so r2
  1009. would have been 1 at the end, not 0. (The reasoning holds even for
  1010. Alpha, although the details are more complicated and we will not go
  1011. into them.)
  1012. But what if we put an smp_rmb() fence between P1's loads? The fence
  1013. would force the two loads to be executed in program order, and it
  1014. would generate a cycle in the hb relation: The fence would create a ppo
  1015. link (hence an hb link) from the first load to the second, and the
  1016. prop relation would give an hb link from the second load to the first.
  1017. Since an instruction can't execute before itself, we are forced to
  1018. conclude that if an smp_rmb() fence is added, the r1 = 1, r2 = 0
  1019. outcome is impossible -- as it should be.
  1020. The formal definition of the prop relation involves a coe or fre link,
  1021. followed by an arbitrary number of cumul-fence links, ending with an
  1022. rfe link. You can concoct more exotic examples, containing more than
  1023. one fence, although this quickly leads to diminishing returns in terms
  1024. of complexity. For instance, here's an example containing a coe link
  1025. followed by two fences and an rfe link, utilizing the fact that
  1026. release fences are A-cumulative:
  1027. int x, y, z;
  1028. P0()
  1029. {
  1030. int r0;
  1031. WRITE_ONCE(x, 1);
  1032. r0 = READ_ONCE(z);
  1033. }
  1034. P1()
  1035. {
  1036. WRITE_ONCE(x, 2);
  1037. smp_wmb();
  1038. WRITE_ONCE(y, 1);
  1039. }
  1040. P2()
  1041. {
  1042. int r2;
  1043. r2 = READ_ONCE(y);
  1044. smp_store_release(&z, 1);
  1045. }
  1046. If x = 2, r0 = 1, and r2 = 1 after this code runs then there is a prop
  1047. link from P0's store to its load. This is because P0's store gets
  1048. overwritten by P1's store since x = 2 at the end (a coe link), the
  1049. smp_wmb() ensures that P1's store to x propagates to P2 before the
  1050. store to y does (the first fence), the store to y propagates to P2
  1051. before P2's load and store execute, P2's smp_store_release()
  1052. guarantees that the stores to x and y both propagate to P0 before the
  1053. store to z does (the second fence), and P0's load executes after the
  1054. store to z has propagated to P0 (an rfe link).
  1055. In summary, the fact that the hb relation links memory access events
  1056. in the order they execute means that it must not have cycles. This
  1057. requirement is the content of the LKMM's "happens-before" axiom.
  1058. The LKMM defines yet another relation connected to times of
  1059. instruction execution, but it is not included in hb. It relies on the
  1060. particular properties of strong fences, which we cover in the next
  1061. section.
  1062. THE PROPAGATES-BEFORE RELATION: pb
  1063. ----------------------------------
  1064. The propagates-before (pb) relation capitalizes on the special
  1065. features of strong fences. It links two events E and F whenever some
  1066. store is coherence-later than E and propagates to every CPU and to RAM
  1067. before F executes. The formal definition requires that E be linked to
  1068. F via a coe or fre link, an arbitrary number of cumul-fences, an
  1069. optional rfe link, a strong fence, and an arbitrary number of hb
  1070. links. Let's see how this definition works out.
  1071. Consider first the case where E is a store (implying that the sequence
  1072. of links begins with coe). Then there are events W, X, Y, and Z such
  1073. that:
  1074. E ->coe W ->cumul-fence* X ->rfe? Y ->strong-fence Z ->hb* F,
  1075. where the * suffix indicates an arbitrary number of links of the
  1076. specified type, and the ? suffix indicates the link is optional (Y may
  1077. be equal to X). Because of the cumul-fence links, we know that W will
  1078. propagate to Y's CPU before X does, hence before Y executes and hence
  1079. before the strong fence executes. Because this fence is strong, we
  1080. know that W will propagate to every CPU and to RAM before Z executes.
  1081. And because of the hb links, we know that Z will execute before F.
  1082. Thus W, which comes later than E in the coherence order, will
  1083. propagate to every CPU and to RAM before F executes.
  1084. The case where E is a load is exactly the same, except that the first
  1085. link in the sequence is fre instead of coe.
  1086. The existence of a pb link from E to F implies that E must execute
  1087. before F. To see why, suppose that F executed first. Then W would
  1088. have propagated to E's CPU before E executed. If E was a store, the
  1089. memory subsystem would then be forced to make E come after W in the
  1090. coherence order, contradicting the fact that E ->coe W. If E was a
  1091. load, the memory subsystem would then be forced to satisfy E's read
  1092. request with the value stored by W or an even later store,
  1093. contradicting the fact that E ->fre W.
  1094. A good example illustrating how pb works is the SB pattern with strong
  1095. fences:
  1096. int x = 0, y = 0;
  1097. P0()
  1098. {
  1099. int r0;
  1100. WRITE_ONCE(x, 1);
  1101. smp_mb();
  1102. r0 = READ_ONCE(y);
  1103. }
  1104. P1()
  1105. {
  1106. int r1;
  1107. WRITE_ONCE(y, 1);
  1108. smp_mb();
  1109. r1 = READ_ONCE(x);
  1110. }
  1111. If r0 = 0 at the end then there is a pb link from P0's load to P1's
  1112. load: an fre link from P0's load to P1's store (which overwrites the
  1113. value read by P0), and a strong fence between P1's store and its load.
  1114. In this example, the sequences of cumul-fence and hb links are empty.
  1115. Note that this pb link is not included in hb as an instance of prop,
  1116. because it does not start and end on the same CPU.
  1117. Similarly, if r1 = 0 at the end then there is a pb link from P1's load
  1118. to P0's. This means that if both r1 and r2 were 0 there would be a
  1119. cycle in pb, which is not possible since an instruction cannot execute
  1120. before itself. Thus, adding smp_mb() fences to the SB pattern
  1121. prevents the r0 = 0, r1 = 0 outcome.
  1122. In summary, the fact that the pb relation links events in the order
  1123. they execute means that it cannot have cycles. This requirement is
  1124. the content of the LKMM's "propagation" axiom.
  1125. RCU RELATIONS: rcu-link, gp, rscs, rcu-fence, and rb
  1126. ----------------------------------------------------
  1127. RCU (Read-Copy-Update) is a powerful synchronization mechanism. It
  1128. rests on two concepts: grace periods and read-side critical sections.
  1129. A grace period is the span of time occupied by a call to
  1130. synchronize_rcu(). A read-side critical section (or just critical
  1131. section, for short) is a region of code delimited by rcu_read_lock()
  1132. at the start and rcu_read_unlock() at the end. Critical sections can
  1133. be nested, although we won't make use of this fact.
  1134. As far as memory models are concerned, RCU's main feature is its
  1135. Grace-Period Guarantee, which states that a critical section can never
  1136. span a full grace period. In more detail, the Guarantee says:
  1137. If a critical section starts before a grace period then it
  1138. must end before the grace period does. In addition, every
  1139. store that propagates to the critical section's CPU before the
  1140. end of the critical section must propagate to every CPU before
  1141. the end of the grace period.
  1142. If a critical section ends after a grace period ends then it
  1143. must start after the grace period does. In addition, every
  1144. store that propagates to the grace period's CPU before the
  1145. start of the grace period must propagate to every CPU before
  1146. the start of the critical section.
  1147. Here is a simple example of RCU in action:
  1148. int x, y;
  1149. P0()
  1150. {
  1151. rcu_read_lock();
  1152. WRITE_ONCE(x, 1);
  1153. WRITE_ONCE(y, 1);
  1154. rcu_read_unlock();
  1155. }
  1156. P1()
  1157. {
  1158. int r1, r2;
  1159. r1 = READ_ONCE(x);
  1160. synchronize_rcu();
  1161. r2 = READ_ONCE(y);
  1162. }
  1163. The Grace Period Guarantee tells us that when this code runs, it will
  1164. never end with r1 = 1 and r2 = 0. The reasoning is as follows. r1 = 1
  1165. means that P0's store to x propagated to P1 before P1 called
  1166. synchronize_rcu(), so P0's critical section must have started before
  1167. P1's grace period. On the other hand, r2 = 0 means that P0's store to
  1168. y, which occurs before the end of the critical section, did not
  1169. propagate to P1 before the end of the grace period, violating the
  1170. Guarantee.
  1171. In the kernel's implementations of RCU, the requirements for stores
  1172. to propagate to every CPU are fulfilled by placing strong fences at
  1173. suitable places in the RCU-related code. Thus, if a critical section
  1174. starts before a grace period does then the critical section's CPU will
  1175. execute an smp_mb() fence after the end of the critical section and
  1176. some time before the grace period's synchronize_rcu() call returns.
  1177. And if a critical section ends after a grace period does then the
  1178. synchronize_rcu() routine will execute an smp_mb() fence at its start
  1179. and some time before the critical section's opening rcu_read_lock()
  1180. executes.
  1181. What exactly do we mean by saying that a critical section "starts
  1182. before" or "ends after" a grace period? Some aspects of the meaning
  1183. are pretty obvious, as in the example above, but the details aren't
  1184. entirely clear. The LKMM formalizes this notion by means of the
  1185. rcu-link relation. rcu-link encompasses a very general notion of
  1186. "before": Among other things, X ->rcu-link Z includes cases where X
  1187. happens-before or is equal to some event Y which is equal to or comes
  1188. before Z in the coherence order. When Y = Z this says that X ->rfe Z
  1189. implies X ->rcu-link Z. In addition, when Y = X it says that X ->fr Z
  1190. and X ->co Z each imply X ->rcu-link Z.
  1191. The formal definition of the rcu-link relation is more than a little
  1192. obscure, and we won't give it here. It is closely related to the pb
  1193. relation, and the details don't matter unless you want to comb through
  1194. a somewhat lengthy formal proof. Pretty much all you need to know
  1195. about rcu-link is the information in the preceding paragraph.
  1196. The LKMM also defines the gp and rscs relations. They bring grace
  1197. periods and read-side critical sections into the picture, in the
  1198. following way:
  1199. E ->gp F means there is a synchronize_rcu() fence event S such
  1200. that E ->po S and either S ->po F or S = F. In simple terms,
  1201. there is a grace period po-between E and F.
  1202. E ->rscs F means there is a critical section delimited by an
  1203. rcu_read_lock() fence L and an rcu_read_unlock() fence U, such
  1204. that E ->po U and either L ->po F or L = F. You can think of
  1205. this as saying that E and F are in the same critical section
  1206. (in fact, it also allows E to be po-before the start of the
  1207. critical section and F to be po-after the end).
  1208. If we think of the rcu-link relation as standing for an extended
  1209. "before", then X ->gp Y ->rcu-link Z says that X executes before a
  1210. grace period which ends before Z executes. (In fact it covers more
  1211. than this, because it also includes cases where X executes before a
  1212. grace period and some store propagates to Z's CPU before Z executes
  1213. but doesn't propagate to some other CPU until after the grace period
  1214. ends.) Similarly, X ->rscs Y ->rcu-link Z says that X is part of (or
  1215. before the start of) a critical section which starts before Z
  1216. executes.
  1217. The LKMM goes on to define the rcu-fence relation as a sequence of gp
  1218. and rscs links separated by rcu-link links, in which the number of gp
  1219. links is >= the number of rscs links. For example:
  1220. X ->gp Y ->rcu-link Z ->rscs T ->rcu-link U ->gp V
  1221. would imply that X ->rcu-fence V, because this sequence contains two
  1222. gp links and only one rscs link. (It also implies that X ->rcu-fence T
  1223. and Z ->rcu-fence V.) On the other hand:
  1224. X ->rscs Y ->rcu-link Z ->rscs T ->rcu-link U ->gp V
  1225. does not imply X ->rcu-fence V, because the sequence contains only
  1226. one gp link but two rscs links.
  1227. The rcu-fence relation is important because the Grace Period Guarantee
  1228. means that rcu-fence acts kind of like a strong fence. In particular,
  1229. if W is a write and we have W ->rcu-fence Z, the Guarantee says that W
  1230. will propagate to every CPU before Z executes.
  1231. To prove this in full generality requires some intellectual effort.
  1232. We'll consider just a very simple case:
  1233. W ->gp X ->rcu-link Y ->rscs Z.
  1234. This formula means that there is a grace period G and a critical
  1235. section C such that:
  1236. 1. W is po-before G;
  1237. 2. X is equal to or po-after G;
  1238. 3. X comes "before" Y in some sense;
  1239. 4. Y is po-before the end of C;
  1240. 5. Z is equal to or po-after the start of C.
  1241. From 2 - 4 we deduce that the grace period G ends before the critical
  1242. section C. Then the second part of the Grace Period Guarantee says
  1243. not only that G starts before C does, but also that W (which executes
  1244. on G's CPU before G starts) must propagate to every CPU before C
  1245. starts. In particular, W propagates to every CPU before Z executes
  1246. (or finishes executing, in the case where Z is equal to the
  1247. rcu_read_lock() fence event which starts C.) This sort of reasoning
  1248. can be expanded to handle all the situations covered by rcu-fence.
  1249. Finally, the LKMM defines the RCU-before (rb) relation in terms of
  1250. rcu-fence. This is done in essentially the same way as the pb
  1251. relation was defined in terms of strong-fence. We will omit the
  1252. details; the end result is that E ->rb F implies E must execute before
  1253. F, just as E ->pb F does (and for much the same reasons).
  1254. Putting this all together, the LKMM expresses the Grace Period
  1255. Guarantee by requiring that the rb relation does not contain a cycle.
  1256. Equivalently, this "rcu" axiom requires that there are no events E and
  1257. F with E ->rcu-link F ->rcu-fence E. Or to put it a third way, the
  1258. axiom requires that there are no cycles consisting of gp and rscs
  1259. alternating with rcu-link, where the number of gp links is >= the
  1260. number of rscs links.
  1261. Justifying the axiom isn't easy, but it is in fact a valid
  1262. formalization of the Grace Period Guarantee. We won't attempt to go
  1263. through the detailed argument, but the following analysis gives a
  1264. taste of what is involved. Suppose we have a violation of the first
  1265. part of the Guarantee: A critical section starts before a grace
  1266. period, and some store propagates to the critical section's CPU before
  1267. the end of the critical section but doesn't propagate to some other
  1268. CPU until after the end of the grace period.
  1269. Putting symbols to these ideas, let L and U be the rcu_read_lock() and
  1270. rcu_read_unlock() fence events delimiting the critical section in
  1271. question, and let S be the synchronize_rcu() fence event for the grace
  1272. period. Saying that the critical section starts before S means there
  1273. are events E and F where E is po-after L (which marks the start of the
  1274. critical section), E is "before" F in the sense of the rcu-link
  1275. relation, and F is po-before the grace period S:
  1276. L ->po E ->rcu-link F ->po S.
  1277. Let W be the store mentioned above, let Z come before the end of the
  1278. critical section and witness that W propagates to the critical
  1279. section's CPU by reading from W, and let Y on some arbitrary CPU be a
  1280. witness that W has not propagated to that CPU, where Y happens after
  1281. some event X which is po-after S. Symbolically, this amounts to:
  1282. S ->po X ->hb* Y ->fr W ->rf Z ->po U.
  1283. The fr link from Y to W indicates that W has not propagated to Y's CPU
  1284. at the time that Y executes. From this, it can be shown (see the
  1285. discussion of the rcu-link relation earlier) that X and Z are related
  1286. by rcu-link, yielding:
  1287. S ->po X ->rcu-link Z ->po U.
  1288. The formulas say that S is po-between F and X, hence F ->gp X. They
  1289. also say that Z comes before the end of the critical section and E
  1290. comes after its start, hence Z ->rscs E. From all this we obtain:
  1291. F ->gp X ->rcu-link Z ->rscs E ->rcu-link F,
  1292. a forbidden cycle. Thus the "rcu" axiom rules out this violation of
  1293. the Grace Period Guarantee.
  1294. For something a little more down-to-earth, let's see how the axiom
  1295. works out in practice. Consider the RCU code example from above, this
  1296. time with statement labels added to the memory access instructions:
  1297. int x, y;
  1298. P0()
  1299. {
  1300. rcu_read_lock();
  1301. W: WRITE_ONCE(x, 1);
  1302. X: WRITE_ONCE(y, 1);
  1303. rcu_read_unlock();
  1304. }
  1305. P1()
  1306. {
  1307. int r1, r2;
  1308. Y: r1 = READ_ONCE(x);
  1309. synchronize_rcu();
  1310. Z: r2 = READ_ONCE(y);
  1311. }
  1312. If r2 = 0 at the end then P0's store at X overwrites the value that
  1313. P1's load at Z reads from, so we have Z ->fre X and thus Z ->rcu-link X.
  1314. In addition, there is a synchronize_rcu() between Y and Z, so therefore
  1315. we have Y ->gp Z.
  1316. If r1 = 1 at the end then P1's load at Y reads from P0's store at W,
  1317. so we have W ->rcu-link Y. In addition, W and X are in the same critical
  1318. section, so therefore we have X ->rscs W.
  1319. Then X ->rscs W ->rcu-link Y ->gp Z ->rcu-link X is a forbidden cycle,
  1320. violating the "rcu" axiom. Hence the outcome is not allowed by the
  1321. LKMM, as we would expect.
  1322. For contrast, let's see what can happen in a more complicated example:
  1323. int x, y, z;
  1324. P0()
  1325. {
  1326. int r0;
  1327. rcu_read_lock();
  1328. W: r0 = READ_ONCE(x);
  1329. X: WRITE_ONCE(y, 1);
  1330. rcu_read_unlock();
  1331. }
  1332. P1()
  1333. {
  1334. int r1;
  1335. Y: r1 = READ_ONCE(y);
  1336. synchronize_rcu();
  1337. Z: WRITE_ONCE(z, 1);
  1338. }
  1339. P2()
  1340. {
  1341. int r2;
  1342. rcu_read_lock();
  1343. U: r2 = READ_ONCE(z);
  1344. V: WRITE_ONCE(x, 1);
  1345. rcu_read_unlock();
  1346. }
  1347. If r0 = r1 = r2 = 1 at the end, then similar reasoning to before shows
  1348. that W ->rscs X ->rcu-link Y ->gp Z ->rcu-link U ->rscs V ->rcu-link W.
  1349. However this cycle is not forbidden, because the sequence of relations
  1350. contains fewer instances of gp (one) than of rscs (two). Consequently
  1351. the outcome is allowed by the LKMM. The following instruction timing
  1352. diagram shows how it might actually occur:
  1353. P0 P1 P2
  1354. -------------------- -------------------- --------------------
  1355. rcu_read_lock()
  1356. X: WRITE_ONCE(y, 1)
  1357. Y: r1 = READ_ONCE(y)
  1358. synchronize_rcu() starts
  1359. . rcu_read_lock()
  1360. . V: WRITE_ONCE(x, 1)
  1361. W: r0 = READ_ONCE(x) .
  1362. rcu_read_unlock() .
  1363. synchronize_rcu() ends
  1364. Z: WRITE_ONCE(z, 1)
  1365. U: r2 = READ_ONCE(z)
  1366. rcu_read_unlock()
  1367. This requires P0 and P2 to execute their loads and stores out of
  1368. program order, but of course they are allowed to do so. And as you
  1369. can see, the Grace Period Guarantee is not violated: The critical
  1370. section in P0 both starts before P1's grace period does and ends
  1371. before it does, and the critical section in P2 both starts after P1's
  1372. grace period does and ends after it does.
  1373. LOCKING
  1374. -------
  1375. The LKMM includes locking. In fact, there is special code for locking
  1376. in the formal model, added in order to make tools run faster.
  1377. However, this special code is intended to be more or less equivalent
  1378. to concepts we have already covered. A spinlock_t variable is treated
  1379. the same as an int, and spin_lock(&s) is treated almost the same as:
  1380. while (cmpxchg_acquire(&s, 0, 1) != 0)
  1381. cpu_relax();
  1382. This waits until s is equal to 0 and then atomically sets it to 1,
  1383. and the read part of the cmpxchg operation acts as an acquire fence.
  1384. An alternate way to express the same thing would be:
  1385. r = xchg_acquire(&s, 1);
  1386. along with a requirement that at the end, r = 0. Similarly,
  1387. spin_trylock(&s) is treated almost the same as:
  1388. return !cmpxchg_acquire(&s, 0, 1);
  1389. which atomically sets s to 1 if it is currently equal to 0 and returns
  1390. true if it succeeds (the read part of the cmpxchg operation acts as an
  1391. acquire fence only if the operation is successful). spin_unlock(&s)
  1392. is treated almost the same as:
  1393. smp_store_release(&s, 0);
  1394. The "almost" qualifiers above need some explanation. In the LKMM, the
  1395. store-release in a spin_unlock() and the load-acquire which forms the
  1396. first half of the atomic rmw update in a spin_lock() or a successful
  1397. spin_trylock() -- we can call these things lock-releases and
  1398. lock-acquires -- have two properties beyond those of ordinary releases
  1399. and acquires.
  1400. First, when a lock-acquire reads from a lock-release, the LKMM
  1401. requires that every instruction po-before the lock-release must
  1402. execute before any instruction po-after the lock-acquire. This would
  1403. naturally hold if the release and acquire operations were on different
  1404. CPUs, but the LKMM says it holds even when they are on the same CPU.
  1405. For example:
  1406. int x, y;
  1407. spinlock_t s;
  1408. P0()
  1409. {
  1410. int r1, r2;
  1411. spin_lock(&s);
  1412. r1 = READ_ONCE(x);
  1413. spin_unlock(&s);
  1414. spin_lock(&s);
  1415. r2 = READ_ONCE(y);
  1416. spin_unlock(&s);
  1417. }
  1418. P1()
  1419. {
  1420. WRITE_ONCE(y, 1);
  1421. smp_wmb();
  1422. WRITE_ONCE(x, 1);
  1423. }
  1424. Here the second spin_lock() reads from the first spin_unlock(), and
  1425. therefore the load of x must execute before the load of y. Thus we
  1426. cannot have r1 = 1 and r2 = 0 at the end (this is an instance of the
  1427. MP pattern).
  1428. This requirement does not apply to ordinary release and acquire
  1429. fences, only to lock-related operations. For instance, suppose P0()
  1430. in the example had been written as:
  1431. P0()
  1432. {
  1433. int r1, r2, r3;
  1434. r1 = READ_ONCE(x);
  1435. smp_store_release(&s, 1);
  1436. r3 = smp_load_acquire(&s);
  1437. r2 = READ_ONCE(y);
  1438. }
  1439. Then the CPU would be allowed to forward the s = 1 value from the
  1440. smp_store_release() to the smp_load_acquire(), executing the
  1441. instructions in the following order:
  1442. r3 = smp_load_acquire(&s); // Obtains r3 = 1
  1443. r2 = READ_ONCE(y);
  1444. r1 = READ_ONCE(x);
  1445. smp_store_release(&s, 1); // Value is forwarded
  1446. and thus it could load y before x, obtaining r2 = 0 and r1 = 1.
  1447. Second, when a lock-acquire reads from a lock-release, and some other
  1448. stores W and W' occur po-before the lock-release and po-after the
  1449. lock-acquire respectively, the LKMM requires that W must propagate to
  1450. each CPU before W' does. For example, consider:
  1451. int x, y;
  1452. spinlock_t x;
  1453. P0()
  1454. {
  1455. spin_lock(&s);
  1456. WRITE_ONCE(x, 1);
  1457. spin_unlock(&s);
  1458. }
  1459. P1()
  1460. {
  1461. int r1;
  1462. spin_lock(&s);
  1463. r1 = READ_ONCE(x);
  1464. WRITE_ONCE(y, 1);
  1465. spin_unlock(&s);
  1466. }
  1467. P2()
  1468. {
  1469. int r2, r3;
  1470. r2 = READ_ONCE(y);
  1471. smp_rmb();
  1472. r3 = READ_ONCE(x);
  1473. }
  1474. If r1 = 1 at the end then the spin_lock() in P1 must have read from
  1475. the spin_unlock() in P0. Hence the store to x must propagate to P2
  1476. before the store to y does, so we cannot have r2 = 1 and r3 = 0.
  1477. These two special requirements for lock-release and lock-acquire do
  1478. not arise from the operational model. Nevertheless, kernel developers
  1479. have come to expect and rely on them because they do hold on all
  1480. architectures supported by the Linux kernel, albeit for various
  1481. differing reasons.
  1482. ODDS AND ENDS
  1483. -------------
  1484. This section covers material that didn't quite fit anywhere in the
  1485. earlier sections.
  1486. The descriptions in this document don't always match the formal
  1487. version of the LKMM exactly. For example, the actual formal
  1488. definition of the prop relation makes the initial coe or fre part
  1489. optional, and it doesn't require the events linked by the relation to
  1490. be on the same CPU. These differences are very unimportant; indeed,
  1491. instances where the coe/fre part of prop is missing are of no interest
  1492. because all the other parts (fences and rfe) are already included in
  1493. hb anyway, and where the formal model adds prop into hb, it includes
  1494. an explicit requirement that the events being linked are on the same
  1495. CPU.
  1496. Another minor difference has to do with events that are both memory
  1497. accesses and fences, such as those corresponding to smp_load_acquire()
  1498. calls. In the formal model, these events aren't actually both reads
  1499. and fences; rather, they are read events with an annotation marking
  1500. them as acquires. (Or write events annotated as releases, in the case
  1501. smp_store_release().) The final effect is the same.
  1502. Although we didn't mention it above, the instruction execution
  1503. ordering provided by the smp_rmb() fence doesn't apply to read events
  1504. that are part of a non-value-returning atomic update. For instance,
  1505. given:
  1506. atomic_inc(&x);
  1507. smp_rmb();
  1508. r1 = READ_ONCE(y);
  1509. it is not guaranteed that the load from y will execute after the
  1510. update to x. This is because the ARMv8 architecture allows
  1511. non-value-returning atomic operations effectively to be executed off
  1512. the CPU. Basically, the CPU tells the memory subsystem to increment
  1513. x, and then the increment is carried out by the memory hardware with
  1514. no further involvement from the CPU. Since the CPU doesn't ever read
  1515. the value of x, there is nothing for the smp_rmb() fence to act on.
  1516. The LKMM defines a few extra synchronization operations in terms of
  1517. things we have already covered. In particular, rcu_dereference() is
  1518. treated as READ_ONCE() and rcu_assign_pointer() is treated as
  1519. smp_store_release() -- which is basically how the Linux kernel treats
  1520. them.
  1521. There are a few oddball fences which need special treatment:
  1522. smp_mb__before_atomic(), smp_mb__after_atomic(), and
  1523. smp_mb__after_spinlock(). The LKMM uses fence events with special
  1524. annotations for them; they act as strong fences just like smp_mb()
  1525. except for the sets of events that they order. Instead of ordering
  1526. all po-earlier events against all po-later events, as smp_mb() does,
  1527. they behave as follows:
  1528. smp_mb__before_atomic() orders all po-earlier events against
  1529. po-later atomic updates and the events following them;
  1530. smp_mb__after_atomic() orders po-earlier atomic updates and
  1531. the events preceding them against all po-later events;
  1532. smp_mb_after_spinlock() orders po-earlier lock acquisition
  1533. events and the events preceding them against all po-later
  1534. events.
  1535. Interestingly, RCU and locking each introduce the possibility of
  1536. deadlock. When faced with code sequences such as:
  1537. spin_lock(&s);
  1538. spin_lock(&s);
  1539. spin_unlock(&s);
  1540. spin_unlock(&s);
  1541. or:
  1542. rcu_read_lock();
  1543. synchronize_rcu();
  1544. rcu_read_unlock();
  1545. what does the LKMM have to say? Answer: It says there are no allowed
  1546. executions at all, which makes sense. But this can also lead to
  1547. misleading results, because if a piece of code has multiple possible
  1548. executions, some of which deadlock, the model will report only on the
  1549. non-deadlocking executions. For example:
  1550. int x, y;
  1551. P0()
  1552. {
  1553. int r0;
  1554. WRITE_ONCE(x, 1);
  1555. r0 = READ_ONCE(y);
  1556. }
  1557. P1()
  1558. {
  1559. rcu_read_lock();
  1560. if (READ_ONCE(x) > 0) {
  1561. WRITE_ONCE(y, 36);
  1562. synchronize_rcu();
  1563. }
  1564. rcu_read_unlock();
  1565. }
  1566. Is it possible to end up with r0 = 36 at the end? The LKMM will tell
  1567. you it is not, but the model won't mention that this is because P1
  1568. will self-deadlock in the executions where it stores 36 in y.