memory-barriers.txt 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144
  1. ============================
  2. LINUX KERNEL MEMORY BARRIERS
  3. ============================
  4. By: David Howells <dhowells@redhat.com>
  5. Paul E. McKenney <paulmck@linux.vnet.ibm.com>
  6. Will Deacon <will.deacon@arm.com>
  7. Peter Zijlstra <peterz@infradead.org>
  8. ==========
  9. DISCLAIMER
  10. ==========
  11. This document is not a specification; it is intentionally (for the sake of
  12. brevity) and unintentionally (due to being human) incomplete. This document is
  13. meant as a guide to using the various memory barriers provided by Linux, but
  14. in case of any doubt (and there are many) please ask.
  15. To repeat, this document is not a specification of what Linux expects from
  16. hardware.
  17. The purpose of this document is twofold:
  18. (1) to specify the minimum functionality that one can rely on for any
  19. particular barrier, and
  20. (2) to provide a guide as to how to use the barriers that are available.
  21. Note that an architecture can provide more than the minimum requirement
  22. for any particular barrier, but if the architecture provides less than
  23. that, that architecture is incorrect.
  24. Note also that it is possible that a barrier may be a no-op for an
  25. architecture because the way that arch works renders an explicit barrier
  26. unnecessary in that case.
  27. ========
  28. CONTENTS
  29. ========
  30. (*) Abstract memory access model.
  31. - Device operations.
  32. - Guarantees.
  33. (*) What are memory barriers?
  34. - Varieties of memory barrier.
  35. - What may not be assumed about memory barriers?
  36. - Data dependency barriers.
  37. - Control dependencies.
  38. - SMP barrier pairing.
  39. - Examples of memory barrier sequences.
  40. - Read memory barriers vs load speculation.
  41. - Transitivity
  42. (*) Explicit kernel barriers.
  43. - Compiler barrier.
  44. - CPU memory barriers.
  45. - MMIO write barrier.
  46. (*) Implicit kernel memory barriers.
  47. - Lock acquisition functions.
  48. - Interrupt disabling functions.
  49. - Sleep and wake-up functions.
  50. - Miscellaneous functions.
  51. (*) Inter-CPU acquiring barrier effects.
  52. - Acquires vs memory accesses.
  53. - Acquires vs I/O accesses.
  54. (*) Where are memory barriers needed?
  55. - Interprocessor interaction.
  56. - Atomic operations.
  57. - Accessing devices.
  58. - Interrupts.
  59. (*) Kernel I/O barrier effects.
  60. (*) Assumed minimum execution ordering model.
  61. (*) The effects of the cpu cache.
  62. - Cache coherency.
  63. - Cache coherency vs DMA.
  64. - Cache coherency vs MMIO.
  65. (*) The things CPUs get up to.
  66. - And then there's the Alpha.
  67. - Virtual Machine Guests.
  68. (*) Example uses.
  69. - Circular buffers.
  70. (*) References.
  71. ============================
  72. ABSTRACT MEMORY ACCESS MODEL
  73. ============================
  74. Consider the following abstract model of the system:
  75. : :
  76. : :
  77. : :
  78. +-------+ : +--------+ : +-------+
  79. | | : | | : | |
  80. | | : | | : | |
  81. | CPU 1 |<----->| Memory |<----->| CPU 2 |
  82. | | : | | : | |
  83. | | : | | : | |
  84. +-------+ : +--------+ : +-------+
  85. ^ : ^ : ^
  86. | : | : |
  87. | : | : |
  88. | : v : |
  89. | : +--------+ : |
  90. | : | | : |
  91. | : | | : |
  92. +---------->| Device |<----------+
  93. : | | :
  94. : | | :
  95. : +--------+ :
  96. : :
  97. Each CPU executes a program that generates memory access operations. In the
  98. abstract CPU, memory operation ordering is very relaxed, and a CPU may actually
  99. perform the memory operations in any order it likes, provided program causality
  100. appears to be maintained. Similarly, the compiler may also arrange the
  101. instructions it emits in any order it likes, provided it doesn't affect the
  102. apparent operation of the program.
  103. So in the above diagram, the effects of the memory operations performed by a
  104. CPU are perceived by the rest of the system as the operations cross the
  105. interface between the CPU and rest of the system (the dotted lines).
  106. For example, consider the following sequence of events:
  107. CPU 1 CPU 2
  108. =============== ===============
  109. { A == 1; B == 2 }
  110. A = 3; x = B;
  111. B = 4; y = A;
  112. The set of accesses as seen by the memory system in the middle can be arranged
  113. in 24 different combinations:
  114. STORE A=3, STORE B=4, y=LOAD A->3, x=LOAD B->4
  115. STORE A=3, STORE B=4, x=LOAD B->4, y=LOAD A->3
  116. STORE A=3, y=LOAD A->3, STORE B=4, x=LOAD B->4
  117. STORE A=3, y=LOAD A->3, x=LOAD B->2, STORE B=4
  118. STORE A=3, x=LOAD B->2, STORE B=4, y=LOAD A->3
  119. STORE A=3, x=LOAD B->2, y=LOAD A->3, STORE B=4
  120. STORE B=4, STORE A=3, y=LOAD A->3, x=LOAD B->4
  121. STORE B=4, ...
  122. ...
  123. and can thus result in four different combinations of values:
  124. x == 2, y == 1
  125. x == 2, y == 3
  126. x == 4, y == 1
  127. x == 4, y == 3
  128. Furthermore, the stores committed by a CPU to the memory system may not be
  129. perceived by the loads made by another CPU in the same order as the stores were
  130. committed.
  131. As a further example, consider this sequence of events:
  132. CPU 1 CPU 2
  133. =============== ===============
  134. { A == 1, B == 2, C == 3, P == &A, Q == &C }
  135. B = 4; Q = P;
  136. P = &B D = *Q;
  137. There is an obvious data dependency here, as the value loaded into D depends on
  138. the address retrieved from P by CPU 2. At the end of the sequence, any of the
  139. following results are possible:
  140. (Q == &A) and (D == 1)
  141. (Q == &B) and (D == 2)
  142. (Q == &B) and (D == 4)
  143. Note that CPU 2 will never try and load C into D because the CPU will load P
  144. into Q before issuing the load of *Q.
  145. DEVICE OPERATIONS
  146. -----------------
  147. Some devices present their control interfaces as collections of memory
  148. locations, but the order in which the control registers are accessed is very
  149. important. For instance, imagine an ethernet card with a set of internal
  150. registers that are accessed through an address port register (A) and a data
  151. port register (D). To read internal register 5, the following code might then
  152. be used:
  153. *A = 5;
  154. x = *D;
  155. but this might show up as either of the following two sequences:
  156. STORE *A = 5, x = LOAD *D
  157. x = LOAD *D, STORE *A = 5
  158. the second of which will almost certainly result in a malfunction, since it set
  159. the address _after_ attempting to read the register.
  160. GUARANTEES
  161. ----------
  162. There are some minimal guarantees that may be expected of a CPU:
  163. (*) On any given CPU, dependent memory accesses will be issued in order, with
  164. respect to itself. This means that for:
  165. Q = READ_ONCE(P); smp_read_barrier_depends(); D = READ_ONCE(*Q);
  166. the CPU will issue the following memory operations:
  167. Q = LOAD P, D = LOAD *Q
  168. and always in that order. On most systems, smp_read_barrier_depends()
  169. does nothing, but it is required for DEC Alpha. The READ_ONCE()
  170. is required to prevent compiler mischief. Please note that you
  171. should normally use something like rcu_dereference() instead of
  172. open-coding smp_read_barrier_depends().
  173. (*) Overlapping loads and stores within a particular CPU will appear to be
  174. ordered within that CPU. This means that for:
  175. a = READ_ONCE(*X); WRITE_ONCE(*X, b);
  176. the CPU will only issue the following sequence of memory operations:
  177. a = LOAD *X, STORE *X = b
  178. And for:
  179. WRITE_ONCE(*X, c); d = READ_ONCE(*X);
  180. the CPU will only issue:
  181. STORE *X = c, d = LOAD *X
  182. (Loads and stores overlap if they are targeted at overlapping pieces of
  183. memory).
  184. And there are a number of things that _must_ or _must_not_ be assumed:
  185. (*) It _must_not_ be assumed that the compiler will do what you want
  186. with memory references that are not protected by READ_ONCE() and
  187. WRITE_ONCE(). Without them, the compiler is within its rights to
  188. do all sorts of "creative" transformations, which are covered in
  189. the COMPILER BARRIER section.
  190. (*) It _must_not_ be assumed that independent loads and stores will be issued
  191. in the order given. This means that for:
  192. X = *A; Y = *B; *D = Z;
  193. we may get any of the following sequences:
  194. X = LOAD *A, Y = LOAD *B, STORE *D = Z
  195. X = LOAD *A, STORE *D = Z, Y = LOAD *B
  196. Y = LOAD *B, X = LOAD *A, STORE *D = Z
  197. Y = LOAD *B, STORE *D = Z, X = LOAD *A
  198. STORE *D = Z, X = LOAD *A, Y = LOAD *B
  199. STORE *D = Z, Y = LOAD *B, X = LOAD *A
  200. (*) It _must_ be assumed that overlapping memory accesses may be merged or
  201. discarded. This means that for:
  202. X = *A; Y = *(A + 4);
  203. we may get any one of the following sequences:
  204. X = LOAD *A; Y = LOAD *(A + 4);
  205. Y = LOAD *(A + 4); X = LOAD *A;
  206. {X, Y} = LOAD {*A, *(A + 4) };
  207. And for:
  208. *A = X; *(A + 4) = Y;
  209. we may get any of:
  210. STORE *A = X; STORE *(A + 4) = Y;
  211. STORE *(A + 4) = Y; STORE *A = X;
  212. STORE {*A, *(A + 4) } = {X, Y};
  213. And there are anti-guarantees:
  214. (*) These guarantees do not apply to bitfields, because compilers often
  215. generate code to modify these using non-atomic read-modify-write
  216. sequences. Do not attempt to use bitfields to synchronize parallel
  217. algorithms.
  218. (*) Even in cases where bitfields are protected by locks, all fields
  219. in a given bitfield must be protected by one lock. If two fields
  220. in a given bitfield are protected by different locks, the compiler's
  221. non-atomic read-modify-write sequences can cause an update to one
  222. field to corrupt the value of an adjacent field.
  223. (*) These guarantees apply only to properly aligned and sized scalar
  224. variables. "Properly sized" currently means variables that are
  225. the same size as "char", "short", "int" and "long". "Properly
  226. aligned" means the natural alignment, thus no constraints for
  227. "char", two-byte alignment for "short", four-byte alignment for
  228. "int", and either four-byte or eight-byte alignment for "long",
  229. on 32-bit and 64-bit systems, respectively. Note that these
  230. guarantees were introduced into the C11 standard, so beware when
  231. using older pre-C11 compilers (for example, gcc 4.6). The portion
  232. of the standard containing this guarantee is Section 3.14, which
  233. defines "memory location" as follows:
  234. memory location
  235. either an object of scalar type, or a maximal sequence
  236. of adjacent bit-fields all having nonzero width
  237. NOTE 1: Two threads of execution can update and access
  238. separate memory locations without interfering with
  239. each other.
  240. NOTE 2: A bit-field and an adjacent non-bit-field member
  241. are in separate memory locations. The same applies
  242. to two bit-fields, if one is declared inside a nested
  243. structure declaration and the other is not, or if the two
  244. are separated by a zero-length bit-field declaration,
  245. or if they are separated by a non-bit-field member
  246. declaration. It is not safe to concurrently update two
  247. bit-fields in the same structure if all members declared
  248. between them are also bit-fields, no matter what the
  249. sizes of those intervening bit-fields happen to be.
  250. =========================
  251. WHAT ARE MEMORY BARRIERS?
  252. =========================
  253. As can be seen above, independent memory operations are effectively performed
  254. in random order, but this can be a problem for CPU-CPU interaction and for I/O.
  255. What is required is some way of intervening to instruct the compiler and the
  256. CPU to restrict the order.
  257. Memory barriers are such interventions. They impose a perceived partial
  258. ordering over the memory operations on either side of the barrier.
  259. Such enforcement is important because the CPUs and other devices in a system
  260. can use a variety of tricks to improve performance, including reordering,
  261. deferral and combination of memory operations; speculative loads; speculative
  262. branch prediction and various types of caching. Memory barriers are used to
  263. override or suppress these tricks, allowing the code to sanely control the
  264. interaction of multiple CPUs and/or devices.
  265. VARIETIES OF MEMORY BARRIER
  266. ---------------------------
  267. Memory barriers come in four basic varieties:
  268. (1) Write (or store) memory barriers.
  269. A write memory barrier gives a guarantee that all the STORE operations
  270. specified before the barrier will appear to happen before all the STORE
  271. operations specified after the barrier with respect to the other
  272. components of the system.
  273. A write barrier is a partial ordering on stores only; it is not required
  274. to have any effect on loads.
  275. A CPU can be viewed as committing a sequence of store operations to the
  276. memory system as time progresses. All stores before a write barrier will
  277. occur in the sequence _before_ all the stores after the write barrier.
  278. [!] Note that write barriers should normally be paired with read or data
  279. dependency barriers; see the "SMP barrier pairing" subsection.
  280. (2) Data dependency barriers.
  281. A data dependency barrier is a weaker form of read barrier. In the case
  282. where two loads are performed such that the second depends on the result
  283. of the first (eg: the first load retrieves the address to which the second
  284. load will be directed), a data dependency barrier would be required to
  285. make sure that the target of the second load is updated before the address
  286. obtained by the first load is accessed.
  287. A data dependency barrier is a partial ordering on interdependent loads
  288. only; it is not required to have any effect on stores, independent loads
  289. or overlapping loads.
  290. As mentioned in (1), the other CPUs in the system can be viewed as
  291. committing sequences of stores to the memory system that the CPU being
  292. considered can then perceive. A data dependency barrier issued by the CPU
  293. under consideration guarantees that for any load preceding it, if that
  294. load touches one of a sequence of stores from another CPU, then by the
  295. time the barrier completes, the effects of all the stores prior to that
  296. touched by the load will be perceptible to any loads issued after the data
  297. dependency barrier.
  298. See the "Examples of memory barrier sequences" subsection for diagrams
  299. showing the ordering constraints.
  300. [!] Note that the first load really has to have a _data_ dependency and
  301. not a control dependency. If the address for the second load is dependent
  302. on the first load, but the dependency is through a conditional rather than
  303. actually loading the address itself, then it's a _control_ dependency and
  304. a full read barrier or better is required. See the "Control dependencies"
  305. subsection for more information.
  306. [!] Note that data dependency barriers should normally be paired with
  307. write barriers; see the "SMP barrier pairing" subsection.
  308. (3) Read (or load) memory barriers.
  309. A read barrier is a data dependency barrier plus a guarantee that all the
  310. LOAD operations specified before the barrier will appear to happen before
  311. all the LOAD operations specified after the barrier with respect to the
  312. other components of the system.
  313. A read barrier is a partial ordering on loads only; it is not required to
  314. have any effect on stores.
  315. Read memory barriers imply data dependency barriers, and so can substitute
  316. for them.
  317. [!] Note that read barriers should normally be paired with write barriers;
  318. see the "SMP barrier pairing" subsection.
  319. (4) General memory barriers.
  320. A general memory barrier gives a guarantee that all the LOAD and STORE
  321. operations specified before the barrier will appear to happen before all
  322. the LOAD and STORE operations specified after the barrier with respect to
  323. the other components of the system.
  324. A general memory barrier is a partial ordering over both loads and stores.
  325. General memory barriers imply both read and write memory barriers, and so
  326. can substitute for either.
  327. And a couple of implicit varieties:
  328. (5) ACQUIRE operations.
  329. This acts as a one-way permeable barrier. It guarantees that all memory
  330. operations after the ACQUIRE operation will appear to happen after the
  331. ACQUIRE operation with respect to the other components of the system.
  332. ACQUIRE operations include LOCK operations and both smp_load_acquire()
  333. and smp_cond_acquire() operations. The later builds the necessary ACQUIRE
  334. semantics from relying on a control dependency and smp_rmb().
  335. Memory operations that occur before an ACQUIRE operation may appear to
  336. happen after it completes.
  337. An ACQUIRE operation should almost always be paired with a RELEASE
  338. operation.
  339. (6) RELEASE operations.
  340. This also acts as a one-way permeable barrier. It guarantees that all
  341. memory operations before the RELEASE operation will appear to happen
  342. before the RELEASE operation with respect to the other components of the
  343. system. RELEASE operations include UNLOCK operations and
  344. smp_store_release() operations.
  345. Memory operations that occur after a RELEASE operation may appear to
  346. happen before it completes.
  347. The use of ACQUIRE and RELEASE operations generally precludes the need
  348. for other sorts of memory barrier (but note the exceptions mentioned in
  349. the subsection "MMIO write barrier"). In addition, a RELEASE+ACQUIRE
  350. pair is -not- guaranteed to act as a full memory barrier. However, after
  351. an ACQUIRE on a given variable, all memory accesses preceding any prior
  352. RELEASE on that same variable are guaranteed to be visible. In other
  353. words, within a given variable's critical section, all accesses of all
  354. previous critical sections for that variable are guaranteed to have
  355. completed.
  356. This means that ACQUIRE acts as a minimal "acquire" operation and
  357. RELEASE acts as a minimal "release" operation.
  358. A subset of the atomic operations described in atomic_t.txt have ACQUIRE and
  359. RELEASE variants in addition to fully-ordered and relaxed (no barrier
  360. semantics) definitions. For compound atomics performing both a load and a
  361. store, ACQUIRE semantics apply only to the load and RELEASE semantics apply
  362. only to the store portion of the operation.
  363. Memory barriers are only required where there's a possibility of interaction
  364. between two CPUs or between a CPU and a device. If it can be guaranteed that
  365. there won't be any such interaction in any particular piece of code, then
  366. memory barriers are unnecessary in that piece of code.
  367. Note that these are the _minimum_ guarantees. Different architectures may give
  368. more substantial guarantees, but they may _not_ be relied upon outside of arch
  369. specific code.
  370. WHAT MAY NOT BE ASSUMED ABOUT MEMORY BARRIERS?
  371. ----------------------------------------------
  372. There are certain things that the Linux kernel memory barriers do not guarantee:
  373. (*) There is no guarantee that any of the memory accesses specified before a
  374. memory barrier will be _complete_ by the completion of a memory barrier
  375. instruction; the barrier can be considered to draw a line in that CPU's
  376. access queue that accesses of the appropriate type may not cross.
  377. (*) There is no guarantee that issuing a memory barrier on one CPU will have
  378. any direct effect on another CPU or any other hardware in the system. The
  379. indirect effect will be the order in which the second CPU sees the effects
  380. of the first CPU's accesses occur, but see the next point:
  381. (*) There is no guarantee that a CPU will see the correct order of effects
  382. from a second CPU's accesses, even _if_ the second CPU uses a memory
  383. barrier, unless the first CPU _also_ uses a matching memory barrier (see
  384. the subsection on "SMP Barrier Pairing").
  385. (*) There is no guarantee that some intervening piece of off-the-CPU
  386. hardware[*] will not reorder the memory accesses. CPU cache coherency
  387. mechanisms should propagate the indirect effects of a memory barrier
  388. between CPUs, but might not do so in order.
  389. [*] For information on bus mastering DMA and coherency please read:
  390. Documentation/PCI/pci.txt
  391. Documentation/DMA-API-HOWTO.txt
  392. Documentation/DMA-API.txt
  393. DATA DEPENDENCY BARRIERS
  394. ------------------------
  395. The usage requirements of data dependency barriers are a little subtle, and
  396. it's not always obvious that they're needed. To illustrate, consider the
  397. following sequence of events:
  398. CPU 1 CPU 2
  399. =============== ===============
  400. { A == 1, B == 2, C == 3, P == &A, Q == &C }
  401. B = 4;
  402. <write barrier>
  403. WRITE_ONCE(P, &B)
  404. Q = READ_ONCE(P);
  405. D = *Q;
  406. There's a clear data dependency here, and it would seem that by the end of the
  407. sequence, Q must be either &A or &B, and that:
  408. (Q == &A) implies (D == 1)
  409. (Q == &B) implies (D == 4)
  410. But! CPU 2's perception of P may be updated _before_ its perception of B, thus
  411. leading to the following situation:
  412. (Q == &B) and (D == 2) ????
  413. Whilst this may seem like a failure of coherency or causality maintenance, it
  414. isn't, and this behaviour can be observed on certain real CPUs (such as the DEC
  415. Alpha).
  416. To deal with this, a data dependency barrier or better must be inserted
  417. between the address load and the data load:
  418. CPU 1 CPU 2
  419. =============== ===============
  420. { A == 1, B == 2, C == 3, P == &A, Q == &C }
  421. B = 4;
  422. <write barrier>
  423. WRITE_ONCE(P, &B);
  424. Q = READ_ONCE(P);
  425. <data dependency barrier>
  426. D = *Q;
  427. This enforces the occurrence of one of the two implications, and prevents the
  428. third possibility from arising.
  429. [!] Note that this extremely counterintuitive situation arises most easily on
  430. machines with split caches, so that, for example, one cache bank processes
  431. even-numbered cache lines and the other bank processes odd-numbered cache
  432. lines. The pointer P might be stored in an odd-numbered cache line, and the
  433. variable B might be stored in an even-numbered cache line. Then, if the
  434. even-numbered bank of the reading CPU's cache is extremely busy while the
  435. odd-numbered bank is idle, one can see the new value of the pointer P (&B),
  436. but the old value of the variable B (2).
  437. A data-dependency barrier is not required to order dependent writes
  438. because the CPUs that the Linux kernel supports don't do writes
  439. until they are certain (1) that the write will actually happen, (2)
  440. of the location of the write, and (3) of the value to be written.
  441. But please carefully read the "CONTROL DEPENDENCIES" section and the
  442. Documentation/RCU/rcu_dereference.txt file: The compiler can and does
  443. break dependencies in a great many highly creative ways.
  444. CPU 1 CPU 2
  445. =============== ===============
  446. { A == 1, B == 2, C = 3, P == &A, Q == &C }
  447. B = 4;
  448. <write barrier>
  449. WRITE_ONCE(P, &B);
  450. Q = READ_ONCE(P);
  451. WRITE_ONCE(*Q, 5);
  452. Therefore, no data-dependency barrier is required to order the read into
  453. Q with the store into *Q. In other words, this outcome is prohibited,
  454. even without a data-dependency barrier:
  455. (Q == &B) && (B == 4)
  456. Please note that this pattern should be rare. After all, the whole point
  457. of dependency ordering is to -prevent- writes to the data structure, along
  458. with the expensive cache misses associated with those writes. This pattern
  459. can be used to record rare error conditions and the like, and the CPUs'
  460. naturally occurring ordering prevents such records from being lost.
  461. The data dependency barrier is very important to the RCU system,
  462. for example. See rcu_assign_pointer() and rcu_dereference() in
  463. include/linux/rcupdate.h. This permits the current target of an RCU'd
  464. pointer to be replaced with a new modified target, without the replacement
  465. target appearing to be incompletely initialised.
  466. See also the subsection on "Cache Coherency" for a more thorough example.
  467. CONTROL DEPENDENCIES
  468. --------------------
  469. Control dependencies can be a bit tricky because current compilers do
  470. not understand them. The purpose of this section is to help you prevent
  471. the compiler's ignorance from breaking your code.
  472. A load-load control dependency requires a full read memory barrier, not
  473. simply a data dependency barrier to make it work correctly. Consider the
  474. following bit of code:
  475. q = READ_ONCE(a);
  476. if (q) {
  477. <data dependency barrier> /* BUG: No data dependency!!! */
  478. p = READ_ONCE(b);
  479. }
  480. This will not have the desired effect because there is no actual data
  481. dependency, but rather a control dependency that the CPU may short-circuit
  482. by attempting to predict the outcome in advance, so that other CPUs see
  483. the load from b as having happened before the load from a. In such a
  484. case what's actually required is:
  485. q = READ_ONCE(a);
  486. if (q) {
  487. <read barrier>
  488. p = READ_ONCE(b);
  489. }
  490. However, stores are not speculated. This means that ordering -is- provided
  491. for load-store control dependencies, as in the following example:
  492. q = READ_ONCE(a);
  493. if (q) {
  494. WRITE_ONCE(b, 1);
  495. }
  496. Control dependencies pair normally with other types of barriers.
  497. That said, please note that neither READ_ONCE() nor WRITE_ONCE()
  498. are optional! Without the READ_ONCE(), the compiler might combine the
  499. load from 'a' with other loads from 'a'. Without the WRITE_ONCE(),
  500. the compiler might combine the store to 'b' with other stores to 'b'.
  501. Either can result in highly counterintuitive effects on ordering.
  502. Worse yet, if the compiler is able to prove (say) that the value of
  503. variable 'a' is always non-zero, it would be well within its rights
  504. to optimize the original example by eliminating the "if" statement
  505. as follows:
  506. q = a;
  507. b = 1; /* BUG: Compiler and CPU can both reorder!!! */
  508. So don't leave out the READ_ONCE().
  509. It is tempting to try to enforce ordering on identical stores on both
  510. branches of the "if" statement as follows:
  511. q = READ_ONCE(a);
  512. if (q) {
  513. barrier();
  514. WRITE_ONCE(b, 1);
  515. do_something();
  516. } else {
  517. barrier();
  518. WRITE_ONCE(b, 1);
  519. do_something_else();
  520. }
  521. Unfortunately, current compilers will transform this as follows at high
  522. optimization levels:
  523. q = READ_ONCE(a);
  524. barrier();
  525. WRITE_ONCE(b, 1); /* BUG: No ordering vs. load from a!!! */
  526. if (q) {
  527. /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
  528. do_something();
  529. } else {
  530. /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
  531. do_something_else();
  532. }
  533. Now there is no conditional between the load from 'a' and the store to
  534. 'b', which means that the CPU is within its rights to reorder them:
  535. The conditional is absolutely required, and must be present in the
  536. assembly code even after all compiler optimizations have been applied.
  537. Therefore, if you need ordering in this example, you need explicit
  538. memory barriers, for example, smp_store_release():
  539. q = READ_ONCE(a);
  540. if (q) {
  541. smp_store_release(&b, 1);
  542. do_something();
  543. } else {
  544. smp_store_release(&b, 1);
  545. do_something_else();
  546. }
  547. In contrast, without explicit memory barriers, two-legged-if control
  548. ordering is guaranteed only when the stores differ, for example:
  549. q = READ_ONCE(a);
  550. if (q) {
  551. WRITE_ONCE(b, 1);
  552. do_something();
  553. } else {
  554. WRITE_ONCE(b, 2);
  555. do_something_else();
  556. }
  557. The initial READ_ONCE() is still required to prevent the compiler from
  558. proving the value of 'a'.
  559. In addition, you need to be careful what you do with the local variable 'q',
  560. otherwise the compiler might be able to guess the value and again remove
  561. the needed conditional. For example:
  562. q = READ_ONCE(a);
  563. if (q % MAX) {
  564. WRITE_ONCE(b, 1);
  565. do_something();
  566. } else {
  567. WRITE_ONCE(b, 2);
  568. do_something_else();
  569. }
  570. If MAX is defined to be 1, then the compiler knows that (q % MAX) is
  571. equal to zero, in which case the compiler is within its rights to
  572. transform the above code into the following:
  573. q = READ_ONCE(a);
  574. WRITE_ONCE(b, 2);
  575. do_something_else();
  576. Given this transformation, the CPU is not required to respect the ordering
  577. between the load from variable 'a' and the store to variable 'b'. It is
  578. tempting to add a barrier(), but this does not help. The conditional
  579. is gone, and the barrier won't bring it back. Therefore, if you are
  580. relying on this ordering, you should make sure that MAX is greater than
  581. one, perhaps as follows:
  582. q = READ_ONCE(a);
  583. BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */
  584. if (q % MAX) {
  585. WRITE_ONCE(b, 1);
  586. do_something();
  587. } else {
  588. WRITE_ONCE(b, 2);
  589. do_something_else();
  590. }
  591. Please note once again that the stores to 'b' differ. If they were
  592. identical, as noted earlier, the compiler could pull this store outside
  593. of the 'if' statement.
  594. You must also be careful not to rely too much on boolean short-circuit
  595. evaluation. Consider this example:
  596. q = READ_ONCE(a);
  597. if (q || 1 > 0)
  598. WRITE_ONCE(b, 1);
  599. Because the first condition cannot fault and the second condition is
  600. always true, the compiler can transform this example as following,
  601. defeating control dependency:
  602. q = READ_ONCE(a);
  603. WRITE_ONCE(b, 1);
  604. This example underscores the need to ensure that the compiler cannot
  605. out-guess your code. More generally, although READ_ONCE() does force
  606. the compiler to actually emit code for a given load, it does not force
  607. the compiler to use the results.
  608. In addition, control dependencies apply only to the then-clause and
  609. else-clause of the if-statement in question. In particular, it does
  610. not necessarily apply to code following the if-statement:
  611. q = READ_ONCE(a);
  612. if (q) {
  613. WRITE_ONCE(b, 1);
  614. } else {
  615. WRITE_ONCE(b, 2);
  616. }
  617. WRITE_ONCE(c, 1); /* BUG: No ordering against the read from 'a'. */
  618. It is tempting to argue that there in fact is ordering because the
  619. compiler cannot reorder volatile accesses and also cannot reorder
  620. the writes to 'b' with the condition. Unfortunately for this line
  621. of reasoning, the compiler might compile the two writes to 'b' as
  622. conditional-move instructions, as in this fanciful pseudo-assembly
  623. language:
  624. ld r1,a
  625. cmp r1,$0
  626. cmov,ne r4,$1
  627. cmov,eq r4,$2
  628. st r4,b
  629. st $1,c
  630. A weakly ordered CPU would have no dependency of any sort between the load
  631. from 'a' and the store to 'c'. The control dependencies would extend
  632. only to the pair of cmov instructions and the store depending on them.
  633. In short, control dependencies apply only to the stores in the then-clause
  634. and else-clause of the if-statement in question (including functions
  635. invoked by those two clauses), not to code following that if-statement.
  636. Finally, control dependencies do -not- provide transitivity. This is
  637. demonstrated by two related examples, with the initial values of
  638. 'x' and 'y' both being zero:
  639. CPU 0 CPU 1
  640. ======================= =======================
  641. r1 = READ_ONCE(x); r2 = READ_ONCE(y);
  642. if (r1 > 0) if (r2 > 0)
  643. WRITE_ONCE(y, 1); WRITE_ONCE(x, 1);
  644. assert(!(r1 == 1 && r2 == 1));
  645. The above two-CPU example will never trigger the assert(). However,
  646. if control dependencies guaranteed transitivity (which they do not),
  647. then adding the following CPU would guarantee a related assertion:
  648. CPU 2
  649. =====================
  650. WRITE_ONCE(x, 2);
  651. assert(!(r1 == 2 && r2 == 1 && x == 2)); /* FAILS!!! */
  652. But because control dependencies do -not- provide transitivity, the above
  653. assertion can fail after the combined three-CPU example completes. If you
  654. need the three-CPU example to provide ordering, you will need smp_mb()
  655. between the loads and stores in the CPU 0 and CPU 1 code fragments,
  656. that is, just before or just after the "if" statements. Furthermore,
  657. the original two-CPU example is very fragile and should be avoided.
  658. These two examples are the LB and WWC litmus tests from this paper:
  659. http://www.cl.cam.ac.uk/users/pes20/ppc-supplemental/test6.pdf and this
  660. site: https://www.cl.cam.ac.uk/~pes20/ppcmem/index.html.
  661. In summary:
  662. (*) Control dependencies can order prior loads against later stores.
  663. However, they do -not- guarantee any other sort of ordering:
  664. Not prior loads against later loads, nor prior stores against
  665. later anything. If you need these other forms of ordering,
  666. use smp_rmb(), smp_wmb(), or, in the case of prior stores and
  667. later loads, smp_mb().
  668. (*) If both legs of the "if" statement begin with identical stores to
  669. the same variable, then those stores must be ordered, either by
  670. preceding both of them with smp_mb() or by using smp_store_release()
  671. to carry out the stores. Please note that it is -not- sufficient
  672. to use barrier() at beginning of each leg of the "if" statement
  673. because, as shown by the example above, optimizing compilers can
  674. destroy the control dependency while respecting the letter of the
  675. barrier() law.
  676. (*) Control dependencies require at least one run-time conditional
  677. between the prior load and the subsequent store, and this
  678. conditional must involve the prior load. If the compiler is able
  679. to optimize the conditional away, it will have also optimized
  680. away the ordering. Careful use of READ_ONCE() and WRITE_ONCE()
  681. can help to preserve the needed conditional.
  682. (*) Control dependencies require that the compiler avoid reordering the
  683. dependency into nonexistence. Careful use of READ_ONCE() or
  684. atomic{,64}_read() can help to preserve your control dependency.
  685. Please see the COMPILER BARRIER section for more information.
  686. (*) Control dependencies apply only to the then-clause and else-clause
  687. of the if-statement containing the control dependency, including
  688. any functions that these two clauses call. Control dependencies
  689. do -not- apply to code following the if-statement containing the
  690. control dependency.
  691. (*) Control dependencies pair normally with other types of barriers.
  692. (*) Control dependencies do -not- provide transitivity. If you
  693. need transitivity, use smp_mb().
  694. (*) Compilers do not understand control dependencies. It is therefore
  695. your job to ensure that they do not break your code.
  696. SMP BARRIER PAIRING
  697. -------------------
  698. When dealing with CPU-CPU interactions, certain types of memory barrier should
  699. always be paired. A lack of appropriate pairing is almost certainly an error.
  700. General barriers pair with each other, though they also pair with most
  701. other types of barriers, albeit without transitivity. An acquire barrier
  702. pairs with a release barrier, but both may also pair with other barriers,
  703. including of course general barriers. A write barrier pairs with a data
  704. dependency barrier, a control dependency, an acquire barrier, a release
  705. barrier, a read barrier, or a general barrier. Similarly a read barrier,
  706. control dependency, or a data dependency barrier pairs with a write
  707. barrier, an acquire barrier, a release barrier, or a general barrier:
  708. CPU 1 CPU 2
  709. =============== ===============
  710. WRITE_ONCE(a, 1);
  711. <write barrier>
  712. WRITE_ONCE(b, 2); x = READ_ONCE(b);
  713. <read barrier>
  714. y = READ_ONCE(a);
  715. Or:
  716. CPU 1 CPU 2
  717. =============== ===============================
  718. a = 1;
  719. <write barrier>
  720. WRITE_ONCE(b, &a); x = READ_ONCE(b);
  721. <data dependency barrier>
  722. y = *x;
  723. Or even:
  724. CPU 1 CPU 2
  725. =============== ===============================
  726. r1 = READ_ONCE(y);
  727. <general barrier>
  728. WRITE_ONCE(y, 1); if (r2 = READ_ONCE(x)) {
  729. <implicit control dependency>
  730. WRITE_ONCE(y, 1);
  731. }
  732. assert(r1 == 0 || r2 == 0);
  733. Basically, the read barrier always has to be there, even though it can be of
  734. the "weaker" type.
  735. [!] Note that the stores before the write barrier would normally be expected to
  736. match the loads after the read barrier or the data dependency barrier, and vice
  737. versa:
  738. CPU 1 CPU 2
  739. =================== ===================
  740. WRITE_ONCE(a, 1); }---- --->{ v = READ_ONCE(c);
  741. WRITE_ONCE(b, 2); } \ / { w = READ_ONCE(d);
  742. <write barrier> \ <read barrier>
  743. WRITE_ONCE(c, 3); } / \ { x = READ_ONCE(a);
  744. WRITE_ONCE(d, 4); }---- --->{ y = READ_ONCE(b);
  745. EXAMPLES OF MEMORY BARRIER SEQUENCES
  746. ------------------------------------
  747. Firstly, write barriers act as partial orderings on store operations.
  748. Consider the following sequence of events:
  749. CPU 1
  750. =======================
  751. STORE A = 1
  752. STORE B = 2
  753. STORE C = 3
  754. <write barrier>
  755. STORE D = 4
  756. STORE E = 5
  757. This sequence of events is committed to the memory coherence system in an order
  758. that the rest of the system might perceive as the unordered set of { STORE A,
  759. STORE B, STORE C } all occurring before the unordered set of { STORE D, STORE E
  760. }:
  761. +-------+ : :
  762. | | +------+
  763. | |------>| C=3 | } /\
  764. | | : +------+ }----- \ -----> Events perceptible to
  765. | | : | A=1 | } \/ the rest of the system
  766. | | : +------+ }
  767. | CPU 1 | : | B=2 | }
  768. | | +------+ }
  769. | | wwwwwwwwwwwwwwww } <--- At this point the write barrier
  770. | | +------+ } requires all stores prior to the
  771. | | : | E=5 | } barrier to be committed before
  772. | | : +------+ } further stores may take place
  773. | |------>| D=4 | }
  774. | | +------+
  775. +-------+ : :
  776. |
  777. | Sequence in which stores are committed to the
  778. | memory system by CPU 1
  779. V
  780. Secondly, data dependency barriers act as partial orderings on data-dependent
  781. loads. Consider the following sequence of events:
  782. CPU 1 CPU 2
  783. ======================= =======================
  784. { B = 7; X = 9; Y = 8; C = &Y }
  785. STORE A = 1
  786. STORE B = 2
  787. <write barrier>
  788. STORE C = &B LOAD X
  789. STORE D = 4 LOAD C (gets &B)
  790. LOAD *C (reads B)
  791. Without intervention, CPU 2 may perceive the events on CPU 1 in some
  792. effectively random order, despite the write barrier issued by CPU 1:
  793. +-------+ : : : :
  794. | | +------+ +-------+ | Sequence of update
  795. | |------>| B=2 |----- --->| Y->8 | | of perception on
  796. | | : +------+ \ +-------+ | CPU 2
  797. | CPU 1 | : | A=1 | \ --->| C->&Y | V
  798. | | +------+ | +-------+
  799. | | wwwwwwwwwwwwwwww | : :
  800. | | +------+ | : :
  801. | | : | C=&B |--- | : : +-------+
  802. | | : +------+ \ | +-------+ | |
  803. | |------>| D=4 | ----------->| C->&B |------>| |
  804. | | +------+ | +-------+ | |
  805. +-------+ : : | : : | |
  806. | : : | |
  807. | : : | CPU 2 |
  808. | +-------+ | |
  809. Apparently incorrect ---> | | B->7 |------>| |
  810. perception of B (!) | +-------+ | |
  811. | : : | |
  812. | +-------+ | |
  813. The load of X holds ---> \ | X->9 |------>| |
  814. up the maintenance \ +-------+ | |
  815. of coherence of B ----->| B->2 | +-------+
  816. +-------+
  817. : :
  818. In the above example, CPU 2 perceives that B is 7, despite the load of *C
  819. (which would be B) coming after the LOAD of C.
  820. If, however, a data dependency barrier were to be placed between the load of C
  821. and the load of *C (ie: B) on CPU 2:
  822. CPU 1 CPU 2
  823. ======================= =======================
  824. { B = 7; X = 9; Y = 8; C = &Y }
  825. STORE A = 1
  826. STORE B = 2
  827. <write barrier>
  828. STORE C = &B LOAD X
  829. STORE D = 4 LOAD C (gets &B)
  830. <data dependency barrier>
  831. LOAD *C (reads B)
  832. then the following will occur:
  833. +-------+ : : : :
  834. | | +------+ +-------+
  835. | |------>| B=2 |----- --->| Y->8 |
  836. | | : +------+ \ +-------+
  837. | CPU 1 | : | A=1 | \ --->| C->&Y |
  838. | | +------+ | +-------+
  839. | | wwwwwwwwwwwwwwww | : :
  840. | | +------+ | : :
  841. | | : | C=&B |--- | : : +-------+
  842. | | : +------+ \ | +-------+ | |
  843. | |------>| D=4 | ----------->| C->&B |------>| |
  844. | | +------+ | +-------+ | |
  845. +-------+ : : | : : | |
  846. | : : | |
  847. | : : | CPU 2 |
  848. | +-------+ | |
  849. | | X->9 |------>| |
  850. | +-------+ | |
  851. Makes sure all effects ---> \ ddddddddddddddddd | |
  852. prior to the store of C \ +-------+ | |
  853. are perceptible to ----->| B->2 |------>| |
  854. subsequent loads +-------+ | |
  855. : : +-------+
  856. And thirdly, a read barrier acts as a partial order on loads. Consider the
  857. following sequence of events:
  858. CPU 1 CPU 2
  859. ======================= =======================
  860. { A = 0, B = 9 }
  861. STORE A=1
  862. <write barrier>
  863. STORE B=2
  864. LOAD B
  865. LOAD A
  866. Without intervention, CPU 2 may then choose to perceive the events on CPU 1 in
  867. some effectively random order, despite the write barrier issued by CPU 1:
  868. +-------+ : : : :
  869. | | +------+ +-------+
  870. | |------>| A=1 |------ --->| A->0 |
  871. | | +------+ \ +-------+
  872. | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
  873. | | +------+ | +-------+
  874. | |------>| B=2 |--- | : :
  875. | | +------+ \ | : : +-------+
  876. +-------+ : : \ | +-------+ | |
  877. ---------->| B->2 |------>| |
  878. | +-------+ | CPU 2 |
  879. | | A->0 |------>| |
  880. | +-------+ | |
  881. | : : +-------+
  882. \ : :
  883. \ +-------+
  884. ---->| A->1 |
  885. +-------+
  886. : :
  887. If, however, a read barrier were to be placed between the load of B and the
  888. load of A on CPU 2:
  889. CPU 1 CPU 2
  890. ======================= =======================
  891. { A = 0, B = 9 }
  892. STORE A=1
  893. <write barrier>
  894. STORE B=2
  895. LOAD B
  896. <read barrier>
  897. LOAD A
  898. then the partial ordering imposed by CPU 1 will be perceived correctly by CPU
  899. 2:
  900. +-------+ : : : :
  901. | | +------+ +-------+
  902. | |------>| A=1 |------ --->| A->0 |
  903. | | +------+ \ +-------+
  904. | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
  905. | | +------+ | +-------+
  906. | |------>| B=2 |--- | : :
  907. | | +------+ \ | : : +-------+
  908. +-------+ : : \ | +-------+ | |
  909. ---------->| B->2 |------>| |
  910. | +-------+ | CPU 2 |
  911. | : : | |
  912. | : : | |
  913. At this point the read ----> \ rrrrrrrrrrrrrrrrr | |
  914. barrier causes all effects \ +-------+ | |
  915. prior to the storage of B ---->| A->1 |------>| |
  916. to be perceptible to CPU 2 +-------+ | |
  917. : : +-------+
  918. To illustrate this more completely, consider what could happen if the code
  919. contained a load of A either side of the read barrier:
  920. CPU 1 CPU 2
  921. ======================= =======================
  922. { A = 0, B = 9 }
  923. STORE A=1
  924. <write barrier>
  925. STORE B=2
  926. LOAD B
  927. LOAD A [first load of A]
  928. <read barrier>
  929. LOAD A [second load of A]
  930. Even though the two loads of A both occur after the load of B, they may both
  931. come up with different values:
  932. +-------+ : : : :
  933. | | +------+ +-------+
  934. | |------>| A=1 |------ --->| A->0 |
  935. | | +------+ \ +-------+
  936. | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
  937. | | +------+ | +-------+
  938. | |------>| B=2 |--- | : :
  939. | | +------+ \ | : : +-------+
  940. +-------+ : : \ | +-------+ | |
  941. ---------->| B->2 |------>| |
  942. | +-------+ | CPU 2 |
  943. | : : | |
  944. | : : | |
  945. | +-------+ | |
  946. | | A->0 |------>| 1st |
  947. | +-------+ | |
  948. At this point the read ----> \ rrrrrrrrrrrrrrrrr | |
  949. barrier causes all effects \ +-------+ | |
  950. prior to the storage of B ---->| A->1 |------>| 2nd |
  951. to be perceptible to CPU 2 +-------+ | |
  952. : : +-------+
  953. But it may be that the update to A from CPU 1 becomes perceptible to CPU 2
  954. before the read barrier completes anyway:
  955. +-------+ : : : :
  956. | | +------+ +-------+
  957. | |------>| A=1 |------ --->| A->0 |
  958. | | +------+ \ +-------+
  959. | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
  960. | | +------+ | +-------+
  961. | |------>| B=2 |--- | : :
  962. | | +------+ \ | : : +-------+
  963. +-------+ : : \ | +-------+ | |
  964. ---------->| B->2 |------>| |
  965. | +-------+ | CPU 2 |
  966. | : : | |
  967. \ : : | |
  968. \ +-------+ | |
  969. ---->| A->1 |------>| 1st |
  970. +-------+ | |
  971. rrrrrrrrrrrrrrrrr | |
  972. +-------+ | |
  973. | A->1 |------>| 2nd |
  974. +-------+ | |
  975. : : +-------+
  976. The guarantee is that the second load will always come up with A == 1 if the
  977. load of B came up with B == 2. No such guarantee exists for the first load of
  978. A; that may come up with either A == 0 or A == 1.
  979. READ MEMORY BARRIERS VS LOAD SPECULATION
  980. ----------------------------------------
  981. Many CPUs speculate with loads: that is they see that they will need to load an
  982. item from memory, and they find a time where they're not using the bus for any
  983. other loads, and so do the load in advance - even though they haven't actually
  984. got to that point in the instruction execution flow yet. This permits the
  985. actual load instruction to potentially complete immediately because the CPU
  986. already has the value to hand.
  987. It may turn out that the CPU didn't actually need the value - perhaps because a
  988. branch circumvented the load - in which case it can discard the value or just
  989. cache it for later use.
  990. Consider:
  991. CPU 1 CPU 2
  992. ======================= =======================
  993. LOAD B
  994. DIVIDE } Divide instructions generally
  995. DIVIDE } take a long time to perform
  996. LOAD A
  997. Which might appear as this:
  998. : : +-------+
  999. +-------+ | |
  1000. --->| B->2 |------>| |
  1001. +-------+ | CPU 2 |
  1002. : :DIVIDE | |
  1003. +-------+ | |
  1004. The CPU being busy doing a ---> --->| A->0 |~~~~ | |
  1005. division speculates on the +-------+ ~ | |
  1006. LOAD of A : : ~ | |
  1007. : :DIVIDE | |
  1008. : : ~ | |
  1009. Once the divisions are complete --> : : ~-->| |
  1010. the CPU can then perform the : : | |
  1011. LOAD with immediate effect : : +-------+
  1012. Placing a read barrier or a data dependency barrier just before the second
  1013. load:
  1014. CPU 1 CPU 2
  1015. ======================= =======================
  1016. LOAD B
  1017. DIVIDE
  1018. DIVIDE
  1019. <read barrier>
  1020. LOAD A
  1021. will force any value speculatively obtained to be reconsidered to an extent
  1022. dependent on the type of barrier used. If there was no change made to the
  1023. speculated memory location, then the speculated value will just be used:
  1024. : : +-------+
  1025. +-------+ | |
  1026. --->| B->2 |------>| |
  1027. +-------+ | CPU 2 |
  1028. : :DIVIDE | |
  1029. +-------+ | |
  1030. The CPU being busy doing a ---> --->| A->0 |~~~~ | |
  1031. division speculates on the +-------+ ~ | |
  1032. LOAD of A : : ~ | |
  1033. : :DIVIDE | |
  1034. : : ~ | |
  1035. : : ~ | |
  1036. rrrrrrrrrrrrrrrr~ | |
  1037. : : ~ | |
  1038. : : ~-->| |
  1039. : : | |
  1040. : : +-------+
  1041. but if there was an update or an invalidation from another CPU pending, then
  1042. the speculation will be cancelled and the value reloaded:
  1043. : : +-------+
  1044. +-------+ | |
  1045. --->| B->2 |------>| |
  1046. +-------+ | CPU 2 |
  1047. : :DIVIDE | |
  1048. +-------+ | |
  1049. The CPU being busy doing a ---> --->| A->0 |~~~~ | |
  1050. division speculates on the +-------+ ~ | |
  1051. LOAD of A : : ~ | |
  1052. : :DIVIDE | |
  1053. : : ~ | |
  1054. : : ~ | |
  1055. rrrrrrrrrrrrrrrrr | |
  1056. +-------+ | |
  1057. The speculation is discarded ---> --->| A->1 |------>| |
  1058. and an updated value is +-------+ | |
  1059. retrieved : : +-------+
  1060. TRANSITIVITY
  1061. ------------
  1062. Transitivity is a deeply intuitive notion about ordering that is not
  1063. always provided by real computer systems. The following example
  1064. demonstrates transitivity:
  1065. CPU 1 CPU 2 CPU 3
  1066. ======================= ======================= =======================
  1067. { X = 0, Y = 0 }
  1068. STORE X=1 LOAD X STORE Y=1
  1069. <general barrier> <general barrier>
  1070. LOAD Y LOAD X
  1071. Suppose that CPU 2's load from X returns 1 and its load from Y returns 0.
  1072. This indicates that CPU 2's load from X in some sense follows CPU 1's
  1073. store to X and that CPU 2's load from Y in some sense preceded CPU 3's
  1074. store to Y. The question is then "Can CPU 3's load from X return 0?"
  1075. Because CPU 2's load from X in some sense came after CPU 1's store, it
  1076. is natural to expect that CPU 3's load from X must therefore return 1.
  1077. This expectation is an example of transitivity: if a load executing on
  1078. CPU A follows a load from the same variable executing on CPU B, then
  1079. CPU A's load must either return the same value that CPU B's load did,
  1080. or must return some later value.
  1081. In the Linux kernel, use of general memory barriers guarantees
  1082. transitivity. Therefore, in the above example, if CPU 2's load from X
  1083. returns 1 and its load from Y returns 0, then CPU 3's load from X must
  1084. also return 1.
  1085. However, transitivity is -not- guaranteed for read or write barriers.
  1086. For example, suppose that CPU 2's general barrier in the above example
  1087. is changed to a read barrier as shown below:
  1088. CPU 1 CPU 2 CPU 3
  1089. ======================= ======================= =======================
  1090. { X = 0, Y = 0 }
  1091. STORE X=1 LOAD X STORE Y=1
  1092. <read barrier> <general barrier>
  1093. LOAD Y LOAD X
  1094. This substitution destroys transitivity: in this example, it is perfectly
  1095. legal for CPU 2's load from X to return 1, its load from Y to return 0,
  1096. and CPU 3's load from X to return 0.
  1097. The key point is that although CPU 2's read barrier orders its pair
  1098. of loads, it does not guarantee to order CPU 1's store. Therefore, if
  1099. this example runs on a system where CPUs 1 and 2 share a store buffer
  1100. or a level of cache, CPU 2 might have early access to CPU 1's writes.
  1101. General barriers are therefore required to ensure that all CPUs agree
  1102. on the combined order of CPU 1's and CPU 2's accesses.
  1103. General barriers provide "global transitivity", so that all CPUs will
  1104. agree on the order of operations. In contrast, a chain of release-acquire
  1105. pairs provides only "local transitivity", so that only those CPUs on
  1106. the chain are guaranteed to agree on the combined order of the accesses.
  1107. For example, switching to C code in deference to Herman Hollerith:
  1108. int u, v, x, y, z;
  1109. void cpu0(void)
  1110. {
  1111. r0 = smp_load_acquire(&x);
  1112. WRITE_ONCE(u, 1);
  1113. smp_store_release(&y, 1);
  1114. }
  1115. void cpu1(void)
  1116. {
  1117. r1 = smp_load_acquire(&y);
  1118. r4 = READ_ONCE(v);
  1119. r5 = READ_ONCE(u);
  1120. smp_store_release(&z, 1);
  1121. }
  1122. void cpu2(void)
  1123. {
  1124. r2 = smp_load_acquire(&z);
  1125. smp_store_release(&x, 1);
  1126. }
  1127. void cpu3(void)
  1128. {
  1129. WRITE_ONCE(v, 1);
  1130. smp_mb();
  1131. r3 = READ_ONCE(u);
  1132. }
  1133. Because cpu0(), cpu1(), and cpu2() participate in a local transitive
  1134. chain of smp_store_release()/smp_load_acquire() pairs, the following
  1135. outcome is prohibited:
  1136. r0 == 1 && r1 == 1 && r2 == 1
  1137. Furthermore, because of the release-acquire relationship between cpu0()
  1138. and cpu1(), cpu1() must see cpu0()'s writes, so that the following
  1139. outcome is prohibited:
  1140. r1 == 1 && r5 == 0
  1141. However, the transitivity of release-acquire is local to the participating
  1142. CPUs and does not apply to cpu3(). Therefore, the following outcome
  1143. is possible:
  1144. r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0
  1145. As an aside, the following outcome is also possible:
  1146. r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0 && r5 == 1
  1147. Although cpu0(), cpu1(), and cpu2() will see their respective reads and
  1148. writes in order, CPUs not involved in the release-acquire chain might
  1149. well disagree on the order. This disagreement stems from the fact that
  1150. the weak memory-barrier instructions used to implement smp_load_acquire()
  1151. and smp_store_release() are not required to order prior stores against
  1152. subsequent loads in all cases. This means that cpu3() can see cpu0()'s
  1153. store to u as happening -after- cpu1()'s load from v, even though
  1154. both cpu0() and cpu1() agree that these two operations occurred in the
  1155. intended order.
  1156. However, please keep in mind that smp_load_acquire() is not magic.
  1157. In particular, it simply reads from its argument with ordering. It does
  1158. -not- ensure that any particular value will be read. Therefore, the
  1159. following outcome is possible:
  1160. r0 == 0 && r1 == 0 && r2 == 0 && r5 == 0
  1161. Note that this outcome can happen even on a mythical sequentially
  1162. consistent system where nothing is ever reordered.
  1163. To reiterate, if your code requires global transitivity, use general
  1164. barriers throughout.
  1165. ========================
  1166. EXPLICIT KERNEL BARRIERS
  1167. ========================
  1168. The Linux kernel has a variety of different barriers that act at different
  1169. levels:
  1170. (*) Compiler barrier.
  1171. (*) CPU memory barriers.
  1172. (*) MMIO write barrier.
  1173. COMPILER BARRIER
  1174. ----------------
  1175. The Linux kernel has an explicit compiler barrier function that prevents the
  1176. compiler from moving the memory accesses either side of it to the other side:
  1177. barrier();
  1178. This is a general barrier -- there are no read-read or write-write
  1179. variants of barrier(). However, READ_ONCE() and WRITE_ONCE() can be
  1180. thought of as weak forms of barrier() that affect only the specific
  1181. accesses flagged by the READ_ONCE() or WRITE_ONCE().
  1182. The barrier() function has the following effects:
  1183. (*) Prevents the compiler from reordering accesses following the
  1184. barrier() to precede any accesses preceding the barrier().
  1185. One example use for this property is to ease communication between
  1186. interrupt-handler code and the code that was interrupted.
  1187. (*) Within a loop, forces the compiler to load the variables used
  1188. in that loop's conditional on each pass through that loop.
  1189. The READ_ONCE() and WRITE_ONCE() functions can prevent any number of
  1190. optimizations that, while perfectly safe in single-threaded code, can
  1191. be fatal in concurrent code. Here are some examples of these sorts
  1192. of optimizations:
  1193. (*) The compiler is within its rights to reorder loads and stores
  1194. to the same variable, and in some cases, the CPU is within its
  1195. rights to reorder loads to the same variable. This means that
  1196. the following code:
  1197. a[0] = x;
  1198. a[1] = x;
  1199. Might result in an older value of x stored in a[1] than in a[0].
  1200. Prevent both the compiler and the CPU from doing this as follows:
  1201. a[0] = READ_ONCE(x);
  1202. a[1] = READ_ONCE(x);
  1203. In short, READ_ONCE() and WRITE_ONCE() provide cache coherence for
  1204. accesses from multiple CPUs to a single variable.
  1205. (*) The compiler is within its rights to merge successive loads from
  1206. the same variable. Such merging can cause the compiler to "optimize"
  1207. the following code:
  1208. while (tmp = a)
  1209. do_something_with(tmp);
  1210. into the following code, which, although in some sense legitimate
  1211. for single-threaded code, is almost certainly not what the developer
  1212. intended:
  1213. if (tmp = a)
  1214. for (;;)
  1215. do_something_with(tmp);
  1216. Use READ_ONCE() to prevent the compiler from doing this to you:
  1217. while (tmp = READ_ONCE(a))
  1218. do_something_with(tmp);
  1219. (*) The compiler is within its rights to reload a variable, for example,
  1220. in cases where high register pressure prevents the compiler from
  1221. keeping all data of interest in registers. The compiler might
  1222. therefore optimize the variable 'tmp' out of our previous example:
  1223. while (tmp = a)
  1224. do_something_with(tmp);
  1225. This could result in the following code, which is perfectly safe in
  1226. single-threaded code, but can be fatal in concurrent code:
  1227. while (a)
  1228. do_something_with(a);
  1229. For example, the optimized version of this code could result in
  1230. passing a zero to do_something_with() in the case where the variable
  1231. a was modified by some other CPU between the "while" statement and
  1232. the call to do_something_with().
  1233. Again, use READ_ONCE() to prevent the compiler from doing this:
  1234. while (tmp = READ_ONCE(a))
  1235. do_something_with(tmp);
  1236. Note that if the compiler runs short of registers, it might save
  1237. tmp onto the stack. The overhead of this saving and later restoring
  1238. is why compilers reload variables. Doing so is perfectly safe for
  1239. single-threaded code, so you need to tell the compiler about cases
  1240. where it is not safe.
  1241. (*) The compiler is within its rights to omit a load entirely if it knows
  1242. what the value will be. For example, if the compiler can prove that
  1243. the value of variable 'a' is always zero, it can optimize this code:
  1244. while (tmp = a)
  1245. do_something_with(tmp);
  1246. Into this:
  1247. do { } while (0);
  1248. This transformation is a win for single-threaded code because it
  1249. gets rid of a load and a branch. The problem is that the compiler
  1250. will carry out its proof assuming that the current CPU is the only
  1251. one updating variable 'a'. If variable 'a' is shared, then the
  1252. compiler's proof will be erroneous. Use READ_ONCE() to tell the
  1253. compiler that it doesn't know as much as it thinks it does:
  1254. while (tmp = READ_ONCE(a))
  1255. do_something_with(tmp);
  1256. But please note that the compiler is also closely watching what you
  1257. do with the value after the READ_ONCE(). For example, suppose you
  1258. do the following and MAX is a preprocessor macro with the value 1:
  1259. while ((tmp = READ_ONCE(a)) % MAX)
  1260. do_something_with(tmp);
  1261. Then the compiler knows that the result of the "%" operator applied
  1262. to MAX will always be zero, again allowing the compiler to optimize
  1263. the code into near-nonexistence. (It will still load from the
  1264. variable 'a'.)
  1265. (*) Similarly, the compiler is within its rights to omit a store entirely
  1266. if it knows that the variable already has the value being stored.
  1267. Again, the compiler assumes that the current CPU is the only one
  1268. storing into the variable, which can cause the compiler to do the
  1269. wrong thing for shared variables. For example, suppose you have
  1270. the following:
  1271. a = 0;
  1272. ... Code that does not store to variable a ...
  1273. a = 0;
  1274. The compiler sees that the value of variable 'a' is already zero, so
  1275. it might well omit the second store. This would come as a fatal
  1276. surprise if some other CPU might have stored to variable 'a' in the
  1277. meantime.
  1278. Use WRITE_ONCE() to prevent the compiler from making this sort of
  1279. wrong guess:
  1280. WRITE_ONCE(a, 0);
  1281. ... Code that does not store to variable a ...
  1282. WRITE_ONCE(a, 0);
  1283. (*) The compiler is within its rights to reorder memory accesses unless
  1284. you tell it not to. For example, consider the following interaction
  1285. between process-level code and an interrupt handler:
  1286. void process_level(void)
  1287. {
  1288. msg = get_message();
  1289. flag = true;
  1290. }
  1291. void interrupt_handler(void)
  1292. {
  1293. if (flag)
  1294. process_message(msg);
  1295. }
  1296. There is nothing to prevent the compiler from transforming
  1297. process_level() to the following, in fact, this might well be a
  1298. win for single-threaded code:
  1299. void process_level(void)
  1300. {
  1301. flag = true;
  1302. msg = get_message();
  1303. }
  1304. If the interrupt occurs between these two statement, then
  1305. interrupt_handler() might be passed a garbled msg. Use WRITE_ONCE()
  1306. to prevent this as follows:
  1307. void process_level(void)
  1308. {
  1309. WRITE_ONCE(msg, get_message());
  1310. WRITE_ONCE(flag, true);
  1311. }
  1312. void interrupt_handler(void)
  1313. {
  1314. if (READ_ONCE(flag))
  1315. process_message(READ_ONCE(msg));
  1316. }
  1317. Note that the READ_ONCE() and WRITE_ONCE() wrappers in
  1318. interrupt_handler() are needed if this interrupt handler can itself
  1319. be interrupted by something that also accesses 'flag' and 'msg',
  1320. for example, a nested interrupt or an NMI. Otherwise, READ_ONCE()
  1321. and WRITE_ONCE() are not needed in interrupt_handler() other than
  1322. for documentation purposes. (Note also that nested interrupts
  1323. do not typically occur in modern Linux kernels, in fact, if an
  1324. interrupt handler returns with interrupts enabled, you will get a
  1325. WARN_ONCE() splat.)
  1326. You should assume that the compiler can move READ_ONCE() and
  1327. WRITE_ONCE() past code not containing READ_ONCE(), WRITE_ONCE(),
  1328. barrier(), or similar primitives.
  1329. This effect could also be achieved using barrier(), but READ_ONCE()
  1330. and WRITE_ONCE() are more selective: With READ_ONCE() and
  1331. WRITE_ONCE(), the compiler need only forget the contents of the
  1332. indicated memory locations, while with barrier() the compiler must
  1333. discard the value of all memory locations that it has currented
  1334. cached in any machine registers. Of course, the compiler must also
  1335. respect the order in which the READ_ONCE()s and WRITE_ONCE()s occur,
  1336. though the CPU of course need not do so.
  1337. (*) The compiler is within its rights to invent stores to a variable,
  1338. as in the following example:
  1339. if (a)
  1340. b = a;
  1341. else
  1342. b = 42;
  1343. The compiler might save a branch by optimizing this as follows:
  1344. b = 42;
  1345. if (a)
  1346. b = a;
  1347. In single-threaded code, this is not only safe, but also saves
  1348. a branch. Unfortunately, in concurrent code, this optimization
  1349. could cause some other CPU to see a spurious value of 42 -- even
  1350. if variable 'a' was never zero -- when loading variable 'b'.
  1351. Use WRITE_ONCE() to prevent this as follows:
  1352. if (a)
  1353. WRITE_ONCE(b, a);
  1354. else
  1355. WRITE_ONCE(b, 42);
  1356. The compiler can also invent loads. These are usually less
  1357. damaging, but they can result in cache-line bouncing and thus in
  1358. poor performance and scalability. Use READ_ONCE() to prevent
  1359. invented loads.
  1360. (*) For aligned memory locations whose size allows them to be accessed
  1361. with a single memory-reference instruction, prevents "load tearing"
  1362. and "store tearing," in which a single large access is replaced by
  1363. multiple smaller accesses. For example, given an architecture having
  1364. 16-bit store instructions with 7-bit immediate fields, the compiler
  1365. might be tempted to use two 16-bit store-immediate instructions to
  1366. implement the following 32-bit store:
  1367. p = 0x00010002;
  1368. Please note that GCC really does use this sort of optimization,
  1369. which is not surprising given that it would likely take more
  1370. than two instructions to build the constant and then store it.
  1371. This optimization can therefore be a win in single-threaded code.
  1372. In fact, a recent bug (since fixed) caused GCC to incorrectly use
  1373. this optimization in a volatile store. In the absence of such bugs,
  1374. use of WRITE_ONCE() prevents store tearing in the following example:
  1375. WRITE_ONCE(p, 0x00010002);
  1376. Use of packed structures can also result in load and store tearing,
  1377. as in this example:
  1378. struct __attribute__((__packed__)) foo {
  1379. short a;
  1380. int b;
  1381. short c;
  1382. };
  1383. struct foo foo1, foo2;
  1384. ...
  1385. foo2.a = foo1.a;
  1386. foo2.b = foo1.b;
  1387. foo2.c = foo1.c;
  1388. Because there are no READ_ONCE() or WRITE_ONCE() wrappers and no
  1389. volatile markings, the compiler would be well within its rights to
  1390. implement these three assignment statements as a pair of 32-bit
  1391. loads followed by a pair of 32-bit stores. This would result in
  1392. load tearing on 'foo1.b' and store tearing on 'foo2.b'. READ_ONCE()
  1393. and WRITE_ONCE() again prevent tearing in this example:
  1394. foo2.a = foo1.a;
  1395. WRITE_ONCE(foo2.b, READ_ONCE(foo1.b));
  1396. foo2.c = foo1.c;
  1397. All that aside, it is never necessary to use READ_ONCE() and
  1398. WRITE_ONCE() on a variable that has been marked volatile. For example,
  1399. because 'jiffies' is marked volatile, it is never necessary to
  1400. say READ_ONCE(jiffies). The reason for this is that READ_ONCE() and
  1401. WRITE_ONCE() are implemented as volatile casts, which has no effect when
  1402. its argument is already marked volatile.
  1403. Please note that these compiler barriers have no direct effect on the CPU,
  1404. which may then reorder things however it wishes.
  1405. CPU MEMORY BARRIERS
  1406. -------------------
  1407. The Linux kernel has eight basic CPU memory barriers:
  1408. TYPE MANDATORY SMP CONDITIONAL
  1409. =============== ======================= ===========================
  1410. GENERAL mb() smp_mb()
  1411. WRITE wmb() smp_wmb()
  1412. READ rmb() smp_rmb()
  1413. DATA DEPENDENCY read_barrier_depends() smp_read_barrier_depends()
  1414. All memory barriers except the data dependency barriers imply a compiler
  1415. barrier. Data dependencies do not impose any additional compiler ordering.
  1416. Aside: In the case of data dependencies, the compiler would be expected
  1417. to issue the loads in the correct order (eg. `a[b]` would have to load
  1418. the value of b before loading a[b]), however there is no guarantee in
  1419. the C specification that the compiler may not speculate the value of b
  1420. (eg. is equal to 1) and load a before b (eg. tmp = a[1]; if (b != 1)
  1421. tmp = a[b]; ). There is also the problem of a compiler reloading b after
  1422. having loaded a[b], thus having a newer copy of b than a[b]. A consensus
  1423. has not yet been reached about these problems, however the READ_ONCE()
  1424. macro is a good place to start looking.
  1425. SMP memory barriers are reduced to compiler barriers on uniprocessor compiled
  1426. systems because it is assumed that a CPU will appear to be self-consistent,
  1427. and will order overlapping accesses correctly with respect to itself.
  1428. However, see the subsection on "Virtual Machine Guests" below.
  1429. [!] Note that SMP memory barriers _must_ be used to control the ordering of
  1430. references to shared memory on SMP systems, though the use of locking instead
  1431. is sufficient.
  1432. Mandatory barriers should not be used to control SMP effects, since mandatory
  1433. barriers impose unnecessary overhead on both SMP and UP systems. They may,
  1434. however, be used to control MMIO effects on accesses through relaxed memory I/O
  1435. windows. These barriers are required even on non-SMP systems as they affect
  1436. the order in which memory operations appear to a device by prohibiting both the
  1437. compiler and the CPU from reordering them.
  1438. There are some more advanced barrier functions:
  1439. (*) smp_store_mb(var, value)
  1440. This assigns the value to the variable and then inserts a full memory
  1441. barrier after it. It isn't guaranteed to insert anything more than a
  1442. compiler barrier in a UP compilation.
  1443. (*) smp_mb__before_atomic();
  1444. (*) smp_mb__after_atomic();
  1445. These are for use with atomic (such as add, subtract, increment and
  1446. decrement) functions that don't return a value, especially when used for
  1447. reference counting. These functions do not imply memory barriers.
  1448. These are also used for atomic bitop functions that do not return a
  1449. value (such as set_bit and clear_bit).
  1450. As an example, consider a piece of code that marks an object as being dead
  1451. and then decrements the object's reference count:
  1452. obj->dead = 1;
  1453. smp_mb__before_atomic();
  1454. atomic_dec(&obj->ref_count);
  1455. This makes sure that the death mark on the object is perceived to be set
  1456. *before* the reference counter is decremented.
  1457. See Documentation/atomic_{t,bitops}.txt for more information.
  1458. (*) lockless_dereference();
  1459. This can be thought of as a pointer-fetch wrapper around the
  1460. smp_read_barrier_depends() data-dependency barrier.
  1461. This is also similar to rcu_dereference(), but in cases where
  1462. object lifetime is handled by some mechanism other than RCU, for
  1463. example, when the objects removed only when the system goes down.
  1464. In addition, lockless_dereference() is used in some data structures
  1465. that can be used both with and without RCU.
  1466. (*) dma_wmb();
  1467. (*) dma_rmb();
  1468. These are for use with consistent memory to guarantee the ordering
  1469. of writes or reads of shared memory accessible to both the CPU and a
  1470. DMA capable device.
  1471. For example, consider a device driver that shares memory with a device
  1472. and uses a descriptor status value to indicate if the descriptor belongs
  1473. to the device or the CPU, and a doorbell to notify it when new
  1474. descriptors are available:
  1475. if (desc->status != DEVICE_OWN) {
  1476. /* do not read data until we own descriptor */
  1477. dma_rmb();
  1478. /* read/modify data */
  1479. read_data = desc->data;
  1480. desc->data = write_data;
  1481. /* flush modifications before status update */
  1482. dma_wmb();
  1483. /* assign ownership */
  1484. desc->status = DEVICE_OWN;
  1485. /* force memory to sync before notifying device via MMIO */
  1486. wmb();
  1487. /* notify device of new descriptors */
  1488. writel(DESC_NOTIFY, doorbell);
  1489. }
  1490. The dma_rmb() allows us guarantee the device has released ownership
  1491. before we read the data from the descriptor, and the dma_wmb() allows
  1492. us to guarantee the data is written to the descriptor before the device
  1493. can see it now has ownership. The wmb() is needed to guarantee that the
  1494. cache coherent memory writes have completed before attempting a write to
  1495. the cache incoherent MMIO region.
  1496. See Documentation/DMA-API.txt for more information on consistent memory.
  1497. MMIO WRITE BARRIER
  1498. ------------------
  1499. The Linux kernel also has a special barrier for use with memory-mapped I/O
  1500. writes:
  1501. mmiowb();
  1502. This is a variation on the mandatory write barrier that causes writes to weakly
  1503. ordered I/O regions to be partially ordered. Its effects may go beyond the
  1504. CPU->Hardware interface and actually affect the hardware at some level.
  1505. See the subsection "Acquires vs I/O accesses" for more information.
  1506. ===============================
  1507. IMPLICIT KERNEL MEMORY BARRIERS
  1508. ===============================
  1509. Some of the other functions in the linux kernel imply memory barriers, amongst
  1510. which are locking and scheduling functions.
  1511. This specification is a _minimum_ guarantee; any particular architecture may
  1512. provide more substantial guarantees, but these may not be relied upon outside
  1513. of arch specific code.
  1514. LOCK ACQUISITION FUNCTIONS
  1515. --------------------------
  1516. The Linux kernel has a number of locking constructs:
  1517. (*) spin locks
  1518. (*) R/W spin locks
  1519. (*) mutexes
  1520. (*) semaphores
  1521. (*) R/W semaphores
  1522. In all cases there are variants on "ACQUIRE" operations and "RELEASE" operations
  1523. for each construct. These operations all imply certain barriers:
  1524. (1) ACQUIRE operation implication:
  1525. Memory operations issued after the ACQUIRE will be completed after the
  1526. ACQUIRE operation has completed.
  1527. Memory operations issued before the ACQUIRE may be completed after
  1528. the ACQUIRE operation has completed.
  1529. (2) RELEASE operation implication:
  1530. Memory operations issued before the RELEASE will be completed before the
  1531. RELEASE operation has completed.
  1532. Memory operations issued after the RELEASE may be completed before the
  1533. RELEASE operation has completed.
  1534. (3) ACQUIRE vs ACQUIRE implication:
  1535. All ACQUIRE operations issued before another ACQUIRE operation will be
  1536. completed before that ACQUIRE operation.
  1537. (4) ACQUIRE vs RELEASE implication:
  1538. All ACQUIRE operations issued before a RELEASE operation will be
  1539. completed before the RELEASE operation.
  1540. (5) Failed conditional ACQUIRE implication:
  1541. Certain locking variants of the ACQUIRE operation may fail, either due to
  1542. being unable to get the lock immediately, or due to receiving an unblocked
  1543. signal whilst asleep waiting for the lock to become available. Failed
  1544. locks do not imply any sort of barrier.
  1545. [!] Note: one of the consequences of lock ACQUIREs and RELEASEs being only
  1546. one-way barriers is that the effects of instructions outside of a critical
  1547. section may seep into the inside of the critical section.
  1548. An ACQUIRE followed by a RELEASE may not be assumed to be full memory barrier
  1549. because it is possible for an access preceding the ACQUIRE to happen after the
  1550. ACQUIRE, and an access following the RELEASE to happen before the RELEASE, and
  1551. the two accesses can themselves then cross:
  1552. *A = a;
  1553. ACQUIRE M
  1554. RELEASE M
  1555. *B = b;
  1556. may occur as:
  1557. ACQUIRE M, STORE *B, STORE *A, RELEASE M
  1558. When the ACQUIRE and RELEASE are a lock acquisition and release,
  1559. respectively, this same reordering can occur if the lock's ACQUIRE and
  1560. RELEASE are to the same lock variable, but only from the perspective of
  1561. another CPU not holding that lock. In short, a ACQUIRE followed by an
  1562. RELEASE may -not- be assumed to be a full memory barrier.
  1563. Similarly, the reverse case of a RELEASE followed by an ACQUIRE does
  1564. not imply a full memory barrier. Therefore, the CPU's execution of the
  1565. critical sections corresponding to the RELEASE and the ACQUIRE can cross,
  1566. so that:
  1567. *A = a;
  1568. RELEASE M
  1569. ACQUIRE N
  1570. *B = b;
  1571. could occur as:
  1572. ACQUIRE N, STORE *B, STORE *A, RELEASE M
  1573. It might appear that this reordering could introduce a deadlock.
  1574. However, this cannot happen because if such a deadlock threatened,
  1575. the RELEASE would simply complete, thereby avoiding the deadlock.
  1576. Why does this work?
  1577. One key point is that we are only talking about the CPU doing
  1578. the reordering, not the compiler. If the compiler (or, for
  1579. that matter, the developer) switched the operations, deadlock
  1580. -could- occur.
  1581. But suppose the CPU reordered the operations. In this case,
  1582. the unlock precedes the lock in the assembly code. The CPU
  1583. simply elected to try executing the later lock operation first.
  1584. If there is a deadlock, this lock operation will simply spin (or
  1585. try to sleep, but more on that later). The CPU will eventually
  1586. execute the unlock operation (which preceded the lock operation
  1587. in the assembly code), which will unravel the potential deadlock,
  1588. allowing the lock operation to succeed.
  1589. But what if the lock is a sleeplock? In that case, the code will
  1590. try to enter the scheduler, where it will eventually encounter
  1591. a memory barrier, which will force the earlier unlock operation
  1592. to complete, again unraveling the deadlock. There might be
  1593. a sleep-unlock race, but the locking primitive needs to resolve
  1594. such races properly in any case.
  1595. Locks and semaphores may not provide any guarantee of ordering on UP compiled
  1596. systems, and so cannot be counted on in such a situation to actually achieve
  1597. anything at all - especially with respect to I/O accesses - unless combined
  1598. with interrupt disabling operations.
  1599. See also the section on "Inter-CPU acquiring barrier effects".
  1600. As an example, consider the following:
  1601. *A = a;
  1602. *B = b;
  1603. ACQUIRE
  1604. *C = c;
  1605. *D = d;
  1606. RELEASE
  1607. *E = e;
  1608. *F = f;
  1609. The following sequence of events is acceptable:
  1610. ACQUIRE, {*F,*A}, *E, {*C,*D}, *B, RELEASE
  1611. [+] Note that {*F,*A} indicates a combined access.
  1612. But none of the following are:
  1613. {*F,*A}, *B, ACQUIRE, *C, *D, RELEASE, *E
  1614. *A, *B, *C, ACQUIRE, *D, RELEASE, *E, *F
  1615. *A, *B, ACQUIRE, *C, RELEASE, *D, *E, *F
  1616. *B, ACQUIRE, *C, *D, RELEASE, {*F,*A}, *E
  1617. INTERRUPT DISABLING FUNCTIONS
  1618. -----------------------------
  1619. Functions that disable interrupts (ACQUIRE equivalent) and enable interrupts
  1620. (RELEASE equivalent) will act as compiler barriers only. So if memory or I/O
  1621. barriers are required in such a situation, they must be provided from some
  1622. other means.
  1623. SLEEP AND WAKE-UP FUNCTIONS
  1624. ---------------------------
  1625. Sleeping and waking on an event flagged in global data can be viewed as an
  1626. interaction between two pieces of data: the task state of the task waiting for
  1627. the event and the global data used to indicate the event. To make sure that
  1628. these appear to happen in the right order, the primitives to begin the process
  1629. of going to sleep, and the primitives to initiate a wake up imply certain
  1630. barriers.
  1631. Firstly, the sleeper normally follows something like this sequence of events:
  1632. for (;;) {
  1633. set_current_state(TASK_UNINTERRUPTIBLE);
  1634. if (event_indicated)
  1635. break;
  1636. schedule();
  1637. }
  1638. A general memory barrier is interpolated automatically by set_current_state()
  1639. after it has altered the task state:
  1640. CPU 1
  1641. ===============================
  1642. set_current_state();
  1643. smp_store_mb();
  1644. STORE current->state
  1645. <general barrier>
  1646. LOAD event_indicated
  1647. set_current_state() may be wrapped by:
  1648. prepare_to_wait();
  1649. prepare_to_wait_exclusive();
  1650. which therefore also imply a general memory barrier after setting the state.
  1651. The whole sequence above is available in various canned forms, all of which
  1652. interpolate the memory barrier in the right place:
  1653. wait_event();
  1654. wait_event_interruptible();
  1655. wait_event_interruptible_exclusive();
  1656. wait_event_interruptible_timeout();
  1657. wait_event_killable();
  1658. wait_event_timeout();
  1659. wait_on_bit();
  1660. wait_on_bit_lock();
  1661. Secondly, code that performs a wake up normally follows something like this:
  1662. event_indicated = 1;
  1663. wake_up(&event_wait_queue);
  1664. or:
  1665. event_indicated = 1;
  1666. wake_up_process(event_daemon);
  1667. A write memory barrier is implied by wake_up() and co. if and only if they
  1668. wake something up. The barrier occurs before the task state is cleared, and so
  1669. sits between the STORE to indicate the event and the STORE to set TASK_RUNNING:
  1670. CPU 1 CPU 2
  1671. =============================== ===============================
  1672. set_current_state(); STORE event_indicated
  1673. smp_store_mb(); wake_up();
  1674. STORE current->state <write barrier>
  1675. <general barrier> STORE current->state
  1676. LOAD event_indicated
  1677. To repeat, this write memory barrier is present if and only if something
  1678. is actually awakened. To see this, consider the following sequence of
  1679. events, where X and Y are both initially zero:
  1680. CPU 1 CPU 2
  1681. =============================== ===============================
  1682. X = 1; STORE event_indicated
  1683. smp_mb(); wake_up();
  1684. Y = 1; wait_event(wq, Y == 1);
  1685. wake_up(); load from Y sees 1, no memory barrier
  1686. load from X might see 0
  1687. In contrast, if a wakeup does occur, CPU 2's load from X would be guaranteed
  1688. to see 1.
  1689. The available waker functions include:
  1690. complete();
  1691. wake_up();
  1692. wake_up_all();
  1693. wake_up_bit();
  1694. wake_up_interruptible();
  1695. wake_up_interruptible_all();
  1696. wake_up_interruptible_nr();
  1697. wake_up_interruptible_poll();
  1698. wake_up_interruptible_sync();
  1699. wake_up_interruptible_sync_poll();
  1700. wake_up_locked();
  1701. wake_up_locked_poll();
  1702. wake_up_nr();
  1703. wake_up_poll();
  1704. wake_up_process();
  1705. [!] Note that the memory barriers implied by the sleeper and the waker do _not_
  1706. order multiple stores before the wake-up with respect to loads of those stored
  1707. values after the sleeper has called set_current_state(). For instance, if the
  1708. sleeper does:
  1709. set_current_state(TASK_INTERRUPTIBLE);
  1710. if (event_indicated)
  1711. break;
  1712. __set_current_state(TASK_RUNNING);
  1713. do_something(my_data);
  1714. and the waker does:
  1715. my_data = value;
  1716. event_indicated = 1;
  1717. wake_up(&event_wait_queue);
  1718. there's no guarantee that the change to event_indicated will be perceived by
  1719. the sleeper as coming after the change to my_data. In such a circumstance, the
  1720. code on both sides must interpolate its own memory barriers between the
  1721. separate data accesses. Thus the above sleeper ought to do:
  1722. set_current_state(TASK_INTERRUPTIBLE);
  1723. if (event_indicated) {
  1724. smp_rmb();
  1725. do_something(my_data);
  1726. }
  1727. and the waker should do:
  1728. my_data = value;
  1729. smp_wmb();
  1730. event_indicated = 1;
  1731. wake_up(&event_wait_queue);
  1732. MISCELLANEOUS FUNCTIONS
  1733. -----------------------
  1734. Other functions that imply barriers:
  1735. (*) schedule() and similar imply full memory barriers.
  1736. ===================================
  1737. INTER-CPU ACQUIRING BARRIER EFFECTS
  1738. ===================================
  1739. On SMP systems locking primitives give a more substantial form of barrier: one
  1740. that does affect memory access ordering on other CPUs, within the context of
  1741. conflict on any particular lock.
  1742. ACQUIRES VS MEMORY ACCESSES
  1743. ---------------------------
  1744. Consider the following: the system has a pair of spinlocks (M) and (Q), and
  1745. three CPUs; then should the following sequence of events occur:
  1746. CPU 1 CPU 2
  1747. =============================== ===============================
  1748. WRITE_ONCE(*A, a); WRITE_ONCE(*E, e);
  1749. ACQUIRE M ACQUIRE Q
  1750. WRITE_ONCE(*B, b); WRITE_ONCE(*F, f);
  1751. WRITE_ONCE(*C, c); WRITE_ONCE(*G, g);
  1752. RELEASE M RELEASE Q
  1753. WRITE_ONCE(*D, d); WRITE_ONCE(*H, h);
  1754. Then there is no guarantee as to what order CPU 3 will see the accesses to *A
  1755. through *H occur in, other than the constraints imposed by the separate locks
  1756. on the separate CPUs. It might, for example, see:
  1757. *E, ACQUIRE M, ACQUIRE Q, *G, *C, *F, *A, *B, RELEASE Q, *D, *H, RELEASE M
  1758. But it won't see any of:
  1759. *B, *C or *D preceding ACQUIRE M
  1760. *A, *B or *C following RELEASE M
  1761. *F, *G or *H preceding ACQUIRE Q
  1762. *E, *F or *G following RELEASE Q
  1763. ACQUIRES VS I/O ACCESSES
  1764. ------------------------
  1765. Under certain circumstances (especially involving NUMA), I/O accesses within
  1766. two spinlocked sections on two different CPUs may be seen as interleaved by the
  1767. PCI bridge, because the PCI bridge does not necessarily participate in the
  1768. cache-coherence protocol, and is therefore incapable of issuing the required
  1769. read memory barriers.
  1770. For example:
  1771. CPU 1 CPU 2
  1772. =============================== ===============================
  1773. spin_lock(Q)
  1774. writel(0, ADDR)
  1775. writel(1, DATA);
  1776. spin_unlock(Q);
  1777. spin_lock(Q);
  1778. writel(4, ADDR);
  1779. writel(5, DATA);
  1780. spin_unlock(Q);
  1781. may be seen by the PCI bridge as follows:
  1782. STORE *ADDR = 0, STORE *ADDR = 4, STORE *DATA = 1, STORE *DATA = 5
  1783. which would probably cause the hardware to malfunction.
  1784. What is necessary here is to intervene with an mmiowb() before dropping the
  1785. spinlock, for example:
  1786. CPU 1 CPU 2
  1787. =============================== ===============================
  1788. spin_lock(Q)
  1789. writel(0, ADDR)
  1790. writel(1, DATA);
  1791. mmiowb();
  1792. spin_unlock(Q);
  1793. spin_lock(Q);
  1794. writel(4, ADDR);
  1795. writel(5, DATA);
  1796. mmiowb();
  1797. spin_unlock(Q);
  1798. this will ensure that the two stores issued on CPU 1 appear at the PCI bridge
  1799. before either of the stores issued on CPU 2.
  1800. Furthermore, following a store by a load from the same device obviates the need
  1801. for the mmiowb(), because the load forces the store to complete before the load
  1802. is performed:
  1803. CPU 1 CPU 2
  1804. =============================== ===============================
  1805. spin_lock(Q)
  1806. writel(0, ADDR)
  1807. a = readl(DATA);
  1808. spin_unlock(Q);
  1809. spin_lock(Q);
  1810. writel(4, ADDR);
  1811. b = readl(DATA);
  1812. spin_unlock(Q);
  1813. See Documentation/driver-api/device-io.rst for more information.
  1814. =================================
  1815. WHERE ARE MEMORY BARRIERS NEEDED?
  1816. =================================
  1817. Under normal operation, memory operation reordering is generally not going to
  1818. be a problem as a single-threaded linear piece of code will still appear to
  1819. work correctly, even if it's in an SMP kernel. There are, however, four
  1820. circumstances in which reordering definitely _could_ be a problem:
  1821. (*) Interprocessor interaction.
  1822. (*) Atomic operations.
  1823. (*) Accessing devices.
  1824. (*) Interrupts.
  1825. INTERPROCESSOR INTERACTION
  1826. --------------------------
  1827. When there's a system with more than one processor, more than one CPU in the
  1828. system may be working on the same data set at the same time. This can cause
  1829. synchronisation problems, and the usual way of dealing with them is to use
  1830. locks. Locks, however, are quite expensive, and so it may be preferable to
  1831. operate without the use of a lock if at all possible. In such a case
  1832. operations that affect both CPUs may have to be carefully ordered to prevent
  1833. a malfunction.
  1834. Consider, for example, the R/W semaphore slow path. Here a waiting process is
  1835. queued on the semaphore, by virtue of it having a piece of its stack linked to
  1836. the semaphore's list of waiting processes:
  1837. struct rw_semaphore {
  1838. ...
  1839. spinlock_t lock;
  1840. struct list_head waiters;
  1841. };
  1842. struct rwsem_waiter {
  1843. struct list_head list;
  1844. struct task_struct *task;
  1845. };
  1846. To wake up a particular waiter, the up_read() or up_write() functions have to:
  1847. (1) read the next pointer from this waiter's record to know as to where the
  1848. next waiter record is;
  1849. (2) read the pointer to the waiter's task structure;
  1850. (3) clear the task pointer to tell the waiter it has been given the semaphore;
  1851. (4) call wake_up_process() on the task; and
  1852. (5) release the reference held on the waiter's task struct.
  1853. In other words, it has to perform this sequence of events:
  1854. LOAD waiter->list.next;
  1855. LOAD waiter->task;
  1856. STORE waiter->task;
  1857. CALL wakeup
  1858. RELEASE task
  1859. and if any of these steps occur out of order, then the whole thing may
  1860. malfunction.
  1861. Once it has queued itself and dropped the semaphore lock, the waiter does not
  1862. get the lock again; it instead just waits for its task pointer to be cleared
  1863. before proceeding. Since the record is on the waiter's stack, this means that
  1864. if the task pointer is cleared _before_ the next pointer in the list is read,
  1865. another CPU might start processing the waiter and might clobber the waiter's
  1866. stack before the up*() function has a chance to read the next pointer.
  1867. Consider then what might happen to the above sequence of events:
  1868. CPU 1 CPU 2
  1869. =============================== ===============================
  1870. down_xxx()
  1871. Queue waiter
  1872. Sleep
  1873. up_yyy()
  1874. LOAD waiter->task;
  1875. STORE waiter->task;
  1876. Woken up by other event
  1877. <preempt>
  1878. Resume processing
  1879. down_xxx() returns
  1880. call foo()
  1881. foo() clobbers *waiter
  1882. </preempt>
  1883. LOAD waiter->list.next;
  1884. --- OOPS ---
  1885. This could be dealt with using the semaphore lock, but then the down_xxx()
  1886. function has to needlessly get the spinlock again after being woken up.
  1887. The way to deal with this is to insert a general SMP memory barrier:
  1888. LOAD waiter->list.next;
  1889. LOAD waiter->task;
  1890. smp_mb();
  1891. STORE waiter->task;
  1892. CALL wakeup
  1893. RELEASE task
  1894. In this case, the barrier makes a guarantee that all memory accesses before the
  1895. barrier will appear to happen before all the memory accesses after the barrier
  1896. with respect to the other CPUs on the system. It does _not_ guarantee that all
  1897. the memory accesses before the barrier will be complete by the time the barrier
  1898. instruction itself is complete.
  1899. On a UP system - where this wouldn't be a problem - the smp_mb() is just a
  1900. compiler barrier, thus making sure the compiler emits the instructions in the
  1901. right order without actually intervening in the CPU. Since there's only one
  1902. CPU, that CPU's dependency ordering logic will take care of everything else.
  1903. ATOMIC OPERATIONS
  1904. -----------------
  1905. Whilst they are technically interprocessor interaction considerations, atomic
  1906. operations are noted specially as some of them imply full memory barriers and
  1907. some don't, but they're very heavily relied on as a group throughout the
  1908. kernel.
  1909. See Documentation/atomic_t.txt for more information.
  1910. ACCESSING DEVICES
  1911. -----------------
  1912. Many devices can be memory mapped, and so appear to the CPU as if they're just
  1913. a set of memory locations. To control such a device, the driver usually has to
  1914. make the right memory accesses in exactly the right order.
  1915. However, having a clever CPU or a clever compiler creates a potential problem
  1916. in that the carefully sequenced accesses in the driver code won't reach the
  1917. device in the requisite order if the CPU or the compiler thinks it is more
  1918. efficient to reorder, combine or merge accesses - something that would cause
  1919. the device to malfunction.
  1920. Inside of the Linux kernel, I/O should be done through the appropriate accessor
  1921. routines - such as inb() or writel() - which know how to make such accesses
  1922. appropriately sequential. Whilst this, for the most part, renders the explicit
  1923. use of memory barriers unnecessary, there are a couple of situations where they
  1924. might be needed:
  1925. (1) On some systems, I/O stores are not strongly ordered across all CPUs, and
  1926. so for _all_ general drivers locks should be used and mmiowb() must be
  1927. issued prior to unlocking the critical section.
  1928. (2) If the accessor functions are used to refer to an I/O memory window with
  1929. relaxed memory access properties, then _mandatory_ memory barriers are
  1930. required to enforce ordering.
  1931. See Documentation/driver-api/device-io.rst for more information.
  1932. INTERRUPTS
  1933. ----------
  1934. A driver may be interrupted by its own interrupt service routine, and thus the
  1935. two parts of the driver may interfere with each other's attempts to control or
  1936. access the device.
  1937. This may be alleviated - at least in part - by disabling local interrupts (a
  1938. form of locking), such that the critical operations are all contained within
  1939. the interrupt-disabled section in the driver. Whilst the driver's interrupt
  1940. routine is executing, the driver's core may not run on the same CPU, and its
  1941. interrupt is not permitted to happen again until the current interrupt has been
  1942. handled, thus the interrupt handler does not need to lock against that.
  1943. However, consider a driver that was talking to an ethernet card that sports an
  1944. address register and a data register. If that driver's core talks to the card
  1945. under interrupt-disablement and then the driver's interrupt handler is invoked:
  1946. LOCAL IRQ DISABLE
  1947. writew(ADDR, 3);
  1948. writew(DATA, y);
  1949. LOCAL IRQ ENABLE
  1950. <interrupt>
  1951. writew(ADDR, 4);
  1952. q = readw(DATA);
  1953. </interrupt>
  1954. The store to the data register might happen after the second store to the
  1955. address register if ordering rules are sufficiently relaxed:
  1956. STORE *ADDR = 3, STORE *ADDR = 4, STORE *DATA = y, q = LOAD *DATA
  1957. If ordering rules are relaxed, it must be assumed that accesses done inside an
  1958. interrupt disabled section may leak outside of it and may interleave with
  1959. accesses performed in an interrupt - and vice versa - unless implicit or
  1960. explicit barriers are used.
  1961. Normally this won't be a problem because the I/O accesses done inside such
  1962. sections will include synchronous load operations on strictly ordered I/O
  1963. registers that form implicit I/O barriers. If this isn't sufficient then an
  1964. mmiowb() may need to be used explicitly.
  1965. A similar situation may occur between an interrupt routine and two routines
  1966. running on separate CPUs that communicate with each other. If such a case is
  1967. likely, then interrupt-disabling locks should be used to guarantee ordering.
  1968. ==========================
  1969. KERNEL I/O BARRIER EFFECTS
  1970. ==========================
  1971. When accessing I/O memory, drivers should use the appropriate accessor
  1972. functions:
  1973. (*) inX(), outX():
  1974. These are intended to talk to I/O space rather than memory space, but
  1975. that's primarily a CPU-specific concept. The i386 and x86_64 processors
  1976. do indeed have special I/O space access cycles and instructions, but many
  1977. CPUs don't have such a concept.
  1978. The PCI bus, amongst others, defines an I/O space concept which - on such
  1979. CPUs as i386 and x86_64 - readily maps to the CPU's concept of I/O
  1980. space. However, it may also be mapped as a virtual I/O space in the CPU's
  1981. memory map, particularly on those CPUs that don't support alternate I/O
  1982. spaces.
  1983. Accesses to this space may be fully synchronous (as on i386), but
  1984. intermediary bridges (such as the PCI host bridge) may not fully honour
  1985. that.
  1986. They are guaranteed to be fully ordered with respect to each other.
  1987. They are not guaranteed to be fully ordered with respect to other types of
  1988. memory and I/O operation.
  1989. (*) readX(), writeX():
  1990. Whether these are guaranteed to be fully ordered and uncombined with
  1991. respect to each other on the issuing CPU depends on the characteristics
  1992. defined for the memory window through which they're accessing. On later
  1993. i386 architecture machines, for example, this is controlled by way of the
  1994. MTRR registers.
  1995. Ordinarily, these will be guaranteed to be fully ordered and uncombined,
  1996. provided they're not accessing a prefetchable device.
  1997. However, intermediary hardware (such as a PCI bridge) may indulge in
  1998. deferral if it so wishes; to flush a store, a load from the same location
  1999. is preferred[*], but a load from the same device or from configuration
  2000. space should suffice for PCI.
  2001. [*] NOTE! attempting to load from the same location as was written to may
  2002. cause a malfunction - consider the 16550 Rx/Tx serial registers for
  2003. example.
  2004. Used with prefetchable I/O memory, an mmiowb() barrier may be required to
  2005. force stores to be ordered.
  2006. Please refer to the PCI specification for more information on interactions
  2007. between PCI transactions.
  2008. (*) readX_relaxed(), writeX_relaxed()
  2009. These are similar to readX() and writeX(), but provide weaker memory
  2010. ordering guarantees. Specifically, they do not guarantee ordering with
  2011. respect to normal memory accesses (e.g. DMA buffers) nor do they guarantee
  2012. ordering with respect to LOCK or UNLOCK operations. If the latter is
  2013. required, an mmiowb() barrier can be used. Note that relaxed accesses to
  2014. the same peripheral are guaranteed to be ordered with respect to each
  2015. other.
  2016. (*) ioreadX(), iowriteX()
  2017. These will perform appropriately for the type of access they're actually
  2018. doing, be it inX()/outX() or readX()/writeX().
  2019. ========================================
  2020. ASSUMED MINIMUM EXECUTION ORDERING MODEL
  2021. ========================================
  2022. It has to be assumed that the conceptual CPU is weakly-ordered but that it will
  2023. maintain the appearance of program causality with respect to itself. Some CPUs
  2024. (such as i386 or x86_64) are more constrained than others (such as powerpc or
  2025. frv), and so the most relaxed case (namely DEC Alpha) must be assumed outside
  2026. of arch-specific code.
  2027. This means that it must be considered that the CPU will execute its instruction
  2028. stream in any order it feels like - or even in parallel - provided that if an
  2029. instruction in the stream depends on an earlier instruction, then that
  2030. earlier instruction must be sufficiently complete[*] before the later
  2031. instruction may proceed; in other words: provided that the appearance of
  2032. causality is maintained.
  2033. [*] Some instructions have more than one effect - such as changing the
  2034. condition codes, changing registers or changing memory - and different
  2035. instructions may depend on different effects.
  2036. A CPU may also discard any instruction sequence that winds up having no
  2037. ultimate effect. For example, if two adjacent instructions both load an
  2038. immediate value into the same register, the first may be discarded.
  2039. Similarly, it has to be assumed that compiler might reorder the instruction
  2040. stream in any way it sees fit, again provided the appearance of causality is
  2041. maintained.
  2042. ============================
  2043. THE EFFECTS OF THE CPU CACHE
  2044. ============================
  2045. The way cached memory operations are perceived across the system is affected to
  2046. a certain extent by the caches that lie between CPUs and memory, and by the
  2047. memory coherence system that maintains the consistency of state in the system.
  2048. As far as the way a CPU interacts with another part of the system through the
  2049. caches goes, the memory system has to include the CPU's caches, and memory
  2050. barriers for the most part act at the interface between the CPU and its cache
  2051. (memory barriers logically act on the dotted line in the following diagram):
  2052. <--- CPU ---> : <----------- Memory ----------->
  2053. :
  2054. +--------+ +--------+ : +--------+ +-----------+
  2055. | | | | : | | | | +--------+
  2056. | CPU | | Memory | : | CPU | | | | |
  2057. | Core |--->| Access |----->| Cache |<-->| | | |
  2058. | | | Queue | : | | | |--->| Memory |
  2059. | | | | : | | | | | |
  2060. +--------+ +--------+ : +--------+ | | | |
  2061. : | Cache | +--------+
  2062. : | Coherency |
  2063. : | Mechanism | +--------+
  2064. +--------+ +--------+ : +--------+ | | | |
  2065. | | | | : | | | | | |
  2066. | CPU | | Memory | : | CPU | | |--->| Device |
  2067. | Core |--->| Access |----->| Cache |<-->| | | |
  2068. | | | Queue | : | | | | | |
  2069. | | | | : | | | | +--------+
  2070. +--------+ +--------+ : +--------+ +-----------+
  2071. :
  2072. :
  2073. Although any particular load or store may not actually appear outside of the
  2074. CPU that issued it since it may have been satisfied within the CPU's own cache,
  2075. it will still appear as if the full memory access had taken place as far as the
  2076. other CPUs are concerned since the cache coherency mechanisms will migrate the
  2077. cacheline over to the accessing CPU and propagate the effects upon conflict.
  2078. The CPU core may execute instructions in any order it deems fit, provided the
  2079. expected program causality appears to be maintained. Some of the instructions
  2080. generate load and store operations which then go into the queue of memory
  2081. accesses to be performed. The core may place these in the queue in any order
  2082. it wishes, and continue execution until it is forced to wait for an instruction
  2083. to complete.
  2084. What memory barriers are concerned with is controlling the order in which
  2085. accesses cross from the CPU side of things to the memory side of things, and
  2086. the order in which the effects are perceived to happen by the other observers
  2087. in the system.
  2088. [!] Memory barriers are _not_ needed within a given CPU, as CPUs always see
  2089. their own loads and stores as if they had happened in program order.
  2090. [!] MMIO or other device accesses may bypass the cache system. This depends on
  2091. the properties of the memory window through which devices are accessed and/or
  2092. the use of any special device communication instructions the CPU may have.
  2093. CACHE COHERENCY
  2094. ---------------
  2095. Life isn't quite as simple as it may appear above, however: for while the
  2096. caches are expected to be coherent, there's no guarantee that that coherency
  2097. will be ordered. This means that whilst changes made on one CPU will
  2098. eventually become visible on all CPUs, there's no guarantee that they will
  2099. become apparent in the same order on those other CPUs.
  2100. Consider dealing with a system that has a pair of CPUs (1 & 2), each of which
  2101. has a pair of parallel data caches (CPU 1 has A/B, and CPU 2 has C/D):
  2102. :
  2103. : +--------+
  2104. : +---------+ | |
  2105. +--------+ : +--->| Cache A |<------->| |
  2106. | | : | +---------+ | |
  2107. | CPU 1 |<---+ | |
  2108. | | : | +---------+ | |
  2109. +--------+ : +--->| Cache B |<------->| |
  2110. : +---------+ | |
  2111. : | Memory |
  2112. : +---------+ | System |
  2113. +--------+ : +--->| Cache C |<------->| |
  2114. | | : | +---------+ | |
  2115. | CPU 2 |<---+ | |
  2116. | | : | +---------+ | |
  2117. +--------+ : +--->| Cache D |<------->| |
  2118. : +---------+ | |
  2119. : +--------+
  2120. :
  2121. Imagine the system has the following properties:
  2122. (*) an odd-numbered cache line may be in cache A, cache C or it may still be
  2123. resident in memory;
  2124. (*) an even-numbered cache line may be in cache B, cache D or it may still be
  2125. resident in memory;
  2126. (*) whilst the CPU core is interrogating one cache, the other cache may be
  2127. making use of the bus to access the rest of the system - perhaps to
  2128. displace a dirty cacheline or to do a speculative load;
  2129. (*) each cache has a queue of operations that need to be applied to that cache
  2130. to maintain coherency with the rest of the system;
  2131. (*) the coherency queue is not flushed by normal loads to lines already
  2132. present in the cache, even though the contents of the queue may
  2133. potentially affect those loads.
  2134. Imagine, then, that two writes are made on the first CPU, with a write barrier
  2135. between them to guarantee that they will appear to reach that CPU's caches in
  2136. the requisite order:
  2137. CPU 1 CPU 2 COMMENT
  2138. =============== =============== =======================================
  2139. u == 0, v == 1 and p == &u, q == &u
  2140. v = 2;
  2141. smp_wmb(); Make sure change to v is visible before
  2142. change to p
  2143. <A:modify v=2> v is now in cache A exclusively
  2144. p = &v;
  2145. <B:modify p=&v> p is now in cache B exclusively
  2146. The write memory barrier forces the other CPUs in the system to perceive that
  2147. the local CPU's caches have apparently been updated in the correct order. But
  2148. now imagine that the second CPU wants to read those values:
  2149. CPU 1 CPU 2 COMMENT
  2150. =============== =============== =======================================
  2151. ...
  2152. q = p;
  2153. x = *q;
  2154. The above pair of reads may then fail to happen in the expected order, as the
  2155. cacheline holding p may get updated in one of the second CPU's caches whilst
  2156. the update to the cacheline holding v is delayed in the other of the second
  2157. CPU's caches by some other cache event:
  2158. CPU 1 CPU 2 COMMENT
  2159. =============== =============== =======================================
  2160. u == 0, v == 1 and p == &u, q == &u
  2161. v = 2;
  2162. smp_wmb();
  2163. <A:modify v=2> <C:busy>
  2164. <C:queue v=2>
  2165. p = &v; q = p;
  2166. <D:request p>
  2167. <B:modify p=&v> <D:commit p=&v>
  2168. <D:read p>
  2169. x = *q;
  2170. <C:read *q> Reads from v before v updated in cache
  2171. <C:unbusy>
  2172. <C:commit v=2>
  2173. Basically, whilst both cachelines will be updated on CPU 2 eventually, there's
  2174. no guarantee that, without intervention, the order of update will be the same
  2175. as that committed on CPU 1.
  2176. To intervene, we need to interpolate a data dependency barrier or a read
  2177. barrier between the loads. This will force the cache to commit its coherency
  2178. queue before processing any further requests:
  2179. CPU 1 CPU 2 COMMENT
  2180. =============== =============== =======================================
  2181. u == 0, v == 1 and p == &u, q == &u
  2182. v = 2;
  2183. smp_wmb();
  2184. <A:modify v=2> <C:busy>
  2185. <C:queue v=2>
  2186. p = &v; q = p;
  2187. <D:request p>
  2188. <B:modify p=&v> <D:commit p=&v>
  2189. <D:read p>
  2190. smp_read_barrier_depends()
  2191. <C:unbusy>
  2192. <C:commit v=2>
  2193. x = *q;
  2194. <C:read *q> Reads from v after v updated in cache
  2195. This sort of problem can be encountered on DEC Alpha processors as they have a
  2196. split cache that improves performance by making better use of the data bus.
  2197. Whilst most CPUs do imply a data dependency barrier on the read when a memory
  2198. access depends on a read, not all do, so it may not be relied on.
  2199. Other CPUs may also have split caches, but must coordinate between the various
  2200. cachelets for normal memory accesses. The semantics of the Alpha removes the
  2201. need for coordination in the absence of memory barriers.
  2202. CACHE COHERENCY VS DMA
  2203. ----------------------
  2204. Not all systems maintain cache coherency with respect to devices doing DMA. In
  2205. such cases, a device attempting DMA may obtain stale data from RAM because
  2206. dirty cache lines may be resident in the caches of various CPUs, and may not
  2207. have been written back to RAM yet. To deal with this, the appropriate part of
  2208. the kernel must flush the overlapping bits of cache on each CPU (and maybe
  2209. invalidate them as well).
  2210. In addition, the data DMA'd to RAM by a device may be overwritten by dirty
  2211. cache lines being written back to RAM from a CPU's cache after the device has
  2212. installed its own data, or cache lines present in the CPU's cache may simply
  2213. obscure the fact that RAM has been updated, until at such time as the cacheline
  2214. is discarded from the CPU's cache and reloaded. To deal with this, the
  2215. appropriate part of the kernel must invalidate the overlapping bits of the
  2216. cache on each CPU.
  2217. See Documentation/cachetlb.txt for more information on cache management.
  2218. CACHE COHERENCY VS MMIO
  2219. -----------------------
  2220. Memory mapped I/O usually takes place through memory locations that are part of
  2221. a window in the CPU's memory space that has different properties assigned than
  2222. the usual RAM directed window.
  2223. Amongst these properties is usually the fact that such accesses bypass the
  2224. caching entirely and go directly to the device buses. This means MMIO accesses
  2225. may, in effect, overtake accesses to cached memory that were emitted earlier.
  2226. A memory barrier isn't sufficient in such a case, but rather the cache must be
  2227. flushed between the cached memory write and the MMIO access if the two are in
  2228. any way dependent.
  2229. =========================
  2230. THE THINGS CPUS GET UP TO
  2231. =========================
  2232. A programmer might take it for granted that the CPU will perform memory
  2233. operations in exactly the order specified, so that if the CPU is, for example,
  2234. given the following piece of code to execute:
  2235. a = READ_ONCE(*A);
  2236. WRITE_ONCE(*B, b);
  2237. c = READ_ONCE(*C);
  2238. d = READ_ONCE(*D);
  2239. WRITE_ONCE(*E, e);
  2240. they would then expect that the CPU will complete the memory operation for each
  2241. instruction before moving on to the next one, leading to a definite sequence of
  2242. operations as seen by external observers in the system:
  2243. LOAD *A, STORE *B, LOAD *C, LOAD *D, STORE *E.
  2244. Reality is, of course, much messier. With many CPUs and compilers, the above
  2245. assumption doesn't hold because:
  2246. (*) loads are more likely to need to be completed immediately to permit
  2247. execution progress, whereas stores can often be deferred without a
  2248. problem;
  2249. (*) loads may be done speculatively, and the result discarded should it prove
  2250. to have been unnecessary;
  2251. (*) loads may be done speculatively, leading to the result having been fetched
  2252. at the wrong time in the expected sequence of events;
  2253. (*) the order of the memory accesses may be rearranged to promote better use
  2254. of the CPU buses and caches;
  2255. (*) loads and stores may be combined to improve performance when talking to
  2256. memory or I/O hardware that can do batched accesses of adjacent locations,
  2257. thus cutting down on transaction setup costs (memory and PCI devices may
  2258. both be able to do this); and
  2259. (*) the CPU's data cache may affect the ordering, and whilst cache-coherency
  2260. mechanisms may alleviate this - once the store has actually hit the cache
  2261. - there's no guarantee that the coherency management will be propagated in
  2262. order to other CPUs.
  2263. So what another CPU, say, might actually observe from the above piece of code
  2264. is:
  2265. LOAD *A, ..., LOAD {*C,*D}, STORE *E, STORE *B
  2266. (Where "LOAD {*C,*D}" is a combined load)
  2267. However, it is guaranteed that a CPU will be self-consistent: it will see its
  2268. _own_ accesses appear to be correctly ordered, without the need for a memory
  2269. barrier. For instance with the following code:
  2270. U = READ_ONCE(*A);
  2271. WRITE_ONCE(*A, V);
  2272. WRITE_ONCE(*A, W);
  2273. X = READ_ONCE(*A);
  2274. WRITE_ONCE(*A, Y);
  2275. Z = READ_ONCE(*A);
  2276. and assuming no intervention by an external influence, it can be assumed that
  2277. the final result will appear to be:
  2278. U == the original value of *A
  2279. X == W
  2280. Z == Y
  2281. *A == Y
  2282. The code above may cause the CPU to generate the full sequence of memory
  2283. accesses:
  2284. U=LOAD *A, STORE *A=V, STORE *A=W, X=LOAD *A, STORE *A=Y, Z=LOAD *A
  2285. in that order, but, without intervention, the sequence may have almost any
  2286. combination of elements combined or discarded, provided the program's view
  2287. of the world remains consistent. Note that READ_ONCE() and WRITE_ONCE()
  2288. are -not- optional in the above example, as there are architectures
  2289. where a given CPU might reorder successive loads to the same location.
  2290. On such architectures, READ_ONCE() and WRITE_ONCE() do whatever is
  2291. necessary to prevent this, for example, on Itanium the volatile casts
  2292. used by READ_ONCE() and WRITE_ONCE() cause GCC to emit the special ld.acq
  2293. and st.rel instructions (respectively) that prevent such reordering.
  2294. The compiler may also combine, discard or defer elements of the sequence before
  2295. the CPU even sees them.
  2296. For instance:
  2297. *A = V;
  2298. *A = W;
  2299. may be reduced to:
  2300. *A = W;
  2301. since, without either a write barrier or an WRITE_ONCE(), it can be
  2302. assumed that the effect of the storage of V to *A is lost. Similarly:
  2303. *A = Y;
  2304. Z = *A;
  2305. may, without a memory barrier or an READ_ONCE() and WRITE_ONCE(), be
  2306. reduced to:
  2307. *A = Y;
  2308. Z = Y;
  2309. and the LOAD operation never appear outside of the CPU.
  2310. AND THEN THERE'S THE ALPHA
  2311. --------------------------
  2312. The DEC Alpha CPU is one of the most relaxed CPUs there is. Not only that,
  2313. some versions of the Alpha CPU have a split data cache, permitting them to have
  2314. two semantically-related cache lines updated at separate times. This is where
  2315. the data dependency barrier really becomes necessary as this synchronises both
  2316. caches with the memory coherence system, thus making it seem like pointer
  2317. changes vs new data occur in the right order.
  2318. The Alpha defines the Linux kernel's memory barrier model.
  2319. See the subsection on "Cache Coherency" above.
  2320. VIRTUAL MACHINE GUESTS
  2321. ----------------------
  2322. Guests running within virtual machines might be affected by SMP effects even if
  2323. the guest itself is compiled without SMP support. This is an artifact of
  2324. interfacing with an SMP host while running an UP kernel. Using mandatory
  2325. barriers for this use-case would be possible but is often suboptimal.
  2326. To handle this case optimally, low-level virt_mb() etc macros are available.
  2327. These have the same effect as smp_mb() etc when SMP is enabled, but generate
  2328. identical code for SMP and non-SMP systems. For example, virtual machine guests
  2329. should use virt_mb() rather than smp_mb() when synchronizing against a
  2330. (possibly SMP) host.
  2331. These are equivalent to smp_mb() etc counterparts in all other respects,
  2332. in particular, they do not control MMIO effects: to control
  2333. MMIO effects, use mandatory barriers.
  2334. ============
  2335. EXAMPLE USES
  2336. ============
  2337. CIRCULAR BUFFERS
  2338. ----------------
  2339. Memory barriers can be used to implement circular buffering without the need
  2340. of a lock to serialise the producer with the consumer. See:
  2341. Documentation/circular-buffers.txt
  2342. for details.
  2343. ==========
  2344. REFERENCES
  2345. ==========
  2346. Alpha AXP Architecture Reference Manual, Second Edition (Sites & Witek,
  2347. Digital Press)
  2348. Chapter 5.2: Physical Address Space Characteristics
  2349. Chapter 5.4: Caches and Write Buffers
  2350. Chapter 5.5: Data Sharing
  2351. Chapter 5.6: Read/Write Ordering
  2352. AMD64 Architecture Programmer's Manual Volume 2: System Programming
  2353. Chapter 7.1: Memory-Access Ordering
  2354. Chapter 7.4: Buffering and Combining Memory Writes
  2355. IA-32 Intel Architecture Software Developer's Manual, Volume 3:
  2356. System Programming Guide
  2357. Chapter 7.1: Locked Atomic Operations
  2358. Chapter 7.2: Memory Ordering
  2359. Chapter 7.4: Serializing Instructions
  2360. The SPARC Architecture Manual, Version 9
  2361. Chapter 8: Memory Models
  2362. Appendix D: Formal Specification of the Memory Models
  2363. Appendix J: Programming with the Memory Models
  2364. UltraSPARC Programmer Reference Manual
  2365. Chapter 5: Memory Accesses and Cacheability
  2366. Chapter 15: Sparc-V9 Memory Models
  2367. UltraSPARC III Cu User's Manual
  2368. Chapter 9: Memory Models
  2369. UltraSPARC IIIi Processor User's Manual
  2370. Chapter 8: Memory Models
  2371. UltraSPARC Architecture 2005
  2372. Chapter 9: Memory
  2373. Appendix D: Formal Specifications of the Memory Models
  2374. UltraSPARC T1 Supplement to the UltraSPARC Architecture 2005
  2375. Chapter 8: Memory Models
  2376. Appendix F: Caches and Cache Coherency
  2377. Solaris Internals, Core Kernel Architecture, p63-68:
  2378. Chapter 3.3: Hardware Considerations for Locks and
  2379. Synchronization
  2380. Unix Systems for Modern Architectures, Symmetric Multiprocessing and Caching
  2381. for Kernel Programmers:
  2382. Chapter 13: Other Memory Models
  2383. Intel Itanium Architecture Software Developer's Manual: Volume 1:
  2384. Section 2.6: Speculation
  2385. Section 4.4: Memory Access