explanation.txt 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616
  1. Explanation of the Linux-Kernel Memory Consistency Model
  2. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3. :Author: Alan Stern <[email protected]>
  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, rcu-gp, rcu-rscsi, rcu-order, rcu-fence, and rb
  28. 23. LOCKING
  29. 24. PLAIN ACCESSES AND DATA RACES
  30. 25. ODDS AND ENDS
  31. INTRODUCTION
  32. ------------
  33. The Linux-kernel memory consistency model (LKMM) is rather complex and
  34. obscure. This is particularly evident if you read through the
  35. linux-kernel.bell and linux-kernel.cat files that make up the formal
  36. version of the model; they are extremely terse and their meanings are
  37. far from clear.
  38. This document describes the ideas underlying the LKMM. It is meant
  39. for people who want to understand how the model was designed. It does
  40. not go into the details of the code in the .bell and .cat files;
  41. rather, it explains in English what the code expresses symbolically.
  42. Sections 2 (BACKGROUND) through 5 (ORDERING AND CYCLES) are aimed
  43. toward beginners; they explain what memory consistency models are and
  44. the basic notions shared by all such models. People already familiar
  45. with these concepts can skim or skip over them. Sections 6 (EVENTS)
  46. through 12 (THE FROM_READS RELATION) describe the fundamental
  47. relations used in many models. Starting in Section 13 (AN OPERATIONAL
  48. MODEL), the workings of the LKMM itself are covered.
  49. Warning: The code examples in this document are not written in the
  50. proper format for litmus tests. They don't include a header line, the
  51. initializations are not enclosed in braces, the global variables are
  52. not passed by pointers, and they don't have an "exists" clause at the
  53. end. Converting them to the right format is left as an exercise for
  54. the reader.
  55. BACKGROUND
  56. ----------
  57. A memory consistency model (or just memory model, for short) is
  58. something which predicts, given a piece of computer code running on a
  59. particular kind of system, what values may be obtained by the code's
  60. load instructions. The LKMM makes these predictions for code running
  61. as part of the Linux kernel.
  62. In practice, people tend to use memory models the other way around.
  63. That is, given a piece of code and a collection of values specified
  64. for the loads, the model will predict whether it is possible for the
  65. code to run in such a way that the loads will indeed obtain the
  66. specified values. Of course, this is just another way of expressing
  67. the same idea.
  68. For code running on a uniprocessor system, the predictions are easy:
  69. Each load instruction must obtain the value written by the most recent
  70. store instruction accessing the same location (we ignore complicating
  71. factors such as DMA and mixed-size accesses.) But on multiprocessor
  72. systems, with multiple CPUs making concurrent accesses to shared
  73. memory locations, things aren't so simple.
  74. Different architectures have differing memory models, and the Linux
  75. kernel supports a variety of architectures. The LKMM has to be fairly
  76. permissive, in the sense that any behavior allowed by one of these
  77. architectures also has to be allowed by the LKMM.
  78. A SIMPLE EXAMPLE
  79. ----------------
  80. Here is a simple example to illustrate the basic concepts. Consider
  81. some code running as part of a device driver for an input device. The
  82. driver might contain an interrupt handler which collects data from the
  83. device, stores it in a buffer, and sets a flag to indicate the buffer
  84. is full. Running concurrently on a different CPU might be a part of
  85. the driver code being executed by a process in the midst of a read(2)
  86. system call. This code tests the flag to see whether the buffer is
  87. ready, and if it is, copies the data back to userspace. The buffer
  88. and the flag are memory locations shared between the two CPUs.
  89. We can abstract out the important pieces of the driver code as follows
  90. (the reason for using WRITE_ONCE() and READ_ONCE() instead of simple
  91. assignment statements is discussed later):
  92. int buf = 0, flag = 0;
  93. P0()
  94. {
  95. WRITE_ONCE(buf, 1);
  96. WRITE_ONCE(flag, 1);
  97. }
  98. P1()
  99. {
  100. int r1;
  101. int r2 = 0;
  102. r1 = READ_ONCE(flag);
  103. if (r1)
  104. r2 = READ_ONCE(buf);
  105. }
  106. Here the P0() function represents the interrupt handler running on one
  107. CPU and P1() represents the read() routine running on another. The
  108. value 1 stored in buf represents input data collected from the device.
  109. Thus, P0 stores the data in buf and then sets flag. Meanwhile, P1
  110. reads flag into the private variable r1, and if it is set, reads the
  111. data from buf into a second private variable r2 for copying to
  112. userspace. (Presumably if flag is not set then the driver will wait a
  113. while and try again.)
  114. This pattern of memory accesses, where one CPU stores values to two
  115. shared memory locations and another CPU loads from those locations in
  116. the opposite order, is widely known as the "Message Passing" or MP
  117. pattern. It is typical of memory access patterns in the kernel.
  118. Please note that this example code is a simplified abstraction. Real
  119. buffers are usually larger than a single integer, real device drivers
  120. usually use sleep and wakeup mechanisms rather than polling for I/O
  121. completion, and real code generally doesn't bother to copy values into
  122. private variables before using them. All that is beside the point;
  123. the idea here is simply to illustrate the overall pattern of memory
  124. accesses by the CPUs.
  125. A memory model will predict what values P1 might obtain for its loads
  126. from flag and buf, or equivalently, what values r1 and r2 might end up
  127. with after the code has finished running.
  128. Some predictions are trivial. For instance, no sane memory model would
  129. predict that r1 = 42 or r2 = -7, because neither of those values ever
  130. gets stored in flag or buf.
  131. Some nontrivial predictions are nonetheless quite simple. For
  132. instance, P1 might run entirely before P0 begins, in which case r1 and
  133. r2 will both be 0 at the end. Or P0 might run entirely before P1
  134. begins, in which case r1 and r2 will both be 1.
  135. The interesting predictions concern what might happen when the two
  136. routines run concurrently. One possibility is that P1 runs after P0's
  137. store to buf but before the store to flag. In this case, r1 and r2
  138. will again both be 0. (If P1 had been designed to read buf
  139. unconditionally then we would instead have r1 = 0 and r2 = 1.)
  140. However, the most interesting possibility is where r1 = 1 and r2 = 0.
  141. If this were to occur it would mean the driver contains a bug, because
  142. incorrect data would get sent to the user: 0 instead of 1. As it
  143. happens, the LKMM does predict this outcome can occur, and the example
  144. driver code shown above is indeed buggy.
  145. A SELECTION OF MEMORY MODELS
  146. ----------------------------
  147. The first widely cited memory model, and the simplest to understand,
  148. is Sequential Consistency. According to this model, systems behave as
  149. if each CPU executed its instructions in order but with unspecified
  150. timing. In other words, the instructions from the various CPUs get
  151. interleaved in a nondeterministic way, always according to some single
  152. global order that agrees with the order of the instructions in the
  153. program source for each CPU. The model says that the value obtained
  154. by each load is simply the value written by the most recently executed
  155. store to the same memory location, from any CPU.
  156. For the MP example code shown above, Sequential Consistency predicts
  157. that the undesired result r1 = 1, r2 = 0 cannot occur. The reasoning
  158. goes like this:
  159. Since r1 = 1, P0 must store 1 to flag before P1 loads 1 from
  160. it, as loads can obtain values only from earlier stores.
  161. P1 loads from flag before loading from buf, since CPUs execute
  162. their instructions in order.
  163. P1 must load 0 from buf before P0 stores 1 to it; otherwise r2
  164. would be 1 since a load obtains its value from the most recent
  165. store to the same address.
  166. P0 stores 1 to buf before storing 1 to flag, since it executes
  167. its instructions in order.
  168. Since an instruction (in this case, P0's store to flag) cannot
  169. execute before itself, the specified outcome is impossible.
  170. However, real computer hardware almost never follows the Sequential
  171. Consistency memory model; doing so would rule out too many valuable
  172. performance optimizations. On ARM and PowerPC architectures, for
  173. instance, the MP example code really does sometimes yield r1 = 1 and
  174. r2 = 0.
  175. x86 and SPARC follow yet a different memory model: TSO (Total Store
  176. Ordering). This model predicts that the undesired outcome for the MP
  177. pattern cannot occur, but in other respects it differs from Sequential
  178. Consistency. One example is the Store Buffer (SB) pattern, in which
  179. each CPU stores to its own shared location and then loads from the
  180. other CPU's location:
  181. int x = 0, y = 0;
  182. P0()
  183. {
  184. int r0;
  185. WRITE_ONCE(x, 1);
  186. r0 = READ_ONCE(y);
  187. }
  188. P1()
  189. {
  190. int r1;
  191. WRITE_ONCE(y, 1);
  192. r1 = READ_ONCE(x);
  193. }
  194. Sequential Consistency predicts that the outcome r0 = 0, r1 = 0 is
  195. impossible. (Exercise: Figure out the reasoning.) But TSO allows
  196. this outcome to occur, and in fact it does sometimes occur on x86 and
  197. SPARC systems.
  198. The LKMM was inspired by the memory models followed by PowerPC, ARM,
  199. x86, Alpha, and other architectures. However, it is different in
  200. detail from each of them.
  201. ORDERING AND CYCLES
  202. -------------------
  203. Memory models are all about ordering. Often this is temporal ordering
  204. (i.e., the order in which certain events occur) but it doesn't have to
  205. be; consider for example the order of instructions in a program's
  206. source code. We saw above that Sequential Consistency makes an
  207. important assumption that CPUs execute instructions in the same order
  208. as those instructions occur in the code, and there are many other
  209. instances of ordering playing central roles in memory models.
  210. The counterpart to ordering is a cycle. Ordering rules out cycles:
  211. It's not possible to have X ordered before Y, Y ordered before Z, and
  212. Z ordered before X, because this would mean that X is ordered before
  213. itself. The analysis of the MP example under Sequential Consistency
  214. involved just such an impossible cycle:
  215. W: P0 stores 1 to flag executes before
  216. X: P1 loads 1 from flag executes before
  217. Y: P1 loads 0 from buf executes before
  218. Z: P0 stores 1 to buf executes before
  219. W: P0 stores 1 to flag.
  220. In short, if a memory model requires certain accesses to be ordered,
  221. and a certain outcome for the loads in a piece of code can happen only
  222. if those accesses would form a cycle, then the memory model predicts
  223. that outcome cannot occur.
  224. The LKMM is defined largely in terms of cycles, as we will see.
  225. EVENTS
  226. ------
  227. The LKMM does not work directly with the C statements that make up
  228. kernel source code. Instead it considers the effects of those
  229. statements in a more abstract form, namely, events. The model
  230. includes three types of events:
  231. Read events correspond to loads from shared memory, such as
  232. calls to READ_ONCE(), smp_load_acquire(), or
  233. rcu_dereference().
  234. Write events correspond to stores to shared memory, such as
  235. calls to WRITE_ONCE(), smp_store_release(), or atomic_set().
  236. Fence events correspond to memory barriers (also known as
  237. fences), such as calls to smp_rmb() or rcu_read_lock().
  238. These categories are not exclusive; a read or write event can also be
  239. a fence. This happens with functions like smp_load_acquire() or
  240. spin_lock(). However, no single event can be both a read and a write.
  241. Atomic read-modify-write accesses, such as atomic_inc() or xchg(),
  242. correspond to a pair of events: a read followed by a write. (The
  243. write event is omitted for executions where it doesn't occur, such as
  244. a cmpxchg() where the comparison fails.)
  245. Other parts of the code, those which do not involve interaction with
  246. shared memory, do not give rise to events. Thus, arithmetic and
  247. logical computations, control-flow instructions, or accesses to
  248. private memory or CPU registers are not of central interest to the
  249. memory model. They only affect the model's predictions indirectly.
  250. For example, an arithmetic computation might determine the value that
  251. gets stored to a shared memory location (or in the case of an array
  252. index, the address where the value gets stored), but the memory model
  253. is concerned only with the store itself -- its value and its address
  254. -- not the computation leading up to it.
  255. Events in the LKMM can be linked by various relations, which we will
  256. describe in the following sections. The memory model requires certain
  257. of these relations to be orderings, that is, it requires them not to
  258. have any cycles.
  259. THE PROGRAM ORDER RELATION: po AND po-loc
  260. -----------------------------------------
  261. The most important relation between events is program order (po). You
  262. can think of it as the order in which statements occur in the source
  263. code after branches are taken into account and loops have been
  264. unrolled. A better description might be the order in which
  265. instructions are presented to a CPU's execution unit. Thus, we say
  266. that X is po-before Y (written as "X ->po Y" in formulas) if X occurs
  267. before Y in the instruction stream.
  268. This is inherently a single-CPU relation; two instructions executing
  269. on different CPUs are never linked by po. Also, it is by definition
  270. an ordering so it cannot have any cycles.
  271. po-loc is a sub-relation of po. It links two memory accesses when the
  272. first comes before the second in program order and they access the
  273. same memory location (the "-loc" suffix).
  274. Although this may seem straightforward, there is one subtle aspect to
  275. program order we need to explain. The LKMM was inspired by low-level
  276. architectural memory models which describe the behavior of machine
  277. code, and it retains their outlook to a considerable extent. The
  278. read, write, and fence events used by the model are close in spirit to
  279. individual machine instructions. Nevertheless, the LKMM describes
  280. kernel code written in C, and the mapping from C to machine code can
  281. be extremely complex.
  282. Optimizing compilers have great freedom in the way they translate
  283. source code to object code. They are allowed to apply transformations
  284. that add memory accesses, eliminate accesses, combine them, split them
  285. into pieces, or move them around. The use of READ_ONCE(), WRITE_ONCE(),
  286. or one of the other atomic or synchronization primitives prevents a
  287. large number of compiler optimizations. In particular, it is guaranteed
  288. that the compiler will not remove such accesses from the generated code
  289. (unless it can prove the accesses will never be executed), it will not
  290. change the order in which they occur in the code (within limits imposed
  291. by the C standard), and it will not introduce extraneous accesses.
  292. The MP and SB examples above used READ_ONCE() and WRITE_ONCE() rather
  293. than ordinary memory accesses. Thanks to this usage, we can be certain
  294. that in the MP example, the compiler won't reorder P0's write event to
  295. buf and P0's write event to flag, and similarly for the other shared
  296. memory accesses in the examples.
  297. Since private variables are not shared between CPUs, they can be
  298. accessed normally without READ_ONCE() or WRITE_ONCE(). In fact, they
  299. need not even be stored in normal memory at all -- in principle a
  300. private variable could be stored in a CPU register (hence the convention
  301. that these variables have names starting with the letter 'r').
  302. A WARNING
  303. ---------
  304. The protections provided by READ_ONCE(), WRITE_ONCE(), and others are
  305. not perfect; and under some circumstances it is possible for the
  306. compiler to undermine the memory model. Here is an example. Suppose
  307. both branches of an "if" statement store the same value to the same
  308. location:
  309. r1 = READ_ONCE(x);
  310. if (r1) {
  311. WRITE_ONCE(y, 2);
  312. ... /* do something */
  313. } else {
  314. WRITE_ONCE(y, 2);
  315. ... /* do something else */
  316. }
  317. For this code, the LKMM predicts that the load from x will always be
  318. executed before either of the stores to y. However, a compiler could
  319. lift the stores out of the conditional, transforming the code into
  320. something resembling:
  321. r1 = READ_ONCE(x);
  322. WRITE_ONCE(y, 2);
  323. if (r1) {
  324. ... /* do something */
  325. } else {
  326. ... /* do something else */
  327. }
  328. Given this version of the code, the LKMM would predict that the load
  329. from x could be executed after the store to y. Thus, the memory
  330. model's original prediction could be invalidated by the compiler.
  331. Another issue arises from the fact that in C, arguments to many
  332. operators and function calls can be evaluated in any order. For
  333. example:
  334. r1 = f(5) + g(6);
  335. The object code might call f(5) either before or after g(6); the
  336. memory model cannot assume there is a fixed program order relation
  337. between them. (In fact, if the function calls are inlined then the
  338. compiler might even interleave their object code.)
  339. DEPENDENCY RELATIONS: data, addr, and ctrl
  340. ------------------------------------------
  341. We say that two events are linked by a dependency relation when the
  342. execution of the second event depends in some way on a value obtained
  343. from memory by the first. The first event must be a read, and the
  344. value it obtains must somehow affect what the second event does.
  345. There are three kinds of dependencies: data, address (addr), and
  346. control (ctrl).
  347. A read and a write event are linked by a data dependency if the value
  348. obtained by the read affects the value stored by the write. As a very
  349. simple example:
  350. int x, y;
  351. r1 = READ_ONCE(x);
  352. WRITE_ONCE(y, r1 + 5);
  353. The value stored by the WRITE_ONCE obviously depends on the value
  354. loaded by the READ_ONCE. Such dependencies can wind through
  355. arbitrarily complicated computations, and a write can depend on the
  356. values of multiple reads.
  357. A read event and another memory access event are linked by an address
  358. dependency if the value obtained by the read affects the location
  359. accessed by the other event. The second event can be either a read or
  360. a write. Here's another simple example:
  361. int a[20];
  362. int i;
  363. r1 = READ_ONCE(i);
  364. r2 = READ_ONCE(a[r1]);
  365. Here the location accessed by the second READ_ONCE() depends on the
  366. index value loaded by the first. Pointer indirection also gives rise
  367. to address dependencies, since the address of a location accessed
  368. through a pointer will depend on the value read earlier from that
  369. pointer.
  370. Finally, a read event and another memory access event are linked by a
  371. control dependency if the value obtained by the read affects whether
  372. the second event is executed at all. Simple example:
  373. int x, y;
  374. r1 = READ_ONCE(x);
  375. if (r1)
  376. WRITE_ONCE(y, 1984);
  377. Execution of the WRITE_ONCE() is controlled by a conditional expression
  378. which depends on the value obtained by the READ_ONCE(); hence there is
  379. a control dependency from the load to the store.
  380. It should be pretty obvious that events can only depend on reads that
  381. come earlier in program order. Symbolically, if we have R ->data X,
  382. R ->addr X, or R ->ctrl X (where R is a read event), then we must also
  383. have R ->po X. It wouldn't make sense for a computation to depend
  384. somehow on a value that doesn't get loaded from shared memory until
  385. later in the code!
  386. Here's a trick question: When is a dependency not a dependency? Answer:
  387. When it is purely syntactic rather than semantic. We say a dependency
  388. between two accesses is purely syntactic if the second access doesn't
  389. actually depend on the result of the first. Here is a trivial example:
  390. r1 = READ_ONCE(x);
  391. WRITE_ONCE(y, r1 * 0);
  392. There appears to be a data dependency from the load of x to the store
  393. of y, since the value to be stored is computed from the value that was
  394. loaded. But in fact, the value stored does not really depend on
  395. anything since it will always be 0. Thus the data dependency is only
  396. syntactic (it appears to exist in the code) but not semantic (the
  397. second access will always be the same, regardless of the value of the
  398. first access). Given code like this, a compiler could simply discard
  399. the value returned by the load from x, which would certainly destroy
  400. any dependency. (The compiler is not permitted to eliminate entirely
  401. the load generated for a READ_ONCE() -- that's one of the nice
  402. properties of READ_ONCE() -- but it is allowed to ignore the load's
  403. value.)
  404. It's natural to object that no one in their right mind would write
  405. code like the above. However, macro expansions can easily give rise
  406. to this sort of thing, in ways that often are not apparent to the
  407. programmer.
  408. Another mechanism that can lead to purely syntactic dependencies is
  409. related to the notion of "undefined behavior". Certain program
  410. behaviors are called "undefined" in the C language specification,
  411. which means that when they occur there are no guarantees at all about
  412. the outcome. Consider the following example:
  413. int a[1];
  414. int i;
  415. r1 = READ_ONCE(i);
  416. r2 = READ_ONCE(a[r1]);
  417. Access beyond the end or before the beginning of an array is one kind
  418. of undefined behavior. Therefore the compiler doesn't have to worry
  419. about what will happen if r1 is nonzero, and it can assume that r1
  420. will always be zero regardless of the value actually loaded from i.
  421. (If the assumption turns out to be wrong the resulting behavior will
  422. be undefined anyway, so the compiler doesn't care!) Thus the value
  423. from the load can be discarded, breaking the address dependency.
  424. The LKMM is unaware that purely syntactic dependencies are different
  425. from semantic dependencies and therefore mistakenly predicts that the
  426. accesses in the two examples above will be ordered. This is another
  427. example of how the compiler can undermine the memory model. Be warned.
  428. THE READS-FROM RELATION: rf, rfi, and rfe
  429. -----------------------------------------
  430. The reads-from relation (rf) links a write event to a read event when
  431. the value loaded by the read is the value that was stored by the
  432. write. In colloquial terms, the load "reads from" the store. We
  433. write W ->rf R to indicate that the load R reads from the store W. We
  434. further distinguish the cases where the load and the store occur on
  435. the same CPU (internal reads-from, or rfi) and where they occur on
  436. different CPUs (external reads-from, or rfe).
  437. For our purposes, a memory location's initial value is treated as
  438. though it had been written there by an imaginary initial store that
  439. executes on a separate CPU before the main program runs.
  440. Usage of the rf relation implicitly assumes that loads will always
  441. read from a single store. It doesn't apply properly in the presence
  442. of load-tearing, where a load obtains some of its bits from one store
  443. and some of them from another store. Fortunately, use of READ_ONCE()
  444. and WRITE_ONCE() will prevent load-tearing; it's not possible to have:
  445. int x = 0;
  446. P0()
  447. {
  448. WRITE_ONCE(x, 0x1234);
  449. }
  450. P1()
  451. {
  452. int r1;
  453. r1 = READ_ONCE(x);
  454. }
  455. and end up with r1 = 0x1200 (partly from x's initial value and partly
  456. from the value stored by P0).
  457. On the other hand, load-tearing is unavoidable when mixed-size
  458. accesses are used. Consider this example:
  459. union {
  460. u32 w;
  461. u16 h[2];
  462. } x;
  463. P0()
  464. {
  465. WRITE_ONCE(x.h[0], 0x1234);
  466. WRITE_ONCE(x.h[1], 0x5678);
  467. }
  468. P1()
  469. {
  470. int r1;
  471. r1 = READ_ONCE(x.w);
  472. }
  473. If r1 = 0x56781234 (little-endian!) at the end, then P1 must have read
  474. from both of P0's stores. It is possible to handle mixed-size and
  475. unaligned accesses in a memory model, but the LKMM currently does not
  476. attempt to do so. It requires all accesses to be properly aligned and
  477. of the location's actual size.
  478. CACHE COHERENCE AND THE COHERENCE ORDER RELATION: co, coi, and coe
  479. ------------------------------------------------------------------
  480. Cache coherence is a general principle requiring that in a
  481. multi-processor system, the CPUs must share a consistent view of the
  482. memory contents. Specifically, it requires that for each location in
  483. shared memory, the stores to that location must form a single global
  484. ordering which all the CPUs agree on (the coherence order), and this
  485. ordering must be consistent with the program order for accesses to
  486. that location.
  487. To put it another way, for any variable x, the coherence order (co) of
  488. the stores to x is simply the order in which the stores overwrite one
  489. another. The imaginary store which establishes x's initial value
  490. comes first in the coherence order; the store which directly
  491. overwrites the initial value comes second; the store which overwrites
  492. that value comes third, and so on.
  493. You can think of the coherence order as being the order in which the
  494. stores reach x's location in memory (or if you prefer a more
  495. hardware-centric view, the order in which the stores get written to
  496. x's cache line). We write W ->co W' if W comes before W' in the
  497. coherence order, that is, if the value stored by W gets overwritten,
  498. directly or indirectly, by the value stored by W'.
  499. Coherence order is required to be consistent with program order. This
  500. requirement takes the form of four coherency rules:
  501. Write-write coherence: If W ->po-loc W' (i.e., W comes before
  502. W' in program order and they access the same location), where W
  503. and W' are two stores, then W ->co W'.
  504. Write-read coherence: If W ->po-loc R, where W is a store and R
  505. is a load, then R must read from W or from some other store
  506. which comes after W in the coherence order.
  507. Read-write coherence: If R ->po-loc W, where R is a load and W
  508. is a store, then the store which R reads from must come before
  509. W in the coherence order.
  510. Read-read coherence: If R ->po-loc R', where R and R' are two
  511. loads, then either they read from the same store or else the
  512. store read by R comes before the store read by R' in the
  513. coherence order.
  514. This is sometimes referred to as sequential consistency per variable,
  515. because it means that the accesses to any single memory location obey
  516. the rules of the Sequential Consistency memory model. (According to
  517. Wikipedia, sequential consistency per variable and cache coherence
  518. mean the same thing except that cache coherence includes an extra
  519. requirement that every store eventually becomes visible to every CPU.)
  520. Any reasonable memory model will include cache coherence. Indeed, our
  521. expectation of cache coherence is so deeply ingrained that violations
  522. of its requirements look more like hardware bugs than programming
  523. errors:
  524. int x;
  525. P0()
  526. {
  527. WRITE_ONCE(x, 17);
  528. WRITE_ONCE(x, 23);
  529. }
  530. If the final value stored in x after this code ran was 17, you would
  531. think your computer was broken. It would be a violation of the
  532. write-write coherence rule: Since the store of 23 comes later in
  533. program order, it must also come later in x's coherence order and
  534. thus must overwrite the store of 17.
  535. int x = 0;
  536. P0()
  537. {
  538. int r1;
  539. r1 = READ_ONCE(x);
  540. WRITE_ONCE(x, 666);
  541. }
  542. If r1 = 666 at the end, this would violate the read-write coherence
  543. rule: The READ_ONCE() load comes before the WRITE_ONCE() store in
  544. program order, so it must not read from that store but rather from one
  545. coming earlier in the coherence order (in this case, x's initial
  546. value).
  547. int x = 0;
  548. P0()
  549. {
  550. WRITE_ONCE(x, 5);
  551. }
  552. P1()
  553. {
  554. int r1, r2;
  555. r1 = READ_ONCE(x);
  556. r2 = READ_ONCE(x);
  557. }
  558. If r1 = 5 (reading from P0's store) and r2 = 0 (reading from the
  559. imaginary store which establishes x's initial value) at the end, this
  560. would violate the read-read coherence rule: The r1 load comes before
  561. the r2 load in program order, so it must not read from a store that
  562. comes later in the coherence order.
  563. (As a minor curiosity, if this code had used normal loads instead of
  564. READ_ONCE() in P1, on Itanium it sometimes could end up with r1 = 5
  565. and r2 = 0! This results from parallel execution of the operations
  566. encoded in Itanium's Very-Long-Instruction-Word format, and it is yet
  567. another motivation for using READ_ONCE() when accessing shared memory
  568. locations.)
  569. Just like the po relation, co is inherently an ordering -- it is not
  570. possible for a store to directly or indirectly overwrite itself! And
  571. just like with the rf relation, we distinguish between stores that
  572. occur on the same CPU (internal coherence order, or coi) and stores
  573. that occur on different CPUs (external coherence order, or coe).
  574. On the other hand, stores to different memory locations are never
  575. related by co, just as instructions on different CPUs are never
  576. related by po. Coherence order is strictly per-location, or if you
  577. prefer, each location has its own independent coherence order.
  578. THE FROM-READS RELATION: fr, fri, and fre
  579. -----------------------------------------
  580. The from-reads relation (fr) can be a little difficult for people to
  581. grok. It describes the situation where a load reads a value that gets
  582. overwritten by a store. In other words, we have R ->fr W when the
  583. value that R reads is overwritten (directly or indirectly) by W, or
  584. equivalently, when R reads from a store which comes earlier than W in
  585. the coherence order.
  586. For example:
  587. int x = 0;
  588. P0()
  589. {
  590. int r1;
  591. r1 = READ_ONCE(x);
  592. WRITE_ONCE(x, 2);
  593. }
  594. The value loaded from x will be 0 (assuming cache coherence!), and it
  595. gets overwritten by the value 2. Thus there is an fr link from the
  596. READ_ONCE() to the WRITE_ONCE(). If the code contained any later
  597. stores to x, there would also be fr links from the READ_ONCE() to
  598. them.
  599. As with rf, rfi, and rfe, we subdivide the fr relation into fri (when
  600. the load and the store are on the same CPU) and fre (when they are on
  601. different CPUs).
  602. Note that the fr relation is determined entirely by the rf and co
  603. relations; it is not independent. Given a read event R and a write
  604. event W for the same location, we will have R ->fr W if and only if
  605. the write which R reads from is co-before W. In symbols,
  606. (R ->fr W) := (there exists W' with W' ->rf R and W' ->co W).
  607. AN OPERATIONAL MODEL
  608. --------------------
  609. The LKMM is based on various operational memory models, meaning that
  610. the models arise from an abstract view of how a computer system
  611. operates. Here are the main ideas, as incorporated into the LKMM.
  612. The system as a whole is divided into the CPUs and a memory subsystem.
  613. The CPUs are responsible for executing instructions (not necessarily
  614. in program order), and they communicate with the memory subsystem.
  615. For the most part, executing an instruction requires a CPU to perform
  616. only internal operations. However, loads, stores, and fences involve
  617. more.
  618. When CPU C executes a store instruction, it tells the memory subsystem
  619. to store a certain value at a certain location. The memory subsystem
  620. propagates the store to all the other CPUs as well as to RAM. (As a
  621. special case, we say that the store propagates to its own CPU at the
  622. time it is executed.) The memory subsystem also determines where the
  623. store falls in the location's coherence order. In particular, it must
  624. arrange for the store to be co-later than (i.e., to overwrite) any
  625. other store to the same location which has already propagated to CPU C.
  626. When a CPU executes a load instruction R, it first checks to see
  627. whether there are any as-yet unexecuted store instructions, for the
  628. same location, that come before R in program order. If there are, it
  629. uses the value of the po-latest such store as the value obtained by R,
  630. and we say that the store's value is forwarded to R. Otherwise, the
  631. CPU asks the memory subsystem for the value to load and we say that R
  632. is satisfied from memory. The memory subsystem hands back the value
  633. of the co-latest store to the location in question which has already
  634. propagated to that CPU.
  635. (In fact, the picture needs to be a little more complicated than this.
  636. CPUs have local caches, and propagating a store to a CPU really means
  637. propagating it to the CPU's local cache. A local cache can take some
  638. time to process the stores that it receives, and a store can't be used
  639. to satisfy one of the CPU's loads until it has been processed. On
  640. most architectures, the local caches process stores in
  641. First-In-First-Out order, and consequently the processing delay
  642. doesn't matter for the memory model. But on Alpha, the local caches
  643. have a partitioned design that results in non-FIFO behavior. We will
  644. discuss this in more detail later.)
  645. Note that load instructions may be executed speculatively and may be
  646. restarted under certain circumstances. The memory model ignores these
  647. premature executions; we simply say that the load executes at the
  648. final time it is forwarded or satisfied.
  649. Executing a fence (or memory barrier) instruction doesn't require a
  650. CPU to do anything special other than informing the memory subsystem
  651. about the fence. However, fences do constrain the way CPUs and the
  652. memory subsystem handle other instructions, in two respects.
  653. First, a fence forces the CPU to execute various instructions in
  654. program order. Exactly which instructions are ordered depends on the
  655. type of fence:
  656. Strong fences, including smp_mb() and synchronize_rcu(), force
  657. the CPU to execute all po-earlier instructions before any
  658. po-later instructions;
  659. smp_rmb() forces the CPU to execute all po-earlier loads
  660. before any po-later loads;
  661. smp_wmb() forces the CPU to execute all po-earlier stores
  662. before any po-later stores;
  663. Acquire fences, such as smp_load_acquire(), force the CPU to
  664. execute the load associated with the fence (e.g., the load
  665. part of an smp_load_acquire()) before any po-later
  666. instructions;
  667. Release fences, such as smp_store_release(), force the CPU to
  668. execute all po-earlier instructions before the store
  669. associated with the fence (e.g., the store part of an
  670. smp_store_release()).
  671. Second, some types of fence affect the way the memory subsystem
  672. propagates stores. When a fence instruction is executed on CPU C:
  673. For each other CPU C', smp_wmb() forces all po-earlier stores
  674. on C to propagate to C' before any po-later stores do.
  675. For each other CPU C', any store which propagates to C before
  676. a release fence is executed (including all po-earlier
  677. stores executed on C) is forced to propagate to C' before the
  678. store associated with the release fence does.
  679. Any store which propagates to C before a strong fence is
  680. executed (including all po-earlier stores on C) is forced to
  681. propagate to all other CPUs before any instructions po-after
  682. the strong fence are executed on C.
  683. The propagation ordering enforced by release fences and strong fences
  684. affects stores from other CPUs that propagate to CPU C before the
  685. fence is executed, as well as stores that are executed on C before the
  686. fence. We describe this property by saying that release fences and
  687. strong fences are A-cumulative. By contrast, smp_wmb() fences are not
  688. A-cumulative; they only affect the propagation of stores that are
  689. executed on C before the fence (i.e., those which precede the fence in
  690. program order).
  691. rcu_read_lock(), rcu_read_unlock(), and synchronize_rcu() fences have
  692. other properties which we discuss later.
  693. PROPAGATION ORDER RELATION: cumul-fence
  694. ---------------------------------------
  695. The fences which affect propagation order (i.e., strong, release, and
  696. smp_wmb() fences) are collectively referred to as cumul-fences, even
  697. though smp_wmb() isn't A-cumulative. The cumul-fence relation is
  698. defined to link memory access events E and F whenever:
  699. E and F are both stores on the same CPU and an smp_wmb() fence
  700. event occurs between them in program order; or
  701. F is a release fence and some X comes before F in program order,
  702. where either X = E or else E ->rf X; or
  703. A strong fence event occurs between some X and F in program
  704. order, where either X = E or else E ->rf X.
  705. The operational model requires that whenever W and W' are both stores
  706. and W ->cumul-fence W', then W must propagate to any given CPU
  707. before W' does. However, for different CPUs C and C', it does not
  708. require W to propagate to C before W' propagates to C'.
  709. DERIVATION OF THE LKMM FROM THE OPERATIONAL MODEL
  710. -------------------------------------------------
  711. The LKMM is derived from the restrictions imposed by the design
  712. outlined above. These restrictions involve the necessity of
  713. maintaining cache coherence and the fact that a CPU can't operate on a
  714. value before it knows what that value is, among other things.
  715. The formal version of the LKMM is defined by six requirements, or
  716. axioms:
  717. Sequential consistency per variable: This requires that the
  718. system obey the four coherency rules.
  719. Atomicity: This requires that atomic read-modify-write
  720. operations really are atomic, that is, no other stores can
  721. sneak into the middle of such an update.
  722. Happens-before: This requires that certain instructions are
  723. executed in a specific order.
  724. Propagation: This requires that certain stores propagate to
  725. CPUs and to RAM in a specific order.
  726. Rcu: This requires that RCU read-side critical sections and
  727. grace periods obey the rules of RCU, in particular, the
  728. Grace-Period Guarantee.
  729. Plain-coherence: This requires that plain memory accesses
  730. (those not using READ_ONCE(), WRITE_ONCE(), etc.) must obey
  731. the operational model's rules regarding cache coherence.
  732. The first and second are quite common; they can be found in many
  733. memory models (such as those for C11/C++11). The "happens-before" and
  734. "propagation" axioms have analogs in other memory models as well. The
  735. "rcu" and "plain-coherence" axioms are specific to the LKMM.
  736. Each of these axioms is discussed below.
  737. SEQUENTIAL CONSISTENCY PER VARIABLE
  738. -----------------------------------
  739. According to the principle of cache coherence, the stores to any fixed
  740. shared location in memory form a global ordering. We can imagine
  741. inserting the loads from that location into this ordering, by placing
  742. each load between the store that it reads from and the following
  743. store. This leaves the relative positions of loads that read from the
  744. same store unspecified; let's say they are inserted in program order,
  745. first for CPU 0, then CPU 1, etc.
  746. You can check that the four coherency rules imply that the rf, co, fr,
  747. and po-loc relations agree with this global ordering; in other words,
  748. whenever we have X ->rf Y or X ->co Y or X ->fr Y or X ->po-loc Y, the
  749. X event comes before the Y event in the global ordering. The LKMM's
  750. "coherence" axiom expresses this by requiring the union of these
  751. relations not to have any cycles. This means it must not be possible
  752. to find events
  753. X0 -> X1 -> X2 -> ... -> Xn -> X0,
  754. where each of the links is either rf, co, fr, or po-loc. This has to
  755. hold if the accesses to the fixed memory location can be ordered as
  756. cache coherence demands.
  757. Although it is not obvious, it can be shown that the converse is also
  758. true: This LKMM axiom implies that the four coherency rules are
  759. obeyed.
  760. ATOMIC UPDATES: rmw
  761. -------------------
  762. What does it mean to say that a read-modify-write (rmw) update, such
  763. as atomic_inc(&x), is atomic? It means that the memory location (x in
  764. this case) does not get altered between the read and the write events
  765. making up the atomic operation. In particular, if two CPUs perform
  766. atomic_inc(&x) concurrently, it must be guaranteed that the final
  767. value of x will be the initial value plus two. We should never have
  768. the following sequence of events:
  769. CPU 0 loads x obtaining 13;
  770. CPU 1 loads x obtaining 13;
  771. CPU 0 stores 14 to x;
  772. CPU 1 stores 14 to x;
  773. where the final value of x is wrong (14 rather than 15).
  774. In this example, CPU 0's increment effectively gets lost because it
  775. occurs in between CPU 1's load and store. To put it another way, the
  776. problem is that the position of CPU 0's store in x's coherence order
  777. is between the store that CPU 1 reads from and the store that CPU 1
  778. performs.
  779. The same analysis applies to all atomic update operations. Therefore,
  780. to enforce atomicity the LKMM requires that atomic updates follow this
  781. rule: Whenever R and W are the read and write events composing an
  782. atomic read-modify-write and W' is the write event which R reads from,
  783. there must not be any stores coming between W' and W in the coherence
  784. order. Equivalently,
  785. (R ->rmw W) implies (there is no X with R ->fr X and X ->co W),
  786. where the rmw relation links the read and write events making up each
  787. atomic update. This is what the LKMM's "atomic" axiom says.
  788. THE PRESERVED PROGRAM ORDER RELATION: ppo
  789. -----------------------------------------
  790. There are many situations where a CPU is obliged to execute two
  791. instructions in program order. We amalgamate them into the ppo (for
  792. "preserved program order") relation, which links the po-earlier
  793. instruction to the po-later instruction and is thus a sub-relation of
  794. po.
  795. The operational model already includes a description of one such
  796. situation: Fences are a source of ppo links. Suppose X and Y are
  797. memory accesses with X ->po Y; then the CPU must execute X before Y if
  798. any of the following hold:
  799. A strong (smp_mb() or synchronize_rcu()) fence occurs between
  800. X and Y;
  801. X and Y are both stores and an smp_wmb() fence occurs between
  802. them;
  803. X and Y are both loads and an smp_rmb() fence occurs between
  804. them;
  805. X is also an acquire fence, such as smp_load_acquire();
  806. Y is also a release fence, such as smp_store_release().
  807. Another possibility, not mentioned earlier but discussed in the next
  808. section, is:
  809. X and Y are both loads, X ->addr Y (i.e., there is an address
  810. dependency from X to Y), and X is a READ_ONCE() or an atomic
  811. access.
  812. Dependencies can also cause instructions to be executed in program
  813. order. This is uncontroversial when the second instruction is a
  814. store; either a data, address, or control dependency from a load R to
  815. a store W will force the CPU to execute R before W. This is very
  816. simply because the CPU cannot tell the memory subsystem about W's
  817. store before it knows what value should be stored (in the case of a
  818. data dependency), what location it should be stored into (in the case
  819. of an address dependency), or whether the store should actually take
  820. place (in the case of a control dependency).
  821. Dependencies to load instructions are more problematic. To begin with,
  822. there is no such thing as a data dependency to a load. Next, a CPU
  823. has no reason to respect a control dependency to a load, because it
  824. can always satisfy the second load speculatively before the first, and
  825. then ignore the result if it turns out that the second load shouldn't
  826. be executed after all. And lastly, the real difficulties begin when
  827. we consider address dependencies to loads.
  828. To be fair about it, all Linux-supported architectures do execute
  829. loads in program order if there is an address dependency between them.
  830. After all, a CPU cannot ask the memory subsystem to load a value from
  831. a particular location before it knows what that location is. However,
  832. the split-cache design used by Alpha can cause it to behave in a way
  833. that looks as if the loads were executed out of order (see the next
  834. section for more details). The kernel includes a workaround for this
  835. problem when the loads come from READ_ONCE(), and therefore the LKMM
  836. includes address dependencies to loads in the ppo relation.
  837. On the other hand, dependencies can indirectly affect the ordering of
  838. two loads. This happens when there is a dependency from a load to a
  839. store and a second, po-later load reads from that store:
  840. R ->dep W ->rfi R',
  841. where the dep link can be either an address or a data dependency. In
  842. this situation we know it is possible for the CPU to execute R' before
  843. W, because it can forward the value that W will store to R'. But it
  844. cannot execute R' before R, because it cannot forward the value before
  845. it knows what that value is, or that W and R' do access the same
  846. location. However, if there is merely a control dependency between R
  847. and W then the CPU can speculatively forward W to R' before executing
  848. R; if the speculation turns out to be wrong then the CPU merely has to
  849. restart or abandon R'.
  850. (In theory, a CPU might forward a store to a load when it runs across
  851. an address dependency like this:
  852. r1 = READ_ONCE(ptr);
  853. WRITE_ONCE(*r1, 17);
  854. r2 = READ_ONCE(*r1);
  855. because it could tell that the store and the second load access the
  856. same location even before it knows what the location's address is.
  857. However, none of the architectures supported by the Linux kernel do
  858. this.)
  859. Two memory accesses of the same location must always be executed in
  860. program order if the second access is a store. Thus, if we have
  861. R ->po-loc W
  862. (the po-loc link says that R comes before W in program order and they
  863. access the same location), the CPU is obliged to execute W after R.
  864. If it executed W first then the memory subsystem would respond to R's
  865. read request with the value stored by W (or an even later store), in
  866. violation of the read-write coherence rule. Similarly, if we had
  867. W ->po-loc W'
  868. and the CPU executed W' before W, then the memory subsystem would put
  869. W' before W in the coherence order. It would effectively cause W to
  870. overwrite W', in violation of the write-write coherence rule.
  871. (Interestingly, an early ARMv8 memory model, now obsolete, proposed
  872. allowing out-of-order writes like this to occur. The model avoided
  873. violating the write-write coherence rule by requiring the CPU not to
  874. send the W write to the memory subsystem at all!)
  875. AND THEN THERE WAS ALPHA
  876. ------------------------
  877. As mentioned above, the Alpha architecture is unique in that it does
  878. not appear to respect address dependencies to loads. This means that
  879. code such as the following:
  880. int x = 0;
  881. int y = -1;
  882. int *ptr = &y;
  883. P0()
  884. {
  885. WRITE_ONCE(x, 1);
  886. smp_wmb();
  887. WRITE_ONCE(ptr, &x);
  888. }
  889. P1()
  890. {
  891. int *r1;
  892. int r2;
  893. r1 = ptr;
  894. r2 = READ_ONCE(*r1);
  895. }
  896. can malfunction on Alpha systems (notice that P1 uses an ordinary load
  897. to read ptr instead of READ_ONCE()). It is quite possible that r1 = &x
  898. and r2 = 0 at the end, in spite of the address dependency.
  899. At first glance this doesn't seem to make sense. We know that the
  900. smp_wmb() forces P0's store to x to propagate to P1 before the store
  901. to ptr does. And since P1 can't execute its second load
  902. until it knows what location to load from, i.e., after executing its
  903. first load, the value x = 1 must have propagated to P1 before the
  904. second load executed. So why doesn't r2 end up equal to 1?
  905. The answer lies in the Alpha's split local caches. Although the two
  906. stores do reach P1's local cache in the proper order, it can happen
  907. that the first store is processed by a busy part of the cache while
  908. the second store is processed by an idle part. As a result, the x = 1
  909. value may not become available for P1's CPU to read until after the
  910. ptr = &x value does, leading to the undesirable result above. The
  911. final effect is that even though the two loads really are executed in
  912. program order, it appears that they aren't.
  913. This could not have happened if the local cache had processed the
  914. incoming stores in FIFO order. By contrast, other architectures
  915. maintain at least the appearance of FIFO order.
  916. In practice, this difficulty is solved by inserting a special fence
  917. between P1's two loads when the kernel is compiled for the Alpha
  918. architecture. In fact, as of version 4.15, the kernel automatically
  919. adds this fence after every READ_ONCE() and atomic load on Alpha. The
  920. effect of the fence is to cause the CPU not to execute any po-later
  921. instructions until after the local cache has finished processing all
  922. the stores it has already received. Thus, if the code was changed to:
  923. P1()
  924. {
  925. int *r1;
  926. int r2;
  927. r1 = READ_ONCE(ptr);
  928. r2 = READ_ONCE(*r1);
  929. }
  930. then we would never get r1 = &x and r2 = 0. By the time P1 executed
  931. its second load, the x = 1 store would already be fully processed by
  932. the local cache and available for satisfying the read request. Thus
  933. we have yet another reason why shared data should always be read with
  934. READ_ONCE() or another synchronization primitive rather than accessed
  935. directly.
  936. The LKMM requires that smp_rmb(), acquire fences, and strong fences
  937. share this property: They do not allow the CPU to execute any po-later
  938. instructions (or po-later loads in the case of smp_rmb()) until all
  939. outstanding stores have been processed by the local cache. In the
  940. case of a strong fence, the CPU first has to wait for all of its
  941. po-earlier stores to propagate to every other CPU in the system; then
  942. it has to wait for the local cache to process all the stores received
  943. as of that time -- not just the stores received when the strong fence
  944. began.
  945. And of course, none of this matters for any architecture other than
  946. Alpha.
  947. THE HAPPENS-BEFORE RELATION: hb
  948. -------------------------------
  949. The happens-before relation (hb) links memory accesses that have to
  950. execute in a certain order. hb includes the ppo relation and two
  951. others, one of which is rfe.
  952. W ->rfe R implies that W and R are on different CPUs. It also means
  953. that W's store must have propagated to R's CPU before R executed;
  954. otherwise R could not have read the value stored by W. Therefore W
  955. must have executed before R, and so we have W ->hb R.
  956. The equivalent fact need not hold if W ->rfi R (i.e., W and R are on
  957. the same CPU). As we have already seen, the operational model allows
  958. W's value to be forwarded to R in such cases, meaning that R may well
  959. execute before W does.
  960. It's important to understand that neither coe nor fre is included in
  961. hb, despite their similarities to rfe. For example, suppose we have
  962. W ->coe W'. This means that W and W' are stores to the same location,
  963. they execute on different CPUs, and W comes before W' in the coherence
  964. order (i.e., W' overwrites W). Nevertheless, it is possible for W' to
  965. execute before W, because the decision as to which store overwrites
  966. the other is made later by the memory subsystem. When the stores are
  967. nearly simultaneous, either one can come out on top. Similarly,
  968. R ->fre W means that W overwrites the value which R reads, but it
  969. doesn't mean that W has to execute after R. All that's necessary is
  970. for the memory subsystem not to propagate W to R's CPU until after R
  971. has executed, which is possible if W executes shortly before R.
  972. The third relation included in hb is like ppo, in that it only links
  973. events that are on the same CPU. However it is more difficult to
  974. explain, because it arises only indirectly from the requirement of
  975. cache coherence. The relation is called prop, and it links two events
  976. on CPU C in situations where a store from some other CPU comes after
  977. the first event in the coherence order and propagates to C before the
  978. second event executes.
  979. This is best explained with some examples. The simplest case looks
  980. like this:
  981. int x;
  982. P0()
  983. {
  984. int r1;
  985. WRITE_ONCE(x, 1);
  986. r1 = READ_ONCE(x);
  987. }
  988. P1()
  989. {
  990. WRITE_ONCE(x, 8);
  991. }
  992. If r1 = 8 at the end then P0's accesses must have executed in program
  993. order. We can deduce this from the operational model; if P0's load
  994. had executed before its store then the value of the store would have
  995. been forwarded to the load, so r1 would have ended up equal to 1, not
  996. 8. In this case there is a prop link from P0's write event to its read
  997. event, because P1's store came after P0's store in x's coherence
  998. order, and P1's store propagated to P0 before P0's load executed.
  999. An equally simple case involves two loads of the same location that
  1000. read from different stores:
  1001. int x = 0;
  1002. P0()
  1003. {
  1004. int r1, r2;
  1005. r1 = READ_ONCE(x);
  1006. r2 = READ_ONCE(x);
  1007. }
  1008. P1()
  1009. {
  1010. WRITE_ONCE(x, 9);
  1011. }
  1012. If r1 = 0 and r2 = 9 at the end then P0's accesses must have executed
  1013. in program order. If the second load had executed before the first
  1014. then the x = 9 store must have been propagated to P0 before the first
  1015. load executed, and so r1 would have been 9 rather than 0. In this
  1016. case there is a prop link from P0's first read event to its second,
  1017. because P1's store overwrote the value read by P0's first load, and
  1018. P1's store propagated to P0 before P0's second load executed.
  1019. Less trivial examples of prop all involve fences. Unlike the simple
  1020. examples above, they can require that some instructions are executed
  1021. out of program order. This next one should look familiar:
  1022. int buf = 0, flag = 0;
  1023. P0()
  1024. {
  1025. WRITE_ONCE(buf, 1);
  1026. smp_wmb();
  1027. WRITE_ONCE(flag, 1);
  1028. }
  1029. P1()
  1030. {
  1031. int r1;
  1032. int r2;
  1033. r1 = READ_ONCE(flag);
  1034. r2 = READ_ONCE(buf);
  1035. }
  1036. This is the MP pattern again, with an smp_wmb() fence between the two
  1037. stores. If r1 = 1 and r2 = 0 at the end then there is a prop link
  1038. from P1's second load to its first (backwards!). The reason is
  1039. similar to the previous examples: The value P1 loads from buf gets
  1040. overwritten by P0's store to buf, the fence guarantees that the store
  1041. to buf will propagate to P1 before the store to flag does, and the
  1042. store to flag propagates to P1 before P1 reads flag.
  1043. The prop link says that in order to obtain the r1 = 1, r2 = 0 result,
  1044. P1 must execute its second load before the first. Indeed, if the load
  1045. from flag were executed first, then the buf = 1 store would already
  1046. have propagated to P1 by the time P1's load from buf executed, so r2
  1047. would have been 1 at the end, not 0. (The reasoning holds even for
  1048. Alpha, although the details are more complicated and we will not go
  1049. into them.)
  1050. But what if we put an smp_rmb() fence between P1's loads? The fence
  1051. would force the two loads to be executed in program order, and it
  1052. would generate a cycle in the hb relation: The fence would create a ppo
  1053. link (hence an hb link) from the first load to the second, and the
  1054. prop relation would give an hb link from the second load to the first.
  1055. Since an instruction can't execute before itself, we are forced to
  1056. conclude that if an smp_rmb() fence is added, the r1 = 1, r2 = 0
  1057. outcome is impossible -- as it should be.
  1058. The formal definition of the prop relation involves a coe or fre link,
  1059. followed by an arbitrary number of cumul-fence links, ending with an
  1060. rfe link. You can concoct more exotic examples, containing more than
  1061. one fence, although this quickly leads to diminishing returns in terms
  1062. of complexity. For instance, here's an example containing a coe link
  1063. followed by two cumul-fences and an rfe link, utilizing the fact that
  1064. release fences are A-cumulative:
  1065. int x, y, z;
  1066. P0()
  1067. {
  1068. int r0;
  1069. WRITE_ONCE(x, 1);
  1070. r0 = READ_ONCE(z);
  1071. }
  1072. P1()
  1073. {
  1074. WRITE_ONCE(x, 2);
  1075. smp_wmb();
  1076. WRITE_ONCE(y, 1);
  1077. }
  1078. P2()
  1079. {
  1080. int r2;
  1081. r2 = READ_ONCE(y);
  1082. smp_store_release(&z, 1);
  1083. }
  1084. If x = 2, r0 = 1, and r2 = 1 after this code runs then there is a prop
  1085. link from P0's store to its load. This is because P0's store gets
  1086. overwritten by P1's store since x = 2 at the end (a coe link), the
  1087. smp_wmb() ensures that P1's store to x propagates to P2 before the
  1088. store to y does (the first cumul-fence), the store to y propagates to P2
  1089. before P2's load and store execute, P2's smp_store_release()
  1090. guarantees that the stores to x and y both propagate to P0 before the
  1091. store to z does (the second cumul-fence), and P0's load executes after the
  1092. store to z has propagated to P0 (an rfe link).
  1093. In summary, the fact that the hb relation links memory access events
  1094. in the order they execute means that it must not have cycles. This
  1095. requirement is the content of the LKMM's "happens-before" axiom.
  1096. The LKMM defines yet another relation connected to times of
  1097. instruction execution, but it is not included in hb. It relies on the
  1098. particular properties of strong fences, which we cover in the next
  1099. section.
  1100. THE PROPAGATES-BEFORE RELATION: pb
  1101. ----------------------------------
  1102. The propagates-before (pb) relation capitalizes on the special
  1103. features of strong fences. It links two events E and F whenever some
  1104. store is coherence-later than E and propagates to every CPU and to RAM
  1105. before F executes. The formal definition requires that E be linked to
  1106. F via a coe or fre link, an arbitrary number of cumul-fences, an
  1107. optional rfe link, a strong fence, and an arbitrary number of hb
  1108. links. Let's see how this definition works out.
  1109. Consider first the case where E is a store (implying that the sequence
  1110. of links begins with coe). Then there are events W, X, Y, and Z such
  1111. that:
  1112. E ->coe W ->cumul-fence* X ->rfe? Y ->strong-fence Z ->hb* F,
  1113. where the * suffix indicates an arbitrary number of links of the
  1114. specified type, and the ? suffix indicates the link is optional (Y may
  1115. be equal to X). Because of the cumul-fence links, we know that W will
  1116. propagate to Y's CPU before X does, hence before Y executes and hence
  1117. before the strong fence executes. Because this fence is strong, we
  1118. know that W will propagate to every CPU and to RAM before Z executes.
  1119. And because of the hb links, we know that Z will execute before F.
  1120. Thus W, which comes later than E in the coherence order, will
  1121. propagate to every CPU and to RAM before F executes.
  1122. The case where E is a load is exactly the same, except that the first
  1123. link in the sequence is fre instead of coe.
  1124. The existence of a pb link from E to F implies that E must execute
  1125. before F. To see why, suppose that F executed first. Then W would
  1126. have propagated to E's CPU before E executed. If E was a store, the
  1127. memory subsystem would then be forced to make E come after W in the
  1128. coherence order, contradicting the fact that E ->coe W. If E was a
  1129. load, the memory subsystem would then be forced to satisfy E's read
  1130. request with the value stored by W or an even later store,
  1131. contradicting the fact that E ->fre W.
  1132. A good example illustrating how pb works is the SB pattern with strong
  1133. fences:
  1134. int x = 0, y = 0;
  1135. P0()
  1136. {
  1137. int r0;
  1138. WRITE_ONCE(x, 1);
  1139. smp_mb();
  1140. r0 = READ_ONCE(y);
  1141. }
  1142. P1()
  1143. {
  1144. int r1;
  1145. WRITE_ONCE(y, 1);
  1146. smp_mb();
  1147. r1 = READ_ONCE(x);
  1148. }
  1149. If r0 = 0 at the end then there is a pb link from P0's load to P1's
  1150. load: an fre link from P0's load to P1's store (which overwrites the
  1151. value read by P0), and a strong fence between P1's store and its load.
  1152. In this example, the sequences of cumul-fence and hb links are empty.
  1153. Note that this pb link is not included in hb as an instance of prop,
  1154. because it does not start and end on the same CPU.
  1155. Similarly, if r1 = 0 at the end then there is a pb link from P1's load
  1156. to P0's. This means that if both r1 and r2 were 0 there would be a
  1157. cycle in pb, which is not possible since an instruction cannot execute
  1158. before itself. Thus, adding smp_mb() fences to the SB pattern
  1159. prevents the r0 = 0, r1 = 0 outcome.
  1160. In summary, the fact that the pb relation links events in the order
  1161. they execute means that it cannot have cycles. This requirement is
  1162. the content of the LKMM's "propagation" axiom.
  1163. RCU RELATIONS: rcu-link, rcu-gp, rcu-rscsi, rcu-order, rcu-fence, and rb
  1164. ------------------------------------------------------------------------
  1165. RCU (Read-Copy-Update) is a powerful synchronization mechanism. It
  1166. rests on two concepts: grace periods and read-side critical sections.
  1167. A grace period is the span of time occupied by a call to
  1168. synchronize_rcu(). A read-side critical section (or just critical
  1169. section, for short) is a region of code delimited by rcu_read_lock()
  1170. at the start and rcu_read_unlock() at the end. Critical sections can
  1171. be nested, although we won't make use of this fact.
  1172. As far as memory models are concerned, RCU's main feature is its
  1173. Grace-Period Guarantee, which states that a critical section can never
  1174. span a full grace period. In more detail, the Guarantee says:
  1175. For any critical section C and any grace period G, at least
  1176. one of the following statements must hold:
  1177. (1) C ends before G does, and in addition, every store that
  1178. propagates to C's CPU before the end of C must propagate to
  1179. every CPU before G ends.
  1180. (2) G starts before C does, and in addition, every store that
  1181. propagates to G's CPU before the start of G must propagate
  1182. to every CPU before C starts.
  1183. In particular, it is not possible for a critical section to both start
  1184. before and end after a grace period.
  1185. Here is a simple example of RCU in action:
  1186. int x, y;
  1187. P0()
  1188. {
  1189. rcu_read_lock();
  1190. WRITE_ONCE(x, 1);
  1191. WRITE_ONCE(y, 1);
  1192. rcu_read_unlock();
  1193. }
  1194. P1()
  1195. {
  1196. int r1, r2;
  1197. r1 = READ_ONCE(x);
  1198. synchronize_rcu();
  1199. r2 = READ_ONCE(y);
  1200. }
  1201. The Grace Period Guarantee tells us that when this code runs, it will
  1202. never end with r1 = 1 and r2 = 0. The reasoning is as follows. r1 = 1
  1203. means that P0's store to x propagated to P1 before P1 called
  1204. synchronize_rcu(), so P0's critical section must have started before
  1205. P1's grace period, contrary to part (2) of the Guarantee. On the
  1206. other hand, r2 = 0 means that P0's store to y, which occurs before the
  1207. end of the critical section, did not propagate to P1 before the end of
  1208. the grace period, contrary to part (1). Together the results violate
  1209. the Guarantee.
  1210. In the kernel's implementations of RCU, the requirements for stores
  1211. to propagate to every CPU are fulfilled by placing strong fences at
  1212. suitable places in the RCU-related code. Thus, if a critical section
  1213. starts before a grace period does then the critical section's CPU will
  1214. execute an smp_mb() fence after the end of the critical section and
  1215. some time before the grace period's synchronize_rcu() call returns.
  1216. And if a critical section ends after a grace period does then the
  1217. synchronize_rcu() routine will execute an smp_mb() fence at its start
  1218. and some time before the critical section's opening rcu_read_lock()
  1219. executes.
  1220. What exactly do we mean by saying that a critical section "starts
  1221. before" or "ends after" a grace period? Some aspects of the meaning
  1222. are pretty obvious, as in the example above, but the details aren't
  1223. entirely clear. The LKMM formalizes this notion by means of the
  1224. rcu-link relation. rcu-link encompasses a very general notion of
  1225. "before": If E and F are RCU fence events (i.e., rcu_read_lock(),
  1226. rcu_read_unlock(), or synchronize_rcu()) then among other things,
  1227. E ->rcu-link F includes cases where E is po-before some memory-access
  1228. event X, F is po-after some memory-access event Y, and we have any of
  1229. X ->rfe Y, X ->co Y, or X ->fr Y.
  1230. The formal definition of the rcu-link relation is more than a little
  1231. obscure, and we won't give it here. It is closely related to the pb
  1232. relation, and the details don't matter unless you want to comb through
  1233. a somewhat lengthy formal proof. Pretty much all you need to know
  1234. about rcu-link is the information in the preceding paragraph.
  1235. The LKMM also defines the rcu-gp and rcu-rscsi relations. They bring
  1236. grace periods and read-side critical sections into the picture, in the
  1237. following way:
  1238. E ->rcu-gp F means that E and F are in fact the same event,
  1239. and that event is a synchronize_rcu() fence (i.e., a grace
  1240. period).
  1241. E ->rcu-rscsi F means that E and F are the rcu_read_unlock()
  1242. and rcu_read_lock() fence events delimiting some read-side
  1243. critical section. (The 'i' at the end of the name emphasizes
  1244. that this relation is "inverted": It links the end of the
  1245. critical section to the start.)
  1246. If we think of the rcu-link relation as standing for an extended
  1247. "before", then X ->rcu-gp Y ->rcu-link Z roughly says that X is a
  1248. grace period which ends before Z begins. (In fact it covers more than
  1249. this, because it also includes cases where some store propagates to
  1250. Z's CPU before Z begins but doesn't propagate to some other CPU until
  1251. after X ends.) Similarly, X ->rcu-rscsi Y ->rcu-link Z says that X is
  1252. the end of a critical section which starts before Z begins.
  1253. The LKMM goes on to define the rcu-order relation as a sequence of
  1254. rcu-gp and rcu-rscsi links separated by rcu-link links, in which the
  1255. number of rcu-gp links is >= the number of rcu-rscsi links. For
  1256. example:
  1257. X ->rcu-gp Y ->rcu-link Z ->rcu-rscsi T ->rcu-link U ->rcu-gp V
  1258. would imply that X ->rcu-order V, because this sequence contains two
  1259. rcu-gp links and one rcu-rscsi link. (It also implies that
  1260. X ->rcu-order T and Z ->rcu-order V.) On the other hand:
  1261. X ->rcu-rscsi Y ->rcu-link Z ->rcu-rscsi T ->rcu-link U ->rcu-gp V
  1262. does not imply X ->rcu-order V, because the sequence contains only
  1263. one rcu-gp link but two rcu-rscsi links.
  1264. The rcu-order relation is important because the Grace Period Guarantee
  1265. means that rcu-order links act kind of like strong fences. In
  1266. particular, E ->rcu-order F implies not only that E begins before F
  1267. ends, but also that any write po-before E will propagate to every CPU
  1268. before any instruction po-after F can execute. (However, it does not
  1269. imply that E must execute before F; in fact, each synchronize_rcu()
  1270. fence event is linked to itself by rcu-order as a degenerate case.)
  1271. To prove this in full generality requires some intellectual effort.
  1272. We'll consider just a very simple case:
  1273. G ->rcu-gp W ->rcu-link Z ->rcu-rscsi F.
  1274. This formula means that G and W are the same event (a grace period),
  1275. and there are events X, Y and a read-side critical section C such that:
  1276. 1. G = W is po-before or equal to X;
  1277. 2. X comes "before" Y in some sense (including rfe, co and fr);
  1278. 3. Y is po-before Z;
  1279. 4. Z is the rcu_read_unlock() event marking the end of C;
  1280. 5. F is the rcu_read_lock() event marking the start of C.
  1281. From 1 - 4 we deduce that the grace period G ends before the critical
  1282. section C. Then part (2) of the Grace Period Guarantee says not only
  1283. that G starts before C does, but also that any write which executes on
  1284. G's CPU before G starts must propagate to every CPU before C starts.
  1285. In particular, the write propagates to every CPU before F finishes
  1286. executing and hence before any instruction po-after F can execute.
  1287. This sort of reasoning can be extended to handle all the situations
  1288. covered by rcu-order.
  1289. The rcu-fence relation is a simple extension of rcu-order. While
  1290. rcu-order only links certain fence events (calls to synchronize_rcu(),
  1291. rcu_read_lock(), or rcu_read_unlock()), rcu-fence links any events
  1292. that are separated by an rcu-order link. This is analogous to the way
  1293. the strong-fence relation links events that are separated by an
  1294. smp_mb() fence event (as mentioned above, rcu-order links act kind of
  1295. like strong fences). Written symbolically, X ->rcu-fence Y means
  1296. there are fence events E and F such that:
  1297. X ->po E ->rcu-order F ->po Y.
  1298. From the discussion above, we see this implies not only that X
  1299. executes before Y, but also (if X is a store) that X propagates to
  1300. every CPU before Y executes. Thus rcu-fence is sort of a
  1301. "super-strong" fence: Unlike the original strong fences (smp_mb() and
  1302. synchronize_rcu()), rcu-fence is able to link events on different
  1303. CPUs. (Perhaps this fact should lead us to say that rcu-fence isn't
  1304. really a fence at all!)
  1305. Finally, the LKMM defines the RCU-before (rb) relation in terms of
  1306. rcu-fence. This is done in essentially the same way as the pb
  1307. relation was defined in terms of strong-fence. We will omit the
  1308. details; the end result is that E ->rb F implies E must execute
  1309. before F, just as E ->pb F does (and for much the same reasons).
  1310. Putting this all together, the LKMM expresses the Grace Period
  1311. Guarantee by requiring that the rb relation does not contain a cycle.
  1312. Equivalently, this "rcu" axiom requires that there are no events E
  1313. and F with E ->rcu-link F ->rcu-order E. Or to put it a third way,
  1314. the axiom requires that there are no cycles consisting of rcu-gp and
  1315. rcu-rscsi alternating with rcu-link, where the number of rcu-gp links
  1316. is >= the number of rcu-rscsi links.
  1317. Justifying the axiom isn't easy, but it is in fact a valid
  1318. formalization of the Grace Period Guarantee. We won't attempt to go
  1319. through the detailed argument, but the following analysis gives a
  1320. taste of what is involved. Suppose both parts of the Guarantee are
  1321. violated: A critical section starts before a grace period, and some
  1322. store propagates to the critical section's CPU before the end of the
  1323. critical section but doesn't propagate to some other CPU until after
  1324. the end of the grace period.
  1325. Putting symbols to these ideas, let L and U be the rcu_read_lock() and
  1326. rcu_read_unlock() fence events delimiting the critical section in
  1327. question, and let S be the synchronize_rcu() fence event for the grace
  1328. period. Saying that the critical section starts before S means there
  1329. are events Q and R where Q is po-after L (which marks the start of the
  1330. critical section), Q is "before" R in the sense used by the rcu-link
  1331. relation, and R is po-before the grace period S. Thus we have:
  1332. L ->rcu-link S.
  1333. Let W be the store mentioned above, let Y come before the end of the
  1334. critical section and witness that W propagates to the critical
  1335. section's CPU by reading from W, and let Z on some arbitrary CPU be a
  1336. witness that W has not propagated to that CPU, where Z happens after
  1337. some event X which is po-after S. Symbolically, this amounts to:
  1338. S ->po X ->hb* Z ->fr W ->rf Y ->po U.
  1339. The fr link from Z to W indicates that W has not propagated to Z's CPU
  1340. at the time that Z executes. From this, it can be shown (see the
  1341. discussion of the rcu-link relation earlier) that S and U are related
  1342. by rcu-link:
  1343. S ->rcu-link U.
  1344. Since S is a grace period we have S ->rcu-gp S, and since L and U are
  1345. the start and end of the critical section C we have U ->rcu-rscsi L.
  1346. From this we obtain:
  1347. S ->rcu-gp S ->rcu-link U ->rcu-rscsi L ->rcu-link S,
  1348. a forbidden cycle. Thus the "rcu" axiom rules out this violation of
  1349. the Grace Period Guarantee.
  1350. For something a little more down-to-earth, let's see how the axiom
  1351. works out in practice. Consider the RCU code example from above, this
  1352. time with statement labels added:
  1353. int x, y;
  1354. P0()
  1355. {
  1356. L: rcu_read_lock();
  1357. X: WRITE_ONCE(x, 1);
  1358. Y: WRITE_ONCE(y, 1);
  1359. U: rcu_read_unlock();
  1360. }
  1361. P1()
  1362. {
  1363. int r1, r2;
  1364. Z: r1 = READ_ONCE(x);
  1365. S: synchronize_rcu();
  1366. W: r2 = READ_ONCE(y);
  1367. }
  1368. If r2 = 0 at the end then P0's store at Y overwrites the value that
  1369. P1's load at W reads from, so we have W ->fre Y. Since S ->po W and
  1370. also Y ->po U, we get S ->rcu-link U. In addition, S ->rcu-gp S
  1371. because S is a grace period.
  1372. If r1 = 1 at the end then P1's load at Z reads from P0's store at X,
  1373. so we have X ->rfe Z. Together with L ->po X and Z ->po S, this
  1374. yields L ->rcu-link S. And since L and U are the start and end of a
  1375. critical section, we have U ->rcu-rscsi L.
  1376. Then U ->rcu-rscsi L ->rcu-link S ->rcu-gp S ->rcu-link U is a
  1377. forbidden cycle, violating the "rcu" axiom. Hence the outcome is not
  1378. allowed by the LKMM, as we would expect.
  1379. For contrast, let's see what can happen in a more complicated example:
  1380. int x, y, z;
  1381. P0()
  1382. {
  1383. int r0;
  1384. L0: rcu_read_lock();
  1385. r0 = READ_ONCE(x);
  1386. WRITE_ONCE(y, 1);
  1387. U0: rcu_read_unlock();
  1388. }
  1389. P1()
  1390. {
  1391. int r1;
  1392. r1 = READ_ONCE(y);
  1393. S1: synchronize_rcu();
  1394. WRITE_ONCE(z, 1);
  1395. }
  1396. P2()
  1397. {
  1398. int r2;
  1399. L2: rcu_read_lock();
  1400. r2 = READ_ONCE(z);
  1401. WRITE_ONCE(x, 1);
  1402. U2: rcu_read_unlock();
  1403. }
  1404. If r0 = r1 = r2 = 1 at the end, then similar reasoning to before shows
  1405. that U0 ->rcu-rscsi L0 ->rcu-link S1 ->rcu-gp S1 ->rcu-link U2 ->rcu-rscsi
  1406. L2 ->rcu-link U0. However this cycle is not forbidden, because the
  1407. sequence of relations contains fewer instances of rcu-gp (one) than of
  1408. rcu-rscsi (two). Consequently the outcome is allowed by the LKMM.
  1409. The following instruction timing diagram shows how it might actually
  1410. occur:
  1411. P0 P1 P2
  1412. -------------------- -------------------- --------------------
  1413. rcu_read_lock()
  1414. WRITE_ONCE(y, 1)
  1415. r1 = READ_ONCE(y)
  1416. synchronize_rcu() starts
  1417. . rcu_read_lock()
  1418. . WRITE_ONCE(x, 1)
  1419. r0 = READ_ONCE(x) .
  1420. rcu_read_unlock() .
  1421. synchronize_rcu() ends
  1422. WRITE_ONCE(z, 1)
  1423. r2 = READ_ONCE(z)
  1424. rcu_read_unlock()
  1425. This requires P0 and P2 to execute their loads and stores out of
  1426. program order, but of course they are allowed to do so. And as you
  1427. can see, the Grace Period Guarantee is not violated: The critical
  1428. section in P0 both starts before P1's grace period does and ends
  1429. before it does, and the critical section in P2 both starts after P1's
  1430. grace period does and ends after it does.
  1431. Addendum: The LKMM now supports SRCU (Sleepable Read-Copy-Update) in
  1432. addition to normal RCU. The ideas involved are much the same as
  1433. above, with new relations srcu-gp and srcu-rscsi added to represent
  1434. SRCU grace periods and read-side critical sections. There is a
  1435. restriction on the srcu-gp and srcu-rscsi links that can appear in an
  1436. rcu-order sequence (the srcu-rscsi links must be paired with srcu-gp
  1437. links having the same SRCU domain with proper nesting); the details
  1438. are relatively unimportant.
  1439. LOCKING
  1440. -------
  1441. The LKMM includes locking. In fact, there is special code for locking
  1442. in the formal model, added in order to make tools run faster.
  1443. However, this special code is intended to be more or less equivalent
  1444. to concepts we have already covered. A spinlock_t variable is treated
  1445. the same as an int, and spin_lock(&s) is treated almost the same as:
  1446. while (cmpxchg_acquire(&s, 0, 1) != 0)
  1447. cpu_relax();
  1448. This waits until s is equal to 0 and then atomically sets it to 1,
  1449. and the read part of the cmpxchg operation acts as an acquire fence.
  1450. An alternate way to express the same thing would be:
  1451. r = xchg_acquire(&s, 1);
  1452. along with a requirement that at the end, r = 0. Similarly,
  1453. spin_trylock(&s) is treated almost the same as:
  1454. return !cmpxchg_acquire(&s, 0, 1);
  1455. which atomically sets s to 1 if it is currently equal to 0 and returns
  1456. true if it succeeds (the read part of the cmpxchg operation acts as an
  1457. acquire fence only if the operation is successful). spin_unlock(&s)
  1458. is treated almost the same as:
  1459. smp_store_release(&s, 0);
  1460. The "almost" qualifiers above need some explanation. In the LKMM, the
  1461. store-release in a spin_unlock() and the load-acquire which forms the
  1462. first half of the atomic rmw update in a spin_lock() or a successful
  1463. spin_trylock() -- we can call these things lock-releases and
  1464. lock-acquires -- have two properties beyond those of ordinary releases
  1465. and acquires.
  1466. First, when a lock-acquire reads from or is po-after a lock-release,
  1467. the LKMM requires that every instruction po-before the lock-release
  1468. must execute before any instruction po-after the lock-acquire. This
  1469. would naturally hold if the release and acquire operations were on
  1470. different CPUs and accessed the same lock variable, but the LKMM says
  1471. it also holds when they are on the same CPU, even if they access
  1472. different lock variables. For example:
  1473. int x, y;
  1474. spinlock_t s, t;
  1475. P0()
  1476. {
  1477. int r1, r2;
  1478. spin_lock(&s);
  1479. r1 = READ_ONCE(x);
  1480. spin_unlock(&s);
  1481. spin_lock(&t);
  1482. r2 = READ_ONCE(y);
  1483. spin_unlock(&t);
  1484. }
  1485. P1()
  1486. {
  1487. WRITE_ONCE(y, 1);
  1488. smp_wmb();
  1489. WRITE_ONCE(x, 1);
  1490. }
  1491. Here the second spin_lock() is po-after the first spin_unlock(), and
  1492. therefore the load of x must execute before the load of y, even though
  1493. the two locking operations use different locks. Thus we cannot have
  1494. r1 = 1 and r2 = 0 at the end (this is an instance of the MP pattern).
  1495. This requirement does not apply to ordinary release and acquire
  1496. fences, only to lock-related operations. For instance, suppose P0()
  1497. in the example had been written as:
  1498. P0()
  1499. {
  1500. int r1, r2, r3;
  1501. r1 = READ_ONCE(x);
  1502. smp_store_release(&s, 1);
  1503. r3 = smp_load_acquire(&s);
  1504. r2 = READ_ONCE(y);
  1505. }
  1506. Then the CPU would be allowed to forward the s = 1 value from the
  1507. smp_store_release() to the smp_load_acquire(), executing the
  1508. instructions in the following order:
  1509. r3 = smp_load_acquire(&s); // Obtains r3 = 1
  1510. r2 = READ_ONCE(y);
  1511. r1 = READ_ONCE(x);
  1512. smp_store_release(&s, 1); // Value is forwarded
  1513. and thus it could load y before x, obtaining r2 = 0 and r1 = 1.
  1514. Second, when a lock-acquire reads from or is po-after a lock-release,
  1515. and some other stores W and W' occur po-before the lock-release and
  1516. po-after the lock-acquire respectively, the LKMM requires that W must
  1517. propagate to each CPU before W' does. For example, consider:
  1518. int x, y;
  1519. spinlock_t s;
  1520. P0()
  1521. {
  1522. spin_lock(&s);
  1523. WRITE_ONCE(x, 1);
  1524. spin_unlock(&s);
  1525. }
  1526. P1()
  1527. {
  1528. int r1;
  1529. spin_lock(&s);
  1530. r1 = READ_ONCE(x);
  1531. WRITE_ONCE(y, 1);
  1532. spin_unlock(&s);
  1533. }
  1534. P2()
  1535. {
  1536. int r2, r3;
  1537. r2 = READ_ONCE(y);
  1538. smp_rmb();
  1539. r3 = READ_ONCE(x);
  1540. }
  1541. If r1 = 1 at the end then the spin_lock() in P1 must have read from
  1542. the spin_unlock() in P0. Hence the store to x must propagate to P2
  1543. before the store to y does, so we cannot have r2 = 1 and r3 = 0. But
  1544. if P1 had used a lock variable different from s, the writes could have
  1545. propagated in either order. (On the other hand, if the code in P0 and
  1546. P1 had all executed on a single CPU, as in the example before this
  1547. one, then the writes would have propagated in order even if the two
  1548. critical sections used different lock variables.)
  1549. These two special requirements for lock-release and lock-acquire do
  1550. not arise from the operational model. Nevertheless, kernel developers
  1551. have come to expect and rely on them because they do hold on all
  1552. architectures supported by the Linux kernel, albeit for various
  1553. differing reasons.
  1554. PLAIN ACCESSES AND DATA RACES
  1555. -----------------------------
  1556. In the LKMM, memory accesses such as READ_ONCE(x), atomic_inc(&y),
  1557. smp_load_acquire(&z), and so on are collectively referred to as
  1558. "marked" accesses, because they are all annotated with special
  1559. operations of one kind or another. Ordinary C-language memory
  1560. accesses such as x or y = 0 are simply called "plain" accesses.
  1561. Early versions of the LKMM had nothing to say about plain accesses.
  1562. The C standard allows compilers to assume that the variables affected
  1563. by plain accesses are not concurrently read or written by any other
  1564. threads or CPUs. This leaves compilers free to implement all manner
  1565. of transformations or optimizations of code containing plain accesses,
  1566. making such code very difficult for a memory model to handle.
  1567. Here is just one example of a possible pitfall:
  1568. int a = 6;
  1569. int *x = &a;
  1570. P0()
  1571. {
  1572. int *r1;
  1573. int r2 = 0;
  1574. r1 = x;
  1575. if (r1 != NULL)
  1576. r2 = READ_ONCE(*r1);
  1577. }
  1578. P1()
  1579. {
  1580. WRITE_ONCE(x, NULL);
  1581. }
  1582. On the face of it, one would expect that when this code runs, the only
  1583. possible final values for r2 are 6 and 0, depending on whether or not
  1584. P1's store to x propagates to P0 before P0's load from x executes.
  1585. But since P0's load from x is a plain access, the compiler may decide
  1586. to carry out the load twice (for the comparison against NULL, then again
  1587. for the READ_ONCE()) and eliminate the temporary variable r1. The
  1588. object code generated for P0 could therefore end up looking rather
  1589. like this:
  1590. P0()
  1591. {
  1592. int r2 = 0;
  1593. if (x != NULL)
  1594. r2 = READ_ONCE(*x);
  1595. }
  1596. And now it is obvious that this code runs the risk of dereferencing a
  1597. NULL pointer, because P1's store to x might propagate to P0 after the
  1598. test against NULL has been made but before the READ_ONCE() executes.
  1599. If the original code had said "r1 = READ_ONCE(x)" instead of "r1 = x",
  1600. the compiler would not have performed this optimization and there
  1601. would be no possibility of a NULL-pointer dereference.
  1602. Given the possibility of transformations like this one, the LKMM
  1603. doesn't try to predict all possible outcomes of code containing plain
  1604. accesses. It is instead content to determine whether the code
  1605. violates the compiler's assumptions, which would render the ultimate
  1606. outcome undefined.
  1607. In technical terms, the compiler is allowed to assume that when the
  1608. program executes, there will not be any data races. A "data race"
  1609. occurs when there are two memory accesses such that:
  1610. 1. they access the same location,
  1611. 2. at least one of them is a store,
  1612. 3. at least one of them is plain,
  1613. 4. they occur on different CPUs (or in different threads on the
  1614. same CPU), and
  1615. 5. they execute concurrently.
  1616. In the literature, two accesses are said to "conflict" if they satisfy
  1617. 1 and 2 above. We'll go a little farther and say that two accesses
  1618. are "race candidates" if they satisfy 1 - 4. Thus, whether or not two
  1619. race candidates actually do race in a given execution depends on
  1620. whether they are concurrent.
  1621. The LKMM tries to determine whether a program contains race candidates
  1622. which may execute concurrently; if it does then the LKMM says there is
  1623. a potential data race and makes no predictions about the program's
  1624. outcome.
  1625. Determining whether two accesses are race candidates is easy; you can
  1626. see that all the concepts involved in the definition above are already
  1627. part of the memory model. The hard part is telling whether they may
  1628. execute concurrently. The LKMM takes a conservative attitude,
  1629. assuming that accesses may be concurrent unless it can prove they
  1630. are not.
  1631. If two memory accesses aren't concurrent then one must execute before
  1632. the other. Therefore the LKMM decides two accesses aren't concurrent
  1633. if they can be connected by a sequence of hb, pb, and rb links
  1634. (together referred to as xb, for "executes before"). However, there
  1635. are two complicating factors.
  1636. If X is a load and X executes before a store Y, then indeed there is
  1637. no danger of X and Y being concurrent. After all, Y can't have any
  1638. effect on the value obtained by X until the memory subsystem has
  1639. propagated Y from its own CPU to X's CPU, which won't happen until
  1640. some time after Y executes and thus after X executes. But if X is a
  1641. store, then even if X executes before Y it is still possible that X
  1642. will propagate to Y's CPU just as Y is executing. In such a case X
  1643. could very well interfere somehow with Y, and we would have to
  1644. consider X and Y to be concurrent.
  1645. Therefore when X is a store, for X and Y to be non-concurrent the LKMM
  1646. requires not only that X must execute before Y but also that X must
  1647. propagate to Y's CPU before Y executes. (Or vice versa, of course, if
  1648. Y executes before X -- then Y must propagate to X's CPU before X
  1649. executes if Y is a store.) This is expressed by the visibility
  1650. relation (vis), where X ->vis Y is defined to hold if there is an
  1651. intermediate event Z such that:
  1652. X is connected to Z by a possibly empty sequence of
  1653. cumul-fence links followed by an optional rfe link (if none of
  1654. these links are present, X and Z are the same event),
  1655. and either:
  1656. Z is connected to Y by a strong-fence link followed by a
  1657. possibly empty sequence of xb links,
  1658. or:
  1659. Z is on the same CPU as Y and is connected to Y by a possibly
  1660. empty sequence of xb links (again, if the sequence is empty it
  1661. means Z and Y are the same event).
  1662. The motivations behind this definition are straightforward:
  1663. cumul-fence memory barriers force stores that are po-before
  1664. the barrier to propagate to other CPUs before stores that are
  1665. po-after the barrier.
  1666. An rfe link from an event W to an event R says that R reads
  1667. from W, which certainly means that W must have propagated to
  1668. R's CPU before R executed.
  1669. strong-fence memory barriers force stores that are po-before
  1670. the barrier, or that propagate to the barrier's CPU before the
  1671. barrier executes, to propagate to all CPUs before any events
  1672. po-after the barrier can execute.
  1673. To see how this works out in practice, consider our old friend, the MP
  1674. pattern (with fences and statement labels, but without the conditional
  1675. test):
  1676. int buf = 0, flag = 0;
  1677. P0()
  1678. {
  1679. X: WRITE_ONCE(buf, 1);
  1680. smp_wmb();
  1681. W: WRITE_ONCE(flag, 1);
  1682. }
  1683. P1()
  1684. {
  1685. int r1;
  1686. int r2 = 0;
  1687. Z: r1 = READ_ONCE(flag);
  1688. smp_rmb();
  1689. Y: r2 = READ_ONCE(buf);
  1690. }
  1691. The smp_wmb() memory barrier gives a cumul-fence link from X to W, and
  1692. assuming r1 = 1 at the end, there is an rfe link from W to Z. This
  1693. means that the store to buf must propagate from P0 to P1 before Z
  1694. executes. Next, Z and Y are on the same CPU and the smp_rmb() fence
  1695. provides an xb link from Z to Y (i.e., it forces Z to execute before
  1696. Y). Therefore we have X ->vis Y: X must propagate to Y's CPU before Y
  1697. executes.
  1698. The second complicating factor mentioned above arises from the fact
  1699. that when we are considering data races, some of the memory accesses
  1700. are plain. Now, although we have not said so explicitly, up to this
  1701. point most of the relations defined by the LKMM (ppo, hb, prop,
  1702. cumul-fence, pb, and so on -- including vis) apply only to marked
  1703. accesses.
  1704. There are good reasons for this restriction. The compiler is not
  1705. allowed to apply fancy transformations to marked accesses, and
  1706. consequently each such access in the source code corresponds more or
  1707. less directly to a single machine instruction in the object code. But
  1708. plain accesses are a different story; the compiler may combine them,
  1709. split them up, duplicate them, eliminate them, invent new ones, and
  1710. who knows what else. Seeing a plain access in the source code tells
  1711. you almost nothing about what machine instructions will end up in the
  1712. object code.
  1713. Fortunately, the compiler isn't completely free; it is subject to some
  1714. limitations. For one, it is not allowed to introduce a data race into
  1715. the object code if the source code does not already contain a data
  1716. race (if it could, memory models would be useless and no multithreaded
  1717. code would be safe!). For another, it cannot move a plain access past
  1718. a compiler barrier.
  1719. A compiler barrier is a kind of fence, but as the name implies, it
  1720. only affects the compiler; it does not necessarily have any effect on
  1721. how instructions are executed by the CPU. In Linux kernel source
  1722. code, the barrier() function is a compiler barrier. It doesn't give
  1723. rise directly to any machine instructions in the object code; rather,
  1724. it affects how the compiler generates the rest of the object code.
  1725. Given source code like this:
  1726. ... some memory accesses ...
  1727. barrier();
  1728. ... some other memory accesses ...
  1729. the barrier() function ensures that the machine instructions
  1730. corresponding to the first group of accesses will all end po-before
  1731. any machine instructions corresponding to the second group of accesses
  1732. -- even if some of the accesses are plain. (Of course, the CPU may
  1733. then execute some of those accesses out of program order, but we
  1734. already know how to deal with such issues.) Without the barrier()
  1735. there would be no such guarantee; the two groups of accesses could be
  1736. intermingled or even reversed in the object code.
  1737. The LKMM doesn't say much about the barrier() function, but it does
  1738. require that all fences are also compiler barriers. In addition, it
  1739. requires that the ordering properties of memory barriers such as
  1740. smp_rmb() or smp_store_release() apply to plain accesses as well as to
  1741. marked accesses.
  1742. This is the key to analyzing data races. Consider the MP pattern
  1743. again, now using plain accesses for buf:
  1744. int buf = 0, flag = 0;
  1745. P0()
  1746. {
  1747. U: buf = 1;
  1748. smp_wmb();
  1749. X: WRITE_ONCE(flag, 1);
  1750. }
  1751. P1()
  1752. {
  1753. int r1;
  1754. int r2 = 0;
  1755. Y: r1 = READ_ONCE(flag);
  1756. if (r1) {
  1757. smp_rmb();
  1758. V: r2 = buf;
  1759. }
  1760. }
  1761. This program does not contain a data race. Although the U and V
  1762. accesses are race candidates, the LKMM can prove they are not
  1763. concurrent as follows:
  1764. The smp_wmb() fence in P0 is both a compiler barrier and a
  1765. cumul-fence. It guarantees that no matter what hash of
  1766. machine instructions the compiler generates for the plain
  1767. access U, all those instructions will be po-before the fence.
  1768. Consequently U's store to buf, no matter how it is carried out
  1769. at the machine level, must propagate to P1 before X's store to
  1770. flag does.
  1771. X and Y are both marked accesses. Hence an rfe link from X to
  1772. Y is a valid indicator that X propagated to P1 before Y
  1773. executed, i.e., X ->vis Y. (And if there is no rfe link then
  1774. r1 will be 0, so V will not be executed and ipso facto won't
  1775. race with U.)
  1776. The smp_rmb() fence in P1 is a compiler barrier as well as a
  1777. fence. It guarantees that all the machine-level instructions
  1778. corresponding to the access V will be po-after the fence, and
  1779. therefore any loads among those instructions will execute
  1780. after the fence does and hence after Y does.
  1781. Thus U's store to buf is forced to propagate to P1 before V's load
  1782. executes (assuming V does execute), ruling out the possibility of a
  1783. data race between them.
  1784. This analysis illustrates how the LKMM deals with plain accesses in
  1785. general. Suppose R is a plain load and we want to show that R
  1786. executes before some marked access E. We can do this by finding a
  1787. marked access X such that R and X are ordered by a suitable fence and
  1788. X ->xb* E. If E was also a plain access, we would also look for a
  1789. marked access Y such that X ->xb* Y, and Y and E are ordered by a
  1790. fence. We describe this arrangement by saying that R is
  1791. "post-bounded" by X and E is "pre-bounded" by Y.
  1792. In fact, we go one step further: Since R is a read, we say that R is
  1793. "r-post-bounded" by X. Similarly, E would be "r-pre-bounded" or
  1794. "w-pre-bounded" by Y, depending on whether E was a store or a load.
  1795. This distinction is needed because some fences affect only loads
  1796. (i.e., smp_rmb()) and some affect only stores (smp_wmb()); otherwise
  1797. the two types of bounds are the same. And as a degenerate case, we
  1798. say that a marked access pre-bounds and post-bounds itself (e.g., if R
  1799. above were a marked load then X could simply be taken to be R itself.)
  1800. The need to distinguish between r- and w-bounding raises yet another
  1801. issue. When the source code contains a plain store, the compiler is
  1802. allowed to put plain loads of the same location into the object code.
  1803. For example, given the source code:
  1804. x = 1;
  1805. the compiler is theoretically allowed to generate object code that
  1806. looks like:
  1807. if (x != 1)
  1808. x = 1;
  1809. thereby adding a load (and possibly replacing the store entirely).
  1810. For this reason, whenever the LKMM requires a plain store to be
  1811. w-pre-bounded or w-post-bounded by a marked access, it also requires
  1812. the store to be r-pre-bounded or r-post-bounded, so as to handle cases
  1813. where the compiler adds a load.
  1814. (This may be overly cautious. We don't know of any examples where a
  1815. compiler has augmented a store with a load in this fashion, and the
  1816. Linux kernel developers would probably fight pretty hard to change a
  1817. compiler if it ever did this. Still, better safe than sorry.)
  1818. Incidentally, the other tranformation -- augmenting a plain load by
  1819. adding in a store to the same location -- is not allowed. This is
  1820. because the compiler cannot know whether any other CPUs might perform
  1821. a concurrent load from that location. Two concurrent loads don't
  1822. constitute a race (they can't interfere with each other), but a store
  1823. does race with a concurrent load. Thus adding a store might create a
  1824. data race where one was not already present in the source code,
  1825. something the compiler is forbidden to do. Augmenting a store with a
  1826. load, on the other hand, is acceptable because doing so won't create a
  1827. data race unless one already existed.
  1828. The LKMM includes a second way to pre-bound plain accesses, in
  1829. addition to fences: an address dependency from a marked load. That
  1830. is, in the sequence:
  1831. p = READ_ONCE(ptr);
  1832. r = *p;
  1833. the LKMM says that the marked load of ptr pre-bounds the plain load of
  1834. *p; the marked load must execute before any of the machine
  1835. instructions corresponding to the plain load. This is a reasonable
  1836. stipulation, since after all, the CPU can't perform the load of *p
  1837. until it knows what value p will hold. Furthermore, without some
  1838. assumption like this one, some usages typical of RCU would count as
  1839. data races. For example:
  1840. int a = 1, b;
  1841. int *ptr = &a;
  1842. P0()
  1843. {
  1844. b = 2;
  1845. rcu_assign_pointer(ptr, &b);
  1846. }
  1847. P1()
  1848. {
  1849. int *p;
  1850. int r;
  1851. rcu_read_lock();
  1852. p = rcu_dereference(ptr);
  1853. r = *p;
  1854. rcu_read_unlock();
  1855. }
  1856. (In this example the rcu_read_lock() and rcu_read_unlock() calls don't
  1857. really do anything, because there aren't any grace periods. They are
  1858. included merely for the sake of good form; typically P0 would call
  1859. synchronize_rcu() somewhere after the rcu_assign_pointer().)
  1860. rcu_assign_pointer() performs a store-release, so the plain store to b
  1861. is definitely w-post-bounded before the store to ptr, and the two
  1862. stores will propagate to P1 in that order. However, rcu_dereference()
  1863. is only equivalent to READ_ONCE(). While it is a marked access, it is
  1864. not a fence or compiler barrier. Hence the only guarantee we have
  1865. that the load of ptr in P1 is r-pre-bounded before the load of *p
  1866. (thus avoiding a race) is the assumption about address dependencies.
  1867. This is a situation where the compiler can undermine the memory model,
  1868. and a certain amount of care is required when programming constructs
  1869. like this one. In particular, comparisons between the pointer and
  1870. other known addresses can cause trouble. If you have something like:
  1871. p = rcu_dereference(ptr);
  1872. if (p == &x)
  1873. r = *p;
  1874. then the compiler just might generate object code resembling:
  1875. p = rcu_dereference(ptr);
  1876. if (p == &x)
  1877. r = x;
  1878. or even:
  1879. rtemp = x;
  1880. p = rcu_dereference(ptr);
  1881. if (p == &x)
  1882. r = rtemp;
  1883. which would invalidate the memory model's assumption, since the CPU
  1884. could now perform the load of x before the load of ptr (there might be
  1885. a control dependency but no address dependency at the machine level).
  1886. Finally, it turns out there is a situation in which a plain write does
  1887. not need to be w-post-bounded: when it is separated from the other
  1888. race-candidate access by a fence. At first glance this may seem
  1889. impossible. After all, to be race candidates the two accesses must
  1890. be on different CPUs, and fences don't link events on different CPUs.
  1891. Well, normal fences don't -- but rcu-fence can! Here's an example:
  1892. int x, y;
  1893. P0()
  1894. {
  1895. WRITE_ONCE(x, 1);
  1896. synchronize_rcu();
  1897. y = 3;
  1898. }
  1899. P1()
  1900. {
  1901. rcu_read_lock();
  1902. if (READ_ONCE(x) == 0)
  1903. y = 2;
  1904. rcu_read_unlock();
  1905. }
  1906. Do the plain stores to y race? Clearly not if P1 reads a non-zero
  1907. value for x, so let's assume the READ_ONCE(x) does obtain 0. This
  1908. means that the read-side critical section in P1 must finish executing
  1909. before the grace period in P0 does, because RCU's Grace-Period
  1910. Guarantee says that otherwise P0's store to x would have propagated to
  1911. P1 before the critical section started and so would have been visible
  1912. to the READ_ONCE(). (Another way of putting it is that the fre link
  1913. from the READ_ONCE() to the WRITE_ONCE() gives rise to an rcu-link
  1914. between those two events.)
  1915. This means there is an rcu-fence link from P1's "y = 2" store to P0's
  1916. "y = 3" store, and consequently the first must propagate from P1 to P0
  1917. before the second can execute. Therefore the two stores cannot be
  1918. concurrent and there is no race, even though P1's plain store to y
  1919. isn't w-post-bounded by any marked accesses.
  1920. Putting all this material together yields the following picture. For
  1921. race-candidate stores W and W', where W ->co W', the LKMM says the
  1922. stores don't race if W can be linked to W' by a
  1923. w-post-bounded ; vis ; w-pre-bounded
  1924. sequence. If W is plain then they also have to be linked by an
  1925. r-post-bounded ; xb* ; w-pre-bounded
  1926. sequence, and if W' is plain then they also have to be linked by a
  1927. w-post-bounded ; vis ; r-pre-bounded
  1928. sequence. For race-candidate load R and store W, the LKMM says the
  1929. two accesses don't race if R can be linked to W by an
  1930. r-post-bounded ; xb* ; w-pre-bounded
  1931. sequence or if W can be linked to R by a
  1932. w-post-bounded ; vis ; r-pre-bounded
  1933. sequence. For the cases involving a vis link, the LKMM also accepts
  1934. sequences in which W is linked to W' or R by a
  1935. strong-fence ; xb* ; {w and/or r}-pre-bounded
  1936. sequence with no post-bounding, and in every case the LKMM also allows
  1937. the link simply to be a fence with no bounding at all. If no sequence
  1938. of the appropriate sort exists, the LKMM says that the accesses race.
  1939. There is one more part of the LKMM related to plain accesses (although
  1940. not to data races) we should discuss. Recall that many relations such
  1941. as hb are limited to marked accesses only. As a result, the
  1942. happens-before, propagates-before, and rcu axioms (which state that
  1943. various relation must not contain a cycle) doesn't apply to plain
  1944. accesses. Nevertheless, we do want to rule out such cycles, because
  1945. they don't make sense even for plain accesses.
  1946. To this end, the LKMM imposes three extra restrictions, together
  1947. called the "plain-coherence" axiom because of their resemblance to the
  1948. rules used by the operational model to ensure cache coherence (that
  1949. is, the rules governing the memory subsystem's choice of a store to
  1950. satisfy a load request and its determination of where a store will
  1951. fall in the coherence order):
  1952. If R and W are race candidates and it is possible to link R to
  1953. W by one of the xb* sequences listed above, then W ->rfe R is
  1954. not allowed (i.e., a load cannot read from a store that it
  1955. executes before, even if one or both is plain).
  1956. If W and R are race candidates and it is possible to link W to
  1957. R by one of the vis sequences listed above, then R ->fre W is
  1958. not allowed (i.e., if a store is visible to a load then the
  1959. load must read from that store or one coherence-after it).
  1960. If W and W' are race candidates and it is possible to link W
  1961. to W' by one of the vis sequences listed above, then W' ->co W
  1962. is not allowed (i.e., if one store is visible to a second then
  1963. the second must come after the first in the coherence order).
  1964. This is the extent to which the LKMM deals with plain accesses.
  1965. Perhaps it could say more (for example, plain accesses might
  1966. contribute to the ppo relation), but at the moment it seems that this
  1967. minimal, conservative approach is good enough.
  1968. ODDS AND ENDS
  1969. -------------
  1970. This section covers material that didn't quite fit anywhere in the
  1971. earlier sections.
  1972. The descriptions in this document don't always match the formal
  1973. version of the LKMM exactly. For example, the actual formal
  1974. definition of the prop relation makes the initial coe or fre part
  1975. optional, and it doesn't require the events linked by the relation to
  1976. be on the same CPU. These differences are very unimportant; indeed,
  1977. instances where the coe/fre part of prop is missing are of no interest
  1978. because all the other parts (fences and rfe) are already included in
  1979. hb anyway, and where the formal model adds prop into hb, it includes
  1980. an explicit requirement that the events being linked are on the same
  1981. CPU.
  1982. Another minor difference has to do with events that are both memory
  1983. accesses and fences, such as those corresponding to smp_load_acquire()
  1984. calls. In the formal model, these events aren't actually both reads
  1985. and fences; rather, they are read events with an annotation marking
  1986. them as acquires. (Or write events annotated as releases, in the case
  1987. smp_store_release().) The final effect is the same.
  1988. Although we didn't mention it above, the instruction execution
  1989. ordering provided by the smp_rmb() fence doesn't apply to read events
  1990. that are part of a non-value-returning atomic update. For instance,
  1991. given:
  1992. atomic_inc(&x);
  1993. smp_rmb();
  1994. r1 = READ_ONCE(y);
  1995. it is not guaranteed that the load from y will execute after the
  1996. update to x. This is because the ARMv8 architecture allows
  1997. non-value-returning atomic operations effectively to be executed off
  1998. the CPU. Basically, the CPU tells the memory subsystem to increment
  1999. x, and then the increment is carried out by the memory hardware with
  2000. no further involvement from the CPU. Since the CPU doesn't ever read
  2001. the value of x, there is nothing for the smp_rmb() fence to act on.
  2002. The LKMM defines a few extra synchronization operations in terms of
  2003. things we have already covered. In particular, rcu_dereference() is
  2004. treated as READ_ONCE() and rcu_assign_pointer() is treated as
  2005. smp_store_release() -- which is basically how the Linux kernel treats
  2006. them.
  2007. Although we said that plain accesses are not linked by the ppo
  2008. relation, they do contribute to it indirectly. Namely, when there is
  2009. an address dependency from a marked load R to a plain store W,
  2010. followed by smp_wmb() and then a marked store W', the LKMM creates a
  2011. ppo link from R to W'. The reasoning behind this is perhaps a little
  2012. shaky, but essentially it says there is no way to generate object code
  2013. for this source code in which W' could execute before R. Just as with
  2014. pre-bounding by address dependencies, it is possible for the compiler
  2015. to undermine this relation if sufficient care is not taken.
  2016. There are a few oddball fences which need special treatment:
  2017. smp_mb__before_atomic(), smp_mb__after_atomic(), and
  2018. smp_mb__after_spinlock(). The LKMM uses fence events with special
  2019. annotations for them; they act as strong fences just like smp_mb()
  2020. except for the sets of events that they order. Instead of ordering
  2021. all po-earlier events against all po-later events, as smp_mb() does,
  2022. they behave as follows:
  2023. smp_mb__before_atomic() orders all po-earlier events against
  2024. po-later atomic updates and the events following them;
  2025. smp_mb__after_atomic() orders po-earlier atomic updates and
  2026. the events preceding them against all po-later events;
  2027. smp_mb__after_spinlock() orders po-earlier lock acquisition
  2028. events and the events preceding them against all po-later
  2029. events.
  2030. Interestingly, RCU and locking each introduce the possibility of
  2031. deadlock. When faced with code sequences such as:
  2032. spin_lock(&s);
  2033. spin_lock(&s);
  2034. spin_unlock(&s);
  2035. spin_unlock(&s);
  2036. or:
  2037. rcu_read_lock();
  2038. synchronize_rcu();
  2039. rcu_read_unlock();
  2040. what does the LKMM have to say? Answer: It says there are no allowed
  2041. executions at all, which makes sense. But this can also lead to
  2042. misleading results, because if a piece of code has multiple possible
  2043. executions, some of which deadlock, the model will report only on the
  2044. non-deadlocking executions. For example:
  2045. int x, y;
  2046. P0()
  2047. {
  2048. int r0;
  2049. WRITE_ONCE(x, 1);
  2050. r0 = READ_ONCE(y);
  2051. }
  2052. P1()
  2053. {
  2054. rcu_read_lock();
  2055. if (READ_ONCE(x) > 0) {
  2056. WRITE_ONCE(y, 36);
  2057. synchronize_rcu();
  2058. }
  2059. rcu_read_unlock();
  2060. }
  2061. Is it possible to end up with r0 = 36 at the end? The LKMM will tell
  2062. you it is not, but the model won't mention that this is because P1
  2063. will self-deadlock in the executions where it stores 36 in y.