memory-barriers.txt 111 KB

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