memory-barriers.txt 110 KB

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