memory-barriers.txt 108 KB

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