memory-barriers.txt 105 KB

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