memory-barriers.txt 112 KB

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