memory-barriers.txt 115 KB

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