explanation.txt 107 KB

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