Requirements.rst 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760
  1. =================================
  2. A Tour Through RCU's Requirements
  3. =================================
  4. Copyright IBM Corporation, 2015
  5. Author: Paul E. McKenney
  6. The initial version of this document appeared in the
  7. `LWN <https://lwn.net/>`_ on those articles:
  8. `part 1 <https://lwn.net/Articles/652156/>`_,
  9. `part 2 <https://lwn.net/Articles/652677/>`_, and
  10. `part 3 <https://lwn.net/Articles/653326/>`_.
  11. Introduction
  12. ------------
  13. Read-copy update (RCU) is a synchronization mechanism that is often used
  14. as a replacement for reader-writer locking. RCU is unusual in that
  15. updaters do not block readers, which means that RCU's read-side
  16. primitives can be exceedingly fast and scalable. In addition, updaters
  17. can make useful forward progress concurrently with readers. However, all
  18. this concurrency between RCU readers and updaters does raise the
  19. question of exactly what RCU readers are doing, which in turn raises the
  20. question of exactly what RCU's requirements are.
  21. This document therefore summarizes RCU's requirements, and can be
  22. thought of as an informal, high-level specification for RCU. It is
  23. important to understand that RCU's specification is primarily empirical
  24. in nature; in fact, I learned about many of these requirements the hard
  25. way. This situation might cause some consternation, however, not only
  26. has this learning process been a lot of fun, but it has also been a
  27. great privilege to work with so many people willing to apply
  28. technologies in interesting new ways.
  29. All that aside, here are the categories of currently known RCU
  30. requirements:
  31. #. `Fundamental Requirements`_
  32. #. `Fundamental Non-Requirements`_
  33. #. `Parallelism Facts of Life`_
  34. #. `Quality-of-Implementation Requirements`_
  35. #. `Linux Kernel Complications`_
  36. #. `Software-Engineering Requirements`_
  37. #. `Other RCU Flavors`_
  38. #. `Possible Future Changes`_
  39. This is followed by a summary_, however, the answers to
  40. each quick quiz immediately follows the quiz. Select the big white space
  41. with your mouse to see the answer.
  42. Fundamental Requirements
  43. ------------------------
  44. RCU's fundamental requirements are the closest thing RCU has to hard
  45. mathematical requirements. These are:
  46. #. `Grace-Period Guarantee`_
  47. #. `Publish/Subscribe Guarantee`_
  48. #. `Memory-Barrier Guarantees`_
  49. #. `RCU Primitives Guaranteed to Execute Unconditionally`_
  50. #. `Guaranteed Read-to-Write Upgrade`_
  51. Grace-Period Guarantee
  52. ~~~~~~~~~~~~~~~~~~~~~~
  53. RCU's grace-period guarantee is unusual in being premeditated: Jack
  54. Slingwine and I had this guarantee firmly in mind when we started work
  55. on RCU (then called “rclock”) in the early 1990s. That said, the past
  56. two decades of experience with RCU have produced a much more detailed
  57. understanding of this guarantee.
  58. RCU's grace-period guarantee allows updaters to wait for the completion
  59. of all pre-existing RCU read-side critical sections. An RCU read-side
  60. critical section begins with the marker rcu_read_lock() and ends
  61. with the marker rcu_read_unlock(). These markers may be nested, and
  62. RCU treats a nested set as one big RCU read-side critical section.
  63. Production-quality implementations of rcu_read_lock() and
  64. rcu_read_unlock() are extremely lightweight, and in fact have
  65. exactly zero overhead in Linux kernels built for production use with
  66. ``CONFIG_PREEMPTION=n``.
  67. This guarantee allows ordering to be enforced with extremely low
  68. overhead to readers, for example:
  69. ::
  70. 1 int x, y;
  71. 2
  72. 3 void thread0(void)
  73. 4 {
  74. 5 rcu_read_lock();
  75. 6 r1 = READ_ONCE(x);
  76. 7 r2 = READ_ONCE(y);
  77. 8 rcu_read_unlock();
  78. 9 }
  79. 10
  80. 11 void thread1(void)
  81. 12 {
  82. 13 WRITE_ONCE(x, 1);
  83. 14 synchronize_rcu();
  84. 15 WRITE_ONCE(y, 1);
  85. 16 }
  86. Because the synchronize_rcu() on line 14 waits for all pre-existing
  87. readers, any instance of thread0() that loads a value of zero from
  88. ``x`` must complete before thread1() stores to ``y``, so that
  89. instance must also load a value of zero from ``y``. Similarly, any
  90. instance of thread0() that loads a value of one from ``y`` must have
  91. started after the synchronize_rcu() started, and must therefore also
  92. load a value of one from ``x``. Therefore, the outcome:
  93. ::
  94. (r1 == 0 && r2 == 1)
  95. cannot happen.
  96. +-----------------------------------------------------------------------+
  97. | **Quick Quiz**: |
  98. +-----------------------------------------------------------------------+
  99. | Wait a minute! You said that updaters can make useful forward |
  100. | progress concurrently with readers, but pre-existing readers will |
  101. | block synchronize_rcu()!!! |
  102. | Just who are you trying to fool??? |
  103. +-----------------------------------------------------------------------+
  104. | **Answer**: |
  105. +-----------------------------------------------------------------------+
  106. | First, if updaters do not wish to be blocked by readers, they can use |
  107. | call_rcu() or kfree_rcu(), which will be discussed later. |
  108. | Second, even when using synchronize_rcu(), the other update-side |
  109. | code does run concurrently with readers, whether pre-existing or not. |
  110. +-----------------------------------------------------------------------+
  111. This scenario resembles one of the first uses of RCU in
  112. `DYNIX/ptx <https://en.wikipedia.org/wiki/DYNIX>`__, which managed a
  113. distributed lock manager's transition into a state suitable for handling
  114. recovery from node failure, more or less as follows:
  115. ::
  116. 1 #define STATE_NORMAL 0
  117. 2 #define STATE_WANT_RECOVERY 1
  118. 3 #define STATE_RECOVERING 2
  119. 4 #define STATE_WANT_NORMAL 3
  120. 5
  121. 6 int state = STATE_NORMAL;
  122. 7
  123. 8 void do_something_dlm(void)
  124. 9 {
  125. 10 int state_snap;
  126. 11
  127. 12 rcu_read_lock();
  128. 13 state_snap = READ_ONCE(state);
  129. 14 if (state_snap == STATE_NORMAL)
  130. 15 do_something();
  131. 16 else
  132. 17 do_something_carefully();
  133. 18 rcu_read_unlock();
  134. 19 }
  135. 20
  136. 21 void start_recovery(void)
  137. 22 {
  138. 23 WRITE_ONCE(state, STATE_WANT_RECOVERY);
  139. 24 synchronize_rcu();
  140. 25 WRITE_ONCE(state, STATE_RECOVERING);
  141. 26 recovery();
  142. 27 WRITE_ONCE(state, STATE_WANT_NORMAL);
  143. 28 synchronize_rcu();
  144. 29 WRITE_ONCE(state, STATE_NORMAL);
  145. 30 }
  146. The RCU read-side critical section in do_something_dlm() works with
  147. the synchronize_rcu() in start_recovery() to guarantee that
  148. do_something() never runs concurrently with recovery(), but with
  149. little or no synchronization overhead in do_something_dlm().
  150. +-----------------------------------------------------------------------+
  151. | **Quick Quiz**: |
  152. +-----------------------------------------------------------------------+
  153. | Why is the synchronize_rcu() on line 28 needed? |
  154. +-----------------------------------------------------------------------+
  155. | **Answer**: |
  156. +-----------------------------------------------------------------------+
  157. | Without that extra grace period, memory reordering could result in |
  158. | do_something_dlm() executing do_something() concurrently with |
  159. | the last bits of recovery(). |
  160. +-----------------------------------------------------------------------+
  161. In order to avoid fatal problems such as deadlocks, an RCU read-side
  162. critical section must not contain calls to synchronize_rcu().
  163. Similarly, an RCU read-side critical section must not contain anything
  164. that waits, directly or indirectly, on completion of an invocation of
  165. synchronize_rcu().
  166. Although RCU's grace-period guarantee is useful in and of itself, with
  167. `quite a few use cases <https://lwn.net/Articles/573497/>`__, it would
  168. be good to be able to use RCU to coordinate read-side access to linked
  169. data structures. For this, the grace-period guarantee is not sufficient,
  170. as can be seen in function add_gp_buggy() below. We will look at the
  171. reader's code later, but in the meantime, just think of the reader as
  172. locklessly picking up the ``gp`` pointer, and, if the value loaded is
  173. non-\ ``NULL``, locklessly accessing the ``->a`` and ``->b`` fields.
  174. ::
  175. 1 bool add_gp_buggy(int a, int b)
  176. 2 {
  177. 3 p = kmalloc(sizeof(*p), GFP_KERNEL);
  178. 4 if (!p)
  179. 5 return -ENOMEM;
  180. 6 spin_lock(&gp_lock);
  181. 7 if (rcu_access_pointer(gp)) {
  182. 8 spin_unlock(&gp_lock);
  183. 9 return false;
  184. 10 }
  185. 11 p->a = a;
  186. 12 p->b = a;
  187. 13 gp = p; /* ORDERING BUG */
  188. 14 spin_unlock(&gp_lock);
  189. 15 return true;
  190. 16 }
  191. The problem is that both the compiler and weakly ordered CPUs are within
  192. their rights to reorder this code as follows:
  193. ::
  194. 1 bool add_gp_buggy_optimized(int a, int b)
  195. 2 {
  196. 3 p = kmalloc(sizeof(*p), GFP_KERNEL);
  197. 4 if (!p)
  198. 5 return -ENOMEM;
  199. 6 spin_lock(&gp_lock);
  200. 7 if (rcu_access_pointer(gp)) {
  201. 8 spin_unlock(&gp_lock);
  202. 9 return false;
  203. 10 }
  204. 11 gp = p; /* ORDERING BUG */
  205. 12 p->a = a;
  206. 13 p->b = a;
  207. 14 spin_unlock(&gp_lock);
  208. 15 return true;
  209. 16 }
  210. If an RCU reader fetches ``gp`` just after ``add_gp_buggy_optimized``
  211. executes line 11, it will see garbage in the ``->a`` and ``->b`` fields.
  212. And this is but one of many ways in which compiler and hardware
  213. optimizations could cause trouble. Therefore, we clearly need some way
  214. to prevent the compiler and the CPU from reordering in this manner,
  215. which brings us to the publish-subscribe guarantee discussed in the next
  216. section.
  217. Publish/Subscribe Guarantee
  218. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  219. RCU's publish-subscribe guarantee allows data to be inserted into a
  220. linked data structure without disrupting RCU readers. The updater uses
  221. rcu_assign_pointer() to insert the new data, and readers use
  222. rcu_dereference() to access data, whether new or old. The following
  223. shows an example of insertion:
  224. ::
  225. 1 bool add_gp(int a, int b)
  226. 2 {
  227. 3 p = kmalloc(sizeof(*p), GFP_KERNEL);
  228. 4 if (!p)
  229. 5 return -ENOMEM;
  230. 6 spin_lock(&gp_lock);
  231. 7 if (rcu_access_pointer(gp)) {
  232. 8 spin_unlock(&gp_lock);
  233. 9 return false;
  234. 10 }
  235. 11 p->a = a;
  236. 12 p->b = a;
  237. 13 rcu_assign_pointer(gp, p);
  238. 14 spin_unlock(&gp_lock);
  239. 15 return true;
  240. 16 }
  241. The rcu_assign_pointer() on line 13 is conceptually equivalent to a
  242. simple assignment statement, but also guarantees that its assignment
  243. will happen after the two assignments in lines 11 and 12, similar to the
  244. C11 ``memory_order_release`` store operation. It also prevents any
  245. number of “interesting” compiler optimizations, for example, the use of
  246. ``gp`` as a scratch location immediately preceding the assignment.
  247. +-----------------------------------------------------------------------+
  248. | **Quick Quiz**: |
  249. +-----------------------------------------------------------------------+
  250. | But rcu_assign_pointer() does nothing to prevent the two |
  251. | assignments to ``p->a`` and ``p->b`` from being reordered. Can't that |
  252. | also cause problems? |
  253. +-----------------------------------------------------------------------+
  254. | **Answer**: |
  255. +-----------------------------------------------------------------------+
  256. | No, it cannot. The readers cannot see either of these two fields |
  257. | until the assignment to ``gp``, by which time both fields are fully |
  258. | initialized. So reordering the assignments to ``p->a`` and ``p->b`` |
  259. | cannot possibly cause any problems. |
  260. +-----------------------------------------------------------------------+
  261. It is tempting to assume that the reader need not do anything special to
  262. control its accesses to the RCU-protected data, as shown in
  263. do_something_gp_buggy() below:
  264. ::
  265. 1 bool do_something_gp_buggy(void)
  266. 2 {
  267. 3 rcu_read_lock();
  268. 4 p = gp; /* OPTIMIZATIONS GALORE!!! */
  269. 5 if (p) {
  270. 6 do_something(p->a, p->b);
  271. 7 rcu_read_unlock();
  272. 8 return true;
  273. 9 }
  274. 10 rcu_read_unlock();
  275. 11 return false;
  276. 12 }
  277. However, this temptation must be resisted because there are a
  278. surprisingly large number of ways that the compiler (or weak ordering
  279. CPUs like the DEC Alpha) can trip this code up. For but one example, if
  280. the compiler were short of registers, it might choose to refetch from
  281. ``gp`` rather than keeping a separate copy in ``p`` as follows:
  282. ::
  283. 1 bool do_something_gp_buggy_optimized(void)
  284. 2 {
  285. 3 rcu_read_lock();
  286. 4 if (gp) { /* OPTIMIZATIONS GALORE!!! */
  287. 5 do_something(gp->a, gp->b);
  288. 6 rcu_read_unlock();
  289. 7 return true;
  290. 8 }
  291. 9 rcu_read_unlock();
  292. 10 return false;
  293. 11 }
  294. If this function ran concurrently with a series of updates that replaced
  295. the current structure with a new one, the fetches of ``gp->a`` and
  296. ``gp->b`` might well come from two different structures, which could
  297. cause serious confusion. To prevent this (and much else besides),
  298. do_something_gp() uses rcu_dereference() to fetch from ``gp``:
  299. ::
  300. 1 bool do_something_gp(void)
  301. 2 {
  302. 3 rcu_read_lock();
  303. 4 p = rcu_dereference(gp);
  304. 5 if (p) {
  305. 6 do_something(p->a, p->b);
  306. 7 rcu_read_unlock();
  307. 8 return true;
  308. 9 }
  309. 10 rcu_read_unlock();
  310. 11 return false;
  311. 12 }
  312. The rcu_dereference() uses volatile casts and (for DEC Alpha) memory
  313. barriers in the Linux kernel. Should a |high-quality implementation of
  314. C11 memory_order_consume [PDF]|_
  315. ever appear, then rcu_dereference() could be implemented as a
  316. ``memory_order_consume`` load. Regardless of the exact implementation, a
  317. pointer fetched by rcu_dereference() may not be used outside of the
  318. outermost RCU read-side critical section containing that
  319. rcu_dereference(), unless protection of the corresponding data
  320. element has been passed from RCU to some other synchronization
  321. mechanism, most commonly locking or reference counting
  322. (see ../../rcuref.rst).
  323. .. |high-quality implementation of C11 memory_order_consume [PDF]| replace:: high-quality implementation of C11 ``memory_order_consume`` [PDF]
  324. .. _high-quality implementation of C11 memory_order_consume [PDF]: http://www.rdrop.com/users/paulmck/RCU/consume.2015.07.13a.pdf
  325. In short, updaters use rcu_assign_pointer() and readers use
  326. rcu_dereference(), and these two RCU API elements work together to
  327. ensure that readers have a consistent view of newly added data elements.
  328. Of course, it is also necessary to remove elements from RCU-protected
  329. data structures, for example, using the following process:
  330. #. Remove the data element from the enclosing structure.
  331. #. Wait for all pre-existing RCU read-side critical sections to complete
  332. (because only pre-existing readers can possibly have a reference to
  333. the newly removed data element).
  334. #. At this point, only the updater has a reference to the newly removed
  335. data element, so it can safely reclaim the data element, for example,
  336. by passing it to kfree().
  337. This process is implemented by remove_gp_synchronous():
  338. ::
  339. 1 bool remove_gp_synchronous(void)
  340. 2 {
  341. 3 struct foo *p;
  342. 4
  343. 5 spin_lock(&gp_lock);
  344. 6 p = rcu_access_pointer(gp);
  345. 7 if (!p) {
  346. 8 spin_unlock(&gp_lock);
  347. 9 return false;
  348. 10 }
  349. 11 rcu_assign_pointer(gp, NULL);
  350. 12 spin_unlock(&gp_lock);
  351. 13 synchronize_rcu();
  352. 14 kfree(p);
  353. 15 return true;
  354. 16 }
  355. This function is straightforward, with line 13 waiting for a grace
  356. period before line 14 frees the old data element. This waiting ensures
  357. that readers will reach line 7 of do_something_gp() before the data
  358. element referenced by ``p`` is freed. The rcu_access_pointer() on
  359. line 6 is similar to rcu_dereference(), except that:
  360. #. The value returned by rcu_access_pointer() cannot be
  361. dereferenced. If you want to access the value pointed to as well as
  362. the pointer itself, use rcu_dereference() instead of
  363. rcu_access_pointer().
  364. #. The call to rcu_access_pointer() need not be protected. In
  365. contrast, rcu_dereference() must either be within an RCU
  366. read-side critical section or in a code segment where the pointer
  367. cannot change, for example, in code protected by the corresponding
  368. update-side lock.
  369. +-----------------------------------------------------------------------+
  370. | **Quick Quiz**: |
  371. +-----------------------------------------------------------------------+
  372. | Without the rcu_dereference() or the rcu_access_pointer(), |
  373. | what destructive optimizations might the compiler make use of? |
  374. +-----------------------------------------------------------------------+
  375. | **Answer**: |
  376. +-----------------------------------------------------------------------+
  377. | Let's start with what happens to do_something_gp() if it fails to |
  378. | use rcu_dereference(). It could reuse a value formerly fetched |
  379. | from this same pointer. It could also fetch the pointer from ``gp`` |
  380. | in a byte-at-a-time manner, resulting in *load tearing*, in turn |
  381. | resulting a bytewise mash-up of two distinct pointer values. It might |
  382. | even use value-speculation optimizations, where it makes a wrong |
  383. | guess, but by the time it gets around to checking the value, an |
  384. | update has changed the pointer to match the wrong guess. Too bad |
  385. | about any dereferences that returned pre-initialization garbage in |
  386. | the meantime! |
  387. | For remove_gp_synchronous(), as long as all modifications to |
  388. | ``gp`` are carried out while holding ``gp_lock``, the above |
  389. | optimizations are harmless. However, ``sparse`` will complain if you |
  390. | define ``gp`` with ``__rcu`` and then access it without using either |
  391. | rcu_access_pointer() or rcu_dereference(). |
  392. +-----------------------------------------------------------------------+
  393. In short, RCU's publish-subscribe guarantee is provided by the
  394. combination of rcu_assign_pointer() and rcu_dereference(). This
  395. guarantee allows data elements to be safely added to RCU-protected
  396. linked data structures without disrupting RCU readers. This guarantee
  397. can be used in combination with the grace-period guarantee to also allow
  398. data elements to be removed from RCU-protected linked data structures,
  399. again without disrupting RCU readers.
  400. This guarantee was only partially premeditated. DYNIX/ptx used an
  401. explicit memory barrier for publication, but had nothing resembling
  402. rcu_dereference() for subscription, nor did it have anything
  403. resembling the dependency-ordering barrier that was later subsumed
  404. into rcu_dereference() and later still into READ_ONCE(). The
  405. need for these operations made itself known quite suddenly at a
  406. late-1990s meeting with the DEC Alpha architects, back in the days when
  407. DEC was still a free-standing company. It took the Alpha architects a
  408. good hour to convince me that any sort of barrier would ever be needed,
  409. and it then took me a good *two* hours to convince them that their
  410. documentation did not make this point clear. More recent work with the C
  411. and C++ standards committees have provided much education on tricks and
  412. traps from the compiler. In short, compilers were much less tricky in
  413. the early 1990s, but in 2015, don't even think about omitting
  414. rcu_dereference()!
  415. Memory-Barrier Guarantees
  416. ~~~~~~~~~~~~~~~~~~~~~~~~~
  417. The previous section's simple linked-data-structure scenario clearly
  418. demonstrates the need for RCU's stringent memory-ordering guarantees on
  419. systems with more than one CPU:
  420. #. Each CPU that has an RCU read-side critical section that begins
  421. before synchronize_rcu() starts is guaranteed to execute a full
  422. memory barrier between the time that the RCU read-side critical
  423. section ends and the time that synchronize_rcu() returns. Without
  424. this guarantee, a pre-existing RCU read-side critical section might
  425. hold a reference to the newly removed ``struct foo`` after the
  426. kfree() on line 14 of remove_gp_synchronous().
  427. #. Each CPU that has an RCU read-side critical section that ends after
  428. synchronize_rcu() returns is guaranteed to execute a full memory
  429. barrier between the time that synchronize_rcu() begins and the
  430. time that the RCU read-side critical section begins. Without this
  431. guarantee, a later RCU read-side critical section running after the
  432. kfree() on line 14 of remove_gp_synchronous() might later run
  433. do_something_gp() and find the newly deleted ``struct foo``.
  434. #. If the task invoking synchronize_rcu() remains on a given CPU,
  435. then that CPU is guaranteed to execute a full memory barrier sometime
  436. during the execution of synchronize_rcu(). This guarantee ensures
  437. that the kfree() on line 14 of remove_gp_synchronous() really
  438. does execute after the removal on line 11.
  439. #. If the task invoking synchronize_rcu() migrates among a group of
  440. CPUs during that invocation, then each of the CPUs in that group is
  441. guaranteed to execute a full memory barrier sometime during the
  442. execution of synchronize_rcu(). This guarantee also ensures that
  443. the kfree() on line 14 of remove_gp_synchronous() really does
  444. execute after the removal on line 11, but also in the case where the
  445. thread executing the synchronize_rcu() migrates in the meantime.
  446. +-----------------------------------------------------------------------+
  447. | **Quick Quiz**: |
  448. +-----------------------------------------------------------------------+
  449. | Given that multiple CPUs can start RCU read-side critical sections at |
  450. | any time without any ordering whatsoever, how can RCU possibly tell |
  451. | whether or not a given RCU read-side critical section starts before a |
  452. | given instance of synchronize_rcu()? |
  453. +-----------------------------------------------------------------------+
  454. | **Answer**: |
  455. +-----------------------------------------------------------------------+
  456. | If RCU cannot tell whether or not a given RCU read-side critical |
  457. | section starts before a given instance of synchronize_rcu(), then |
  458. | it must assume that the RCU read-side critical section started first. |
  459. | In other words, a given instance of synchronize_rcu() can avoid |
  460. | waiting on a given RCU read-side critical section only if it can |
  461. | prove that synchronize_rcu() started first. |
  462. | A related question is “When rcu_read_lock() doesn't generate any |
  463. | code, why does it matter how it relates to a grace period?” The |
  464. | answer is that it is not the relationship of rcu_read_lock() |
  465. | itself that is important, but rather the relationship of the code |
  466. | within the enclosed RCU read-side critical section to the code |
  467. | preceding and following the grace period. If we take this viewpoint, |
  468. | then a given RCU read-side critical section begins before a given |
  469. | grace period when some access preceding the grace period observes the |
  470. | effect of some access within the critical section, in which case none |
  471. | of the accesses within the critical section may observe the effects |
  472. | of any access following the grace period. |
  473. | |
  474. | As of late 2016, mathematical models of RCU take this viewpoint, for |
  475. | example, see slides 62 and 63 of the `2016 LinuxCon |
  476. | EU <http://www2.rdrop.com/users/paulmck/scalability/paper/LinuxMM.201 |
  477. | 6.10.04c.LCE.pdf>`__ |
  478. | presentation. |
  479. +-----------------------------------------------------------------------+
  480. +-----------------------------------------------------------------------+
  481. | **Quick Quiz**: |
  482. +-----------------------------------------------------------------------+
  483. | The first and second guarantees require unbelievably strict ordering! |
  484. | Are all these memory barriers *really* required? |
  485. +-----------------------------------------------------------------------+
  486. | **Answer**: |
  487. +-----------------------------------------------------------------------+
  488. | Yes, they really are required. To see why the first guarantee is |
  489. | required, consider the following sequence of events: |
  490. | |
  491. | #. CPU 1: rcu_read_lock() |
  492. | #. CPU 1: ``q = rcu_dereference(gp); /* Very likely to return p. */`` |
  493. | #. CPU 0: ``list_del_rcu(p);`` |
  494. | #. CPU 0: synchronize_rcu() starts. |
  495. | #. CPU 1: ``do_something_with(q->a);`` |
  496. | ``/* No smp_mb(), so might happen after kfree(). */`` |
  497. | #. CPU 1: rcu_read_unlock() |
  498. | #. CPU 0: synchronize_rcu() returns. |
  499. | #. CPU 0: ``kfree(p);`` |
  500. | |
  501. | Therefore, there absolutely must be a full memory barrier between the |
  502. | end of the RCU read-side critical section and the end of the grace |
  503. | period. |
  504. | |
  505. | The sequence of events demonstrating the necessity of the second rule |
  506. | is roughly similar: |
  507. | |
  508. | #. CPU 0: ``list_del_rcu(p);`` |
  509. | #. CPU 0: synchronize_rcu() starts. |
  510. | #. CPU 1: rcu_read_lock() |
  511. | #. CPU 1: ``q = rcu_dereference(gp);`` |
  512. | ``/* Might return p if no memory barrier. */`` |
  513. | #. CPU 0: synchronize_rcu() returns. |
  514. | #. CPU 0: ``kfree(p);`` |
  515. | #. CPU 1: ``do_something_with(q->a); /* Boom!!! */`` |
  516. | #. CPU 1: rcu_read_unlock() |
  517. | |
  518. | And similarly, without a memory barrier between the beginning of the |
  519. | grace period and the beginning of the RCU read-side critical section, |
  520. | CPU 1 might end up accessing the freelist. |
  521. | |
  522. | The “as if” rule of course applies, so that any implementation that |
  523. | acts as if the appropriate memory barriers were in place is a correct |
  524. | implementation. That said, it is much easier to fool yourself into |
  525. | believing that you have adhered to the as-if rule than it is to |
  526. | actually adhere to it! |
  527. +-----------------------------------------------------------------------+
  528. +-----------------------------------------------------------------------+
  529. | **Quick Quiz**: |
  530. +-----------------------------------------------------------------------+
  531. | You claim that rcu_read_lock() and rcu_read_unlock() generate |
  532. | absolutely no code in some kernel builds. This means that the |
  533. | compiler might arbitrarily rearrange consecutive RCU read-side |
  534. | critical sections. Given such rearrangement, if a given RCU read-side |
  535. | critical section is done, how can you be sure that all prior RCU |
  536. | read-side critical sections are done? Won't the compiler |
  537. | rearrangements make that impossible to determine? |
  538. +-----------------------------------------------------------------------+
  539. | **Answer**: |
  540. +-----------------------------------------------------------------------+
  541. | In cases where rcu_read_lock() and rcu_read_unlock() generate |
  542. | absolutely no code, RCU infers quiescent states only at special |
  543. | locations, for example, within the scheduler. Because calls to |
  544. | schedule() had better prevent calling-code accesses to shared |
  545. | variables from being rearranged across the call to schedule(), if |
  546. | RCU detects the end of a given RCU read-side critical section, it |
  547. | will necessarily detect the end of all prior RCU read-side critical |
  548. | sections, no matter how aggressively the compiler scrambles the code. |
  549. | Again, this all assumes that the compiler cannot scramble code across |
  550. | calls to the scheduler, out of interrupt handlers, into the idle |
  551. | loop, into user-mode code, and so on. But if your kernel build allows |
  552. | that sort of scrambling, you have broken far more than just RCU! |
  553. +-----------------------------------------------------------------------+
  554. Note that these memory-barrier requirements do not replace the
  555. fundamental RCU requirement that a grace period wait for all
  556. pre-existing readers. On the contrary, the memory barriers called out in
  557. this section must operate in such a way as to *enforce* this fundamental
  558. requirement. Of course, different implementations enforce this
  559. requirement in different ways, but enforce it they must.
  560. RCU Primitives Guaranteed to Execute Unconditionally
  561. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  562. The common-case RCU primitives are unconditional. They are invoked, they
  563. do their job, and they return, with no possibility of error, and no need
  564. to retry. This is a key RCU design philosophy.
  565. However, this philosophy is pragmatic rather than pigheaded. If someone
  566. comes up with a good justification for a particular conditional RCU
  567. primitive, it might well be implemented and added. After all, this
  568. guarantee was reverse-engineered, not premeditated. The unconditional
  569. nature of the RCU primitives was initially an accident of
  570. implementation, and later experience with synchronization primitives
  571. with conditional primitives caused me to elevate this accident to a
  572. guarantee. Therefore, the justification for adding a conditional
  573. primitive to RCU would need to be based on detailed and compelling use
  574. cases.
  575. Guaranteed Read-to-Write Upgrade
  576. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  577. As far as RCU is concerned, it is always possible to carry out an update
  578. within an RCU read-side critical section. For example, that RCU
  579. read-side critical section might search for a given data element, and
  580. then might acquire the update-side spinlock in order to update that
  581. element, all while remaining in that RCU read-side critical section. Of
  582. course, it is necessary to exit the RCU read-side critical section
  583. before invoking synchronize_rcu(), however, this inconvenience can
  584. be avoided through use of the call_rcu() and kfree_rcu() API
  585. members described later in this document.
  586. +-----------------------------------------------------------------------+
  587. | **Quick Quiz**: |
  588. +-----------------------------------------------------------------------+
  589. | But how does the upgrade-to-write operation exclude other readers? |
  590. +-----------------------------------------------------------------------+
  591. | **Answer**: |
  592. +-----------------------------------------------------------------------+
  593. | It doesn't, just like normal RCU updates, which also do not exclude |
  594. | RCU readers. |
  595. +-----------------------------------------------------------------------+
  596. This guarantee allows lookup code to be shared between read-side and
  597. update-side code, and was premeditated, appearing in the earliest
  598. DYNIX/ptx RCU documentation.
  599. Fundamental Non-Requirements
  600. ----------------------------
  601. RCU provides extremely lightweight readers, and its read-side
  602. guarantees, though quite useful, are correspondingly lightweight. It is
  603. therefore all too easy to assume that RCU is guaranteeing more than it
  604. really is. Of course, the list of things that RCU does not guarantee is
  605. infinitely long, however, the following sections list a few
  606. non-guarantees that have caused confusion. Except where otherwise noted,
  607. these non-guarantees were premeditated.
  608. #. `Readers Impose Minimal Ordering`_
  609. #. `Readers Do Not Exclude Updaters`_
  610. #. `Updaters Only Wait For Old Readers`_
  611. #. `Grace Periods Don't Partition Read-Side Critical Sections`_
  612. #. `Read-Side Critical Sections Don't Partition Grace Periods`_
  613. Readers Impose Minimal Ordering
  614. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  615. Reader-side markers such as rcu_read_lock() and
  616. rcu_read_unlock() provide absolutely no ordering guarantees except
  617. through their interaction with the grace-period APIs such as
  618. synchronize_rcu(). To see this, consider the following pair of
  619. threads:
  620. ::
  621. 1 void thread0(void)
  622. 2 {
  623. 3 rcu_read_lock();
  624. 4 WRITE_ONCE(x, 1);
  625. 5 rcu_read_unlock();
  626. 6 rcu_read_lock();
  627. 7 WRITE_ONCE(y, 1);
  628. 8 rcu_read_unlock();
  629. 9 }
  630. 10
  631. 11 void thread1(void)
  632. 12 {
  633. 13 rcu_read_lock();
  634. 14 r1 = READ_ONCE(y);
  635. 15 rcu_read_unlock();
  636. 16 rcu_read_lock();
  637. 17 r2 = READ_ONCE(x);
  638. 18 rcu_read_unlock();
  639. 19 }
  640. After thread0() and thread1() execute concurrently, it is quite
  641. possible to have
  642. ::
  643. (r1 == 1 && r2 == 0)
  644. (that is, ``y`` appears to have been assigned before ``x``), which would
  645. not be possible if rcu_read_lock() and rcu_read_unlock() had
  646. much in the way of ordering properties. But they do not, so the CPU is
  647. within its rights to do significant reordering. This is by design: Any
  648. significant ordering constraints would slow down these fast-path APIs.
  649. +-----------------------------------------------------------------------+
  650. | **Quick Quiz**: |
  651. +-----------------------------------------------------------------------+
  652. | Can't the compiler also reorder this code? |
  653. +-----------------------------------------------------------------------+
  654. | **Answer**: |
  655. +-----------------------------------------------------------------------+
  656. | No, the volatile casts in READ_ONCE() and WRITE_ONCE() |
  657. | prevent the compiler from reordering in this particular case. |
  658. +-----------------------------------------------------------------------+
  659. Readers Do Not Exclude Updaters
  660. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  661. Neither rcu_read_lock() nor rcu_read_unlock() exclude updates.
  662. All they do is to prevent grace periods from ending. The following
  663. example illustrates this:
  664. ::
  665. 1 void thread0(void)
  666. 2 {
  667. 3 rcu_read_lock();
  668. 4 r1 = READ_ONCE(y);
  669. 5 if (r1) {
  670. 6 do_something_with_nonzero_x();
  671. 7 r2 = READ_ONCE(x);
  672. 8 WARN_ON(!r2); /* BUG!!! */
  673. 9 }
  674. 10 rcu_read_unlock();
  675. 11 }
  676. 12
  677. 13 void thread1(void)
  678. 14 {
  679. 15 spin_lock(&my_lock);
  680. 16 WRITE_ONCE(x, 1);
  681. 17 WRITE_ONCE(y, 1);
  682. 18 spin_unlock(&my_lock);
  683. 19 }
  684. If the thread0() function's rcu_read_lock() excluded the
  685. thread1() function's update, the WARN_ON() could never fire. But
  686. the fact is that rcu_read_lock() does not exclude much of anything
  687. aside from subsequent grace periods, of which thread1() has none, so
  688. the WARN_ON() can and does fire.
  689. Updaters Only Wait For Old Readers
  690. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  691. It might be tempting to assume that after synchronize_rcu()
  692. completes, there are no readers executing. This temptation must be
  693. avoided because new readers can start immediately after
  694. synchronize_rcu() starts, and synchronize_rcu() is under no
  695. obligation to wait for these new readers.
  696. +-----------------------------------------------------------------------+
  697. | **Quick Quiz**: |
  698. +-----------------------------------------------------------------------+
  699. | Suppose that synchronize_rcu() did wait until *all* readers had |
  700. | completed instead of waiting only on pre-existing readers. For how |
  701. | long would the updater be able to rely on there being no readers? |
  702. +-----------------------------------------------------------------------+
  703. | **Answer**: |
  704. +-----------------------------------------------------------------------+
  705. | For no time at all. Even if synchronize_rcu() were to wait until |
  706. | all readers had completed, a new reader might start immediately after |
  707. | synchronize_rcu() completed. Therefore, the code following |
  708. | synchronize_rcu() can *never* rely on there being no readers. |
  709. +-----------------------------------------------------------------------+
  710. Grace Periods Don't Partition Read-Side Critical Sections
  711. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  712. It is tempting to assume that if any part of one RCU read-side critical
  713. section precedes a given grace period, and if any part of another RCU
  714. read-side critical section follows that same grace period, then all of
  715. the first RCU read-side critical section must precede all of the second.
  716. However, this just isn't the case: A single grace period does not
  717. partition the set of RCU read-side critical sections. An example of this
  718. situation can be illustrated as follows, where ``x``, ``y``, and ``z``
  719. are initially all zero:
  720. ::
  721. 1 void thread0(void)
  722. 2 {
  723. 3 rcu_read_lock();
  724. 4 WRITE_ONCE(a, 1);
  725. 5 WRITE_ONCE(b, 1);
  726. 6 rcu_read_unlock();
  727. 7 }
  728. 8
  729. 9 void thread1(void)
  730. 10 {
  731. 11 r1 = READ_ONCE(a);
  732. 12 synchronize_rcu();
  733. 13 WRITE_ONCE(c, 1);
  734. 14 }
  735. 15
  736. 16 void thread2(void)
  737. 17 {
  738. 18 rcu_read_lock();
  739. 19 r2 = READ_ONCE(b);
  740. 20 r3 = READ_ONCE(c);
  741. 21 rcu_read_unlock();
  742. 22 }
  743. It turns out that the outcome:
  744. ::
  745. (r1 == 1 && r2 == 0 && r3 == 1)
  746. is entirely possible. The following figure show how this can happen,
  747. with each circled ``QS`` indicating the point at which RCU recorded a
  748. *quiescent state* for each thread, that is, a state in which RCU knows
  749. that the thread cannot be in the midst of an RCU read-side critical
  750. section that started before the current grace period:
  751. .. kernel-figure:: GPpartitionReaders1.svg
  752. If it is necessary to partition RCU read-side critical sections in this
  753. manner, it is necessary to use two grace periods, where the first grace
  754. period is known to end before the second grace period starts:
  755. ::
  756. 1 void thread0(void)
  757. 2 {
  758. 3 rcu_read_lock();
  759. 4 WRITE_ONCE(a, 1);
  760. 5 WRITE_ONCE(b, 1);
  761. 6 rcu_read_unlock();
  762. 7 }
  763. 8
  764. 9 void thread1(void)
  765. 10 {
  766. 11 r1 = READ_ONCE(a);
  767. 12 synchronize_rcu();
  768. 13 WRITE_ONCE(c, 1);
  769. 14 }
  770. 15
  771. 16 void thread2(void)
  772. 17 {
  773. 18 r2 = READ_ONCE(c);
  774. 19 synchronize_rcu();
  775. 20 WRITE_ONCE(d, 1);
  776. 21 }
  777. 22
  778. 23 void thread3(void)
  779. 24 {
  780. 25 rcu_read_lock();
  781. 26 r3 = READ_ONCE(b);
  782. 27 r4 = READ_ONCE(d);
  783. 28 rcu_read_unlock();
  784. 29 }
  785. Here, if ``(r1 == 1)``, then thread0()'s write to ``b`` must happen
  786. before the end of thread1()'s grace period. If in addition
  787. ``(r4 == 1)``, then thread3()'s read from ``b`` must happen after
  788. the beginning of thread2()'s grace period. If it is also the case
  789. that ``(r2 == 1)``, then the end of thread1()'s grace period must
  790. precede the beginning of thread2()'s grace period. This mean that
  791. the two RCU read-side critical sections cannot overlap, guaranteeing
  792. that ``(r3 == 1)``. As a result, the outcome:
  793. ::
  794. (r1 == 1 && r2 == 1 && r3 == 0 && r4 == 1)
  795. cannot happen.
  796. This non-requirement was also non-premeditated, but became apparent when
  797. studying RCU's interaction with memory ordering.
  798. Read-Side Critical Sections Don't Partition Grace Periods
  799. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  800. It is also tempting to assume that if an RCU read-side critical section
  801. happens between a pair of grace periods, then those grace periods cannot
  802. overlap. However, this temptation leads nowhere good, as can be
  803. illustrated by the following, with all variables initially zero:
  804. ::
  805. 1 void thread0(void)
  806. 2 {
  807. 3 rcu_read_lock();
  808. 4 WRITE_ONCE(a, 1);
  809. 5 WRITE_ONCE(b, 1);
  810. 6 rcu_read_unlock();
  811. 7 }
  812. 8
  813. 9 void thread1(void)
  814. 10 {
  815. 11 r1 = READ_ONCE(a);
  816. 12 synchronize_rcu();
  817. 13 WRITE_ONCE(c, 1);
  818. 14 }
  819. 15
  820. 16 void thread2(void)
  821. 17 {
  822. 18 rcu_read_lock();
  823. 19 WRITE_ONCE(d, 1);
  824. 20 r2 = READ_ONCE(c);
  825. 21 rcu_read_unlock();
  826. 22 }
  827. 23
  828. 24 void thread3(void)
  829. 25 {
  830. 26 r3 = READ_ONCE(d);
  831. 27 synchronize_rcu();
  832. 28 WRITE_ONCE(e, 1);
  833. 29 }
  834. 30
  835. 31 void thread4(void)
  836. 32 {
  837. 33 rcu_read_lock();
  838. 34 r4 = READ_ONCE(b);
  839. 35 r5 = READ_ONCE(e);
  840. 36 rcu_read_unlock();
  841. 37 }
  842. In this case, the outcome:
  843. ::
  844. (r1 == 1 && r2 == 1 && r3 == 1 && r4 == 0 && r5 == 1)
  845. is entirely possible, as illustrated below:
  846. .. kernel-figure:: ReadersPartitionGP1.svg
  847. Again, an RCU read-side critical section can overlap almost all of a
  848. given grace period, just so long as it does not overlap the entire grace
  849. period. As a result, an RCU read-side critical section cannot partition
  850. a pair of RCU grace periods.
  851. +-----------------------------------------------------------------------+
  852. | **Quick Quiz**: |
  853. +-----------------------------------------------------------------------+
  854. | How long a sequence of grace periods, each separated by an RCU |
  855. | read-side critical section, would be required to partition the RCU |
  856. | read-side critical sections at the beginning and end of the chain? |
  857. +-----------------------------------------------------------------------+
  858. | **Answer**: |
  859. +-----------------------------------------------------------------------+
  860. | In theory, an infinite number. In practice, an unknown number that is |
  861. | sensitive to both implementation details and timing considerations. |
  862. | Therefore, even in practice, RCU users must abide by the theoretical |
  863. | rather than the practical answer. |
  864. +-----------------------------------------------------------------------+
  865. Parallelism Facts of Life
  866. -------------------------
  867. These parallelism facts of life are by no means specific to RCU, but the
  868. RCU implementation must abide by them. They therefore bear repeating:
  869. #. Any CPU or task may be delayed at any time, and any attempts to avoid
  870. these delays by disabling preemption, interrupts, or whatever are
  871. completely futile. This is most obvious in preemptible user-level
  872. environments and in virtualized environments (where a given guest
  873. OS's VCPUs can be preempted at any time by the underlying
  874. hypervisor), but can also happen in bare-metal environments due to
  875. ECC errors, NMIs, and other hardware events. Although a delay of more
  876. than about 20 seconds can result in splats, the RCU implementation is
  877. obligated to use algorithms that can tolerate extremely long delays,
  878. but where “extremely long” is not long enough to allow wrap-around
  879. when incrementing a 64-bit counter.
  880. #. Both the compiler and the CPU can reorder memory accesses. Where it
  881. matters, RCU must use compiler directives and memory-barrier
  882. instructions to preserve ordering.
  883. #. Conflicting writes to memory locations in any given cache line will
  884. result in expensive cache misses. Greater numbers of concurrent
  885. writes and more-frequent concurrent writes will result in more
  886. dramatic slowdowns. RCU is therefore obligated to use algorithms that
  887. have sufficient locality to avoid significant performance and
  888. scalability problems.
  889. #. As a rough rule of thumb, only one CPU's worth of processing may be
  890. carried out under the protection of any given exclusive lock. RCU
  891. must therefore use scalable locking designs.
  892. #. Counters are finite, especially on 32-bit systems. RCU's use of
  893. counters must therefore tolerate counter wrap, or be designed such
  894. that counter wrap would take way more time than a single system is
  895. likely to run. An uptime of ten years is quite possible, a runtime of
  896. a century much less so. As an example of the latter, RCU's
  897. dyntick-idle nesting counter allows 54 bits for interrupt nesting
  898. level (this counter is 64 bits even on a 32-bit system). Overflowing
  899. this counter requires 2\ :sup:`54` half-interrupts on a given CPU
  900. without that CPU ever going idle. If a half-interrupt happened every
  901. microsecond, it would take 570 years of runtime to overflow this
  902. counter, which is currently believed to be an acceptably long time.
  903. #. Linux systems can have thousands of CPUs running a single Linux
  904. kernel in a single shared-memory environment. RCU must therefore pay
  905. close attention to high-end scalability.
  906. This last parallelism fact of life means that RCU must pay special
  907. attention to the preceding facts of life. The idea that Linux might
  908. scale to systems with thousands of CPUs would have been met with some
  909. skepticism in the 1990s, but these requirements would have otherwise
  910. have been unsurprising, even in the early 1990s.
  911. Quality-of-Implementation Requirements
  912. --------------------------------------
  913. These sections list quality-of-implementation requirements. Although an
  914. RCU implementation that ignores these requirements could still be used,
  915. it would likely be subject to limitations that would make it
  916. inappropriate for industrial-strength production use. Classes of
  917. quality-of-implementation requirements are as follows:
  918. #. `Specialization`_
  919. #. `Performance and Scalability`_
  920. #. `Forward Progress`_
  921. #. `Composability`_
  922. #. `Corner Cases`_
  923. These classes is covered in the following sections.
  924. Specialization
  925. ~~~~~~~~~~~~~~
  926. RCU is and always has been intended primarily for read-mostly
  927. situations, which means that RCU's read-side primitives are optimized,
  928. often at the expense of its update-side primitives. Experience thus far
  929. is captured by the following list of situations:
  930. #. Read-mostly data, where stale and inconsistent data is not a problem:
  931. RCU works great!
  932. #. Read-mostly data, where data must be consistent: RCU works well.
  933. #. Read-write data, where data must be consistent: RCU *might* work OK.
  934. Or not.
  935. #. Write-mostly data, where data must be consistent: RCU is very
  936. unlikely to be the right tool for the job, with the following
  937. exceptions, where RCU can provide:
  938. a. Existence guarantees for update-friendly mechanisms.
  939. b. Wait-free read-side primitives for real-time use.
  940. This focus on read-mostly situations means that RCU must interoperate
  941. with other synchronization primitives. For example, the add_gp() and
  942. remove_gp_synchronous() examples discussed earlier use RCU to
  943. protect readers and locking to coordinate updaters. However, the need
  944. extends much farther, requiring that a variety of synchronization
  945. primitives be legal within RCU read-side critical sections, including
  946. spinlocks, sequence locks, atomic operations, reference counters, and
  947. memory barriers.
  948. +-----------------------------------------------------------------------+
  949. | **Quick Quiz**: |
  950. +-----------------------------------------------------------------------+
  951. | What about sleeping locks? |
  952. +-----------------------------------------------------------------------+
  953. | **Answer**: |
  954. +-----------------------------------------------------------------------+
  955. | These are forbidden within Linux-kernel RCU read-side critical |
  956. | sections because it is not legal to place a quiescent state (in this |
  957. | case, voluntary context switch) within an RCU read-side critical |
  958. | section. However, sleeping locks may be used within userspace RCU |
  959. | read-side critical sections, and also within Linux-kernel sleepable |
  960. | RCU `(SRCU) <Sleepable RCU_>`__ read-side critical sections. In |
  961. | addition, the -rt patchset turns spinlocks into a sleeping locks so |
  962. | that the corresponding critical sections can be preempted, which also |
  963. | means that these sleeplockified spinlocks (but not other sleeping |
  964. | locks!) may be acquire within -rt-Linux-kernel RCU read-side critical |
  965. | sections. |
  966. | Note that it *is* legal for a normal RCU read-side critical section |
  967. | to conditionally acquire a sleeping locks (as in |
  968. | mutex_trylock()), but only as long as it does not loop |
  969. | indefinitely attempting to conditionally acquire that sleeping locks. |
  970. | The key point is that things like mutex_trylock() either return |
  971. | with the mutex held, or return an error indication if the mutex was |
  972. | not immediately available. Either way, mutex_trylock() returns |
  973. | immediately without sleeping. |
  974. +-----------------------------------------------------------------------+
  975. It often comes as a surprise that many algorithms do not require a
  976. consistent view of data, but many can function in that mode, with
  977. network routing being the poster child. Internet routing algorithms take
  978. significant time to propagate updates, so that by the time an update
  979. arrives at a given system, that system has been sending network traffic
  980. the wrong way for a considerable length of time. Having a few threads
  981. continue to send traffic the wrong way for a few more milliseconds is
  982. clearly not a problem: In the worst case, TCP retransmissions will
  983. eventually get the data where it needs to go. In general, when tracking
  984. the state of the universe outside of the computer, some level of
  985. inconsistency must be tolerated due to speed-of-light delays if nothing
  986. else.
  987. Furthermore, uncertainty about external state is inherent in many cases.
  988. For example, a pair of veterinarians might use heartbeat to determine
  989. whether or not a given cat was alive. But how long should they wait
  990. after the last heartbeat to decide that the cat is in fact dead? Waiting
  991. less than 400 milliseconds makes no sense because this would mean that a
  992. relaxed cat would be considered to cycle between death and life more
  993. than 100 times per minute. Moreover, just as with human beings, a cat's
  994. heart might stop for some period of time, so the exact wait period is a
  995. judgment call. One of our pair of veterinarians might wait 30 seconds
  996. before pronouncing the cat dead, while the other might insist on waiting
  997. a full minute. The two veterinarians would then disagree on the state of
  998. the cat during the final 30 seconds of the minute following the last
  999. heartbeat.
  1000. Interestingly enough, this same situation applies to hardware. When push
  1001. comes to shove, how do we tell whether or not some external server has
  1002. failed? We send messages to it periodically, and declare it failed if we
  1003. don't receive a response within a given period of time. Policy decisions
  1004. can usually tolerate short periods of inconsistency. The policy was
  1005. decided some time ago, and is only now being put into effect, so a few
  1006. milliseconds of delay is normally inconsequential.
  1007. However, there are algorithms that absolutely must see consistent data.
  1008. For example, the translation between a user-level SystemV semaphore ID
  1009. to the corresponding in-kernel data structure is protected by RCU, but
  1010. it is absolutely forbidden to update a semaphore that has just been
  1011. removed. In the Linux kernel, this need for consistency is accommodated
  1012. by acquiring spinlocks located in the in-kernel data structure from
  1013. within the RCU read-side critical section, and this is indicated by the
  1014. green box in the figure above. Many other techniques may be used, and
  1015. are in fact used within the Linux kernel.
  1016. In short, RCU is not required to maintain consistency, and other
  1017. mechanisms may be used in concert with RCU when consistency is required.
  1018. RCU's specialization allows it to do its job extremely well, and its
  1019. ability to interoperate with other synchronization mechanisms allows the
  1020. right mix of synchronization tools to be used for a given job.
  1021. Performance and Scalability
  1022. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1023. Energy efficiency is a critical component of performance today, and
  1024. Linux-kernel RCU implementations must therefore avoid unnecessarily
  1025. awakening idle CPUs. I cannot claim that this requirement was
  1026. premeditated. In fact, I learned of it during a telephone conversation
  1027. in which I was given “frank and open” feedback on the importance of
  1028. energy efficiency in battery-powered systems and on specific
  1029. energy-efficiency shortcomings of the Linux-kernel RCU implementation.
  1030. In my experience, the battery-powered embedded community will consider
  1031. any unnecessary wakeups to be extremely unfriendly acts. So much so that
  1032. mere Linux-kernel-mailing-list posts are insufficient to vent their ire.
  1033. Memory consumption is not particularly important for in most situations,
  1034. and has become decreasingly so as memory sizes have expanded and memory
  1035. costs have plummeted. However, as I learned from Matt Mackall's
  1036. `bloatwatch <http://elinux.org/Linux_Tiny-FAQ>`__ efforts, memory
  1037. footprint is critically important on single-CPU systems with
  1038. non-preemptible (``CONFIG_PREEMPTION=n``) kernels, and thus `tiny
  1039. RCU <https://lore.kernel.org/r/[email protected]>`__
  1040. was born. Josh Triplett has since taken over the small-memory banner
  1041. with his `Linux kernel tinification <https://tiny.wiki.kernel.org/>`__
  1042. project, which resulted in `SRCU <Sleepable RCU_>`__ becoming optional
  1043. for those kernels not needing it.
  1044. The remaining performance requirements are, for the most part,
  1045. unsurprising. For example, in keeping with RCU's read-side
  1046. specialization, rcu_dereference() should have negligible overhead
  1047. (for example, suppression of a few minor compiler optimizations).
  1048. Similarly, in non-preemptible environments, rcu_read_lock() and
  1049. rcu_read_unlock() should have exactly zero overhead.
  1050. In preemptible environments, in the case where the RCU read-side
  1051. critical section was not preempted (as will be the case for the
  1052. highest-priority real-time process), rcu_read_lock() and
  1053. rcu_read_unlock() should have minimal overhead. In particular, they
  1054. should not contain atomic read-modify-write operations, memory-barrier
  1055. instructions, preemption disabling, interrupt disabling, or backwards
  1056. branches. However, in the case where the RCU read-side critical section
  1057. was preempted, rcu_read_unlock() may acquire spinlocks and disable
  1058. interrupts. This is why it is better to nest an RCU read-side critical
  1059. section within a preempt-disable region than vice versa, at least in
  1060. cases where that critical section is short enough to avoid unduly
  1061. degrading real-time latencies.
  1062. The synchronize_rcu() grace-period-wait primitive is optimized for
  1063. throughput. It may therefore incur several milliseconds of latency in
  1064. addition to the duration of the longest RCU read-side critical section.
  1065. On the other hand, multiple concurrent invocations of
  1066. synchronize_rcu() are required to use batching optimizations so that
  1067. they can be satisfied by a single underlying grace-period-wait
  1068. operation. For example, in the Linux kernel, it is not unusual for a
  1069. single grace-period-wait operation to serve more than `1,000 separate
  1070. invocations <https://www.usenix.org/conference/2004-usenix-annual-technical-conference/making-rcu-safe-deep-sub-millisecond-response>`__
  1071. of synchronize_rcu(), thus amortizing the per-invocation overhead
  1072. down to nearly zero. However, the grace-period optimization is also
  1073. required to avoid measurable degradation of real-time scheduling and
  1074. interrupt latencies.
  1075. In some cases, the multi-millisecond synchronize_rcu() latencies are
  1076. unacceptable. In these cases, synchronize_rcu_expedited() may be
  1077. used instead, reducing the grace-period latency down to a few tens of
  1078. microseconds on small systems, at least in cases where the RCU read-side
  1079. critical sections are short. There are currently no special latency
  1080. requirements for synchronize_rcu_expedited() on large systems, but,
  1081. consistent with the empirical nature of the RCU specification, that is
  1082. subject to change. However, there most definitely are scalability
  1083. requirements: A storm of synchronize_rcu_expedited() invocations on
  1084. 4096 CPUs should at least make reasonable forward progress. In return
  1085. for its shorter latencies, synchronize_rcu_expedited() is permitted
  1086. to impose modest degradation of real-time latency on non-idle online
  1087. CPUs. Here, “modest” means roughly the same latency degradation as a
  1088. scheduling-clock interrupt.
  1089. There are a number of situations where even
  1090. synchronize_rcu_expedited()'s reduced grace-period latency is
  1091. unacceptable. In these situations, the asynchronous call_rcu() can
  1092. be used in place of synchronize_rcu() as follows:
  1093. ::
  1094. 1 struct foo {
  1095. 2 int a;
  1096. 3 int b;
  1097. 4 struct rcu_head rh;
  1098. 5 };
  1099. 6
  1100. 7 static void remove_gp_cb(struct rcu_head *rhp)
  1101. 8 {
  1102. 9 struct foo *p = container_of(rhp, struct foo, rh);
  1103. 10
  1104. 11 kfree(p);
  1105. 12 }
  1106. 13
  1107. 14 bool remove_gp_asynchronous(void)
  1108. 15 {
  1109. 16 struct foo *p;
  1110. 17
  1111. 18 spin_lock(&gp_lock);
  1112. 19 p = rcu_access_pointer(gp);
  1113. 20 if (!p) {
  1114. 21 spin_unlock(&gp_lock);
  1115. 22 return false;
  1116. 23 }
  1117. 24 rcu_assign_pointer(gp, NULL);
  1118. 25 call_rcu(&p->rh, remove_gp_cb);
  1119. 26 spin_unlock(&gp_lock);
  1120. 27 return true;
  1121. 28 }
  1122. A definition of ``struct foo`` is finally needed, and appears on
  1123. lines 1-5. The function remove_gp_cb() is passed to call_rcu()
  1124. on line 25, and will be invoked after the end of a subsequent grace
  1125. period. This gets the same effect as remove_gp_synchronous(), but
  1126. without forcing the updater to wait for a grace period to elapse. The
  1127. call_rcu() function may be used in a number of situations where
  1128. neither synchronize_rcu() nor synchronize_rcu_expedited() would
  1129. be legal, including within preempt-disable code, local_bh_disable()
  1130. code, interrupt-disable code, and interrupt handlers. However, even
  1131. call_rcu() is illegal within NMI handlers and from idle and offline
  1132. CPUs. The callback function (remove_gp_cb() in this case) will be
  1133. executed within softirq (software interrupt) environment within the
  1134. Linux kernel, either within a real softirq handler or under the
  1135. protection of local_bh_disable(). In both the Linux kernel and in
  1136. userspace, it is bad practice to write an RCU callback function that
  1137. takes too long. Long-running operations should be relegated to separate
  1138. threads or (in the Linux kernel) workqueues.
  1139. +-----------------------------------------------------------------------+
  1140. | **Quick Quiz**: |
  1141. +-----------------------------------------------------------------------+
  1142. | Why does line 19 use rcu_access_pointer()? After all, |
  1143. | call_rcu() on line 25 stores into the structure, which would |
  1144. | interact badly with concurrent insertions. Doesn't this mean that |
  1145. | rcu_dereference() is required? |
  1146. +-----------------------------------------------------------------------+
  1147. | **Answer**: |
  1148. +-----------------------------------------------------------------------+
  1149. | Presumably the ``->gp_lock`` acquired on line 18 excludes any |
  1150. | changes, including any insertions that rcu_dereference() would |
  1151. | protect against. Therefore, any insertions will be delayed until |
  1152. | after ``->gp_lock`` is released on line 25, which in turn means that |
  1153. | rcu_access_pointer() suffices. |
  1154. +-----------------------------------------------------------------------+
  1155. However, all that remove_gp_cb() is doing is invoking kfree() on
  1156. the data element. This is a common idiom, and is supported by
  1157. kfree_rcu(), which allows “fire and forget” operation as shown
  1158. below:
  1159. ::
  1160. 1 struct foo {
  1161. 2 int a;
  1162. 3 int b;
  1163. 4 struct rcu_head rh;
  1164. 5 };
  1165. 6
  1166. 7 bool remove_gp_faf(void)
  1167. 8 {
  1168. 9 struct foo *p;
  1169. 10
  1170. 11 spin_lock(&gp_lock);
  1171. 12 p = rcu_dereference(gp);
  1172. 13 if (!p) {
  1173. 14 spin_unlock(&gp_lock);
  1174. 15 return false;
  1175. 16 }
  1176. 17 rcu_assign_pointer(gp, NULL);
  1177. 18 kfree_rcu(p, rh);
  1178. 19 spin_unlock(&gp_lock);
  1179. 20 return true;
  1180. 21 }
  1181. Note that remove_gp_faf() simply invokes kfree_rcu() and
  1182. proceeds, without any need to pay any further attention to the
  1183. subsequent grace period and kfree(). It is permissible to invoke
  1184. kfree_rcu() from the same environments as for call_rcu().
  1185. Interestingly enough, DYNIX/ptx had the equivalents of call_rcu()
  1186. and kfree_rcu(), but not synchronize_rcu(). This was due to the
  1187. fact that RCU was not heavily used within DYNIX/ptx, so the very few
  1188. places that needed something like synchronize_rcu() simply
  1189. open-coded it.
  1190. +-----------------------------------------------------------------------+
  1191. | **Quick Quiz**: |
  1192. +-----------------------------------------------------------------------+
  1193. | Earlier it was claimed that call_rcu() and kfree_rcu() |
  1194. | allowed updaters to avoid being blocked by readers. But how can that |
  1195. | be correct, given that the invocation of the callback and the freeing |
  1196. | of the memory (respectively) must still wait for a grace period to |
  1197. | elapse? |
  1198. +-----------------------------------------------------------------------+
  1199. | **Answer**: |
  1200. +-----------------------------------------------------------------------+
  1201. | We could define things this way, but keep in mind that this sort of |
  1202. | definition would say that updates in garbage-collected languages |
  1203. | cannot complete until the next time the garbage collector runs, which |
  1204. | does not seem at all reasonable. The key point is that in most cases, |
  1205. | an updater using either call_rcu() or kfree_rcu() can proceed |
  1206. | to the next update as soon as it has invoked call_rcu() or |
  1207. | kfree_rcu(), without having to wait for a subsequent grace |
  1208. | period. |
  1209. +-----------------------------------------------------------------------+
  1210. But what if the updater must wait for the completion of code to be
  1211. executed after the end of the grace period, but has other tasks that can
  1212. be carried out in the meantime? The polling-style
  1213. get_state_synchronize_rcu() and cond_synchronize_rcu() functions
  1214. may be used for this purpose, as shown below:
  1215. ::
  1216. 1 bool remove_gp_poll(void)
  1217. 2 {
  1218. 3 struct foo *p;
  1219. 4 unsigned long s;
  1220. 5
  1221. 6 spin_lock(&gp_lock);
  1222. 7 p = rcu_access_pointer(gp);
  1223. 8 if (!p) {
  1224. 9 spin_unlock(&gp_lock);
  1225. 10 return false;
  1226. 11 }
  1227. 12 rcu_assign_pointer(gp, NULL);
  1228. 13 spin_unlock(&gp_lock);
  1229. 14 s = get_state_synchronize_rcu();
  1230. 15 do_something_while_waiting();
  1231. 16 cond_synchronize_rcu(s);
  1232. 17 kfree(p);
  1233. 18 return true;
  1234. 19 }
  1235. On line 14, get_state_synchronize_rcu() obtains a “cookie” from RCU,
  1236. then line 15 carries out other tasks, and finally, line 16 returns
  1237. immediately if a grace period has elapsed in the meantime, but otherwise
  1238. waits as required. The need for ``get_state_synchronize_rcu`` and
  1239. cond_synchronize_rcu() has appeared quite recently, so it is too
  1240. early to tell whether they will stand the test of time.
  1241. RCU thus provides a range of tools to allow updaters to strike the
  1242. required tradeoff between latency, flexibility and CPU overhead.
  1243. Forward Progress
  1244. ~~~~~~~~~~~~~~~~
  1245. In theory, delaying grace-period completion and callback invocation is
  1246. harmless. In practice, not only are memory sizes finite but also
  1247. callbacks sometimes do wakeups, and sufficiently deferred wakeups can be
  1248. difficult to distinguish from system hangs. Therefore, RCU must provide
  1249. a number of mechanisms to promote forward progress.
  1250. These mechanisms are not foolproof, nor can they be. For one simple
  1251. example, an infinite loop in an RCU read-side critical section must by
  1252. definition prevent later grace periods from ever completing. For a more
  1253. involved example, consider a 64-CPU system built with
  1254. ``CONFIG_RCU_NOCB_CPU=y`` and booted with ``rcu_nocbs=1-63``, where
  1255. CPUs 1 through 63 spin in tight loops that invoke call_rcu(). Even
  1256. if these tight loops also contain calls to cond_resched() (thus
  1257. allowing grace periods to complete), CPU 0 simply will not be able to
  1258. invoke callbacks as fast as the other 63 CPUs can register them, at
  1259. least not until the system runs out of memory. In both of these
  1260. examples, the Spiderman principle applies: With great power comes great
  1261. responsibility. However, short of this level of abuse, RCU is required
  1262. to ensure timely completion of grace periods and timely invocation of
  1263. callbacks.
  1264. RCU takes the following steps to encourage timely completion of grace
  1265. periods:
  1266. #. If a grace period fails to complete within 100 milliseconds, RCU
  1267. causes future invocations of cond_resched() on the holdout CPUs
  1268. to provide an RCU quiescent state. RCU also causes those CPUs'
  1269. need_resched() invocations to return ``true``, but only after the
  1270. corresponding CPU's next scheduling-clock.
  1271. #. CPUs mentioned in the ``nohz_full`` kernel boot parameter can run
  1272. indefinitely in the kernel without scheduling-clock interrupts, which
  1273. defeats the above need_resched() strategem. RCU will therefore
  1274. invoke resched_cpu() on any ``nohz_full`` CPUs still holding out
  1275. after 109 milliseconds.
  1276. #. In kernels built with ``CONFIG_RCU_BOOST=y``, if a given task that
  1277. has been preempted within an RCU read-side critical section is
  1278. holding out for more than 500 milliseconds, RCU will resort to
  1279. priority boosting.
  1280. #. If a CPU is still holding out 10 seconds into the grace period, RCU
  1281. will invoke resched_cpu() on it regardless of its ``nohz_full``
  1282. state.
  1283. The above values are defaults for systems running with ``HZ=1000``. They
  1284. will vary as the value of ``HZ`` varies, and can also be changed using
  1285. the relevant Kconfig options and kernel boot parameters. RCU currently
  1286. does not do much sanity checking of these parameters, so please use
  1287. caution when changing them. Note that these forward-progress measures
  1288. are provided only for RCU, not for `SRCU <Sleepable RCU_>`__ or `Tasks
  1289. RCU`_.
  1290. RCU takes the following steps in call_rcu() to encourage timely
  1291. invocation of callbacks when any given non-\ ``rcu_nocbs`` CPU has
  1292. 10,000 callbacks, or has 10,000 more callbacks than it had the last time
  1293. encouragement was provided:
  1294. #. Starts a grace period, if one is not already in progress.
  1295. #. Forces immediate checking for quiescent states, rather than waiting
  1296. for three milliseconds to have elapsed since the beginning of the
  1297. grace period.
  1298. #. Immediately tags the CPU's callbacks with their grace period
  1299. completion numbers, rather than waiting for the ``RCU_SOFTIRQ``
  1300. handler to get around to it.
  1301. #. Lifts callback-execution batch limits, which speeds up callback
  1302. invocation at the expense of degrading realtime response.
  1303. Again, these are default values when running at ``HZ=1000``, and can be
  1304. overridden. Again, these forward-progress measures are provided only for
  1305. RCU, not for `SRCU <Sleepable RCU_>`__ or `Tasks
  1306. RCU`_. Even for RCU, callback-invocation forward
  1307. progress for ``rcu_nocbs`` CPUs is much less well-developed, in part
  1308. because workloads benefiting from ``rcu_nocbs`` CPUs tend to invoke
  1309. call_rcu() relatively infrequently. If workloads emerge that need
  1310. both ``rcu_nocbs`` CPUs and high call_rcu() invocation rates, then
  1311. additional forward-progress work will be required.
  1312. Composability
  1313. ~~~~~~~~~~~~~
  1314. Composability has received much attention in recent years, perhaps in
  1315. part due to the collision of multicore hardware with object-oriented
  1316. techniques designed in single-threaded environments for single-threaded
  1317. use. And in theory, RCU read-side critical sections may be composed, and
  1318. in fact may be nested arbitrarily deeply. In practice, as with all
  1319. real-world implementations of composable constructs, there are
  1320. limitations.
  1321. Implementations of RCU for which rcu_read_lock() and
  1322. rcu_read_unlock() generate no code, such as Linux-kernel RCU when
  1323. ``CONFIG_PREEMPTION=n``, can be nested arbitrarily deeply. After all, there
  1324. is no overhead. Except that if all these instances of
  1325. rcu_read_lock() and rcu_read_unlock() are visible to the
  1326. compiler, compilation will eventually fail due to exhausting memory,
  1327. mass storage, or user patience, whichever comes first. If the nesting is
  1328. not visible to the compiler, as is the case with mutually recursive
  1329. functions each in its own translation unit, stack overflow will result.
  1330. If the nesting takes the form of loops, perhaps in the guise of tail
  1331. recursion, either the control variable will overflow or (in the Linux
  1332. kernel) you will get an RCU CPU stall warning. Nevertheless, this class
  1333. of RCU implementations is one of the most composable constructs in
  1334. existence.
  1335. RCU implementations that explicitly track nesting depth are limited by
  1336. the nesting-depth counter. For example, the Linux kernel's preemptible
  1337. RCU limits nesting to ``INT_MAX``. This should suffice for almost all
  1338. practical purposes. That said, a consecutive pair of RCU read-side
  1339. critical sections between which there is an operation that waits for a
  1340. grace period cannot be enclosed in another RCU read-side critical
  1341. section. This is because it is not legal to wait for a grace period
  1342. within an RCU read-side critical section: To do so would result either
  1343. in deadlock or in RCU implicitly splitting the enclosing RCU read-side
  1344. critical section, neither of which is conducive to a long-lived and
  1345. prosperous kernel.
  1346. It is worth noting that RCU is not alone in limiting composability. For
  1347. example, many transactional-memory implementations prohibit composing a
  1348. pair of transactions separated by an irrevocable operation (for example,
  1349. a network receive operation). For another example, lock-based critical
  1350. sections can be composed surprisingly freely, but only if deadlock is
  1351. avoided.
  1352. In short, although RCU read-side critical sections are highly
  1353. composable, care is required in some situations, just as is the case for
  1354. any other composable synchronization mechanism.
  1355. Corner Cases
  1356. ~~~~~~~~~~~~
  1357. A given RCU workload might have an endless and intense stream of RCU
  1358. read-side critical sections, perhaps even so intense that there was
  1359. never a point in time during which there was not at least one RCU
  1360. read-side critical section in flight. RCU cannot allow this situation to
  1361. block grace periods: As long as all the RCU read-side critical sections
  1362. are finite, grace periods must also be finite.
  1363. That said, preemptible RCU implementations could potentially result in
  1364. RCU read-side critical sections being preempted for long durations,
  1365. which has the effect of creating a long-duration RCU read-side critical
  1366. section. This situation can arise only in heavily loaded systems, but
  1367. systems using real-time priorities are of course more vulnerable.
  1368. Therefore, RCU priority boosting is provided to help deal with this
  1369. case. That said, the exact requirements on RCU priority boosting will
  1370. likely evolve as more experience accumulates.
  1371. Other workloads might have very high update rates. Although one can
  1372. argue that such workloads should instead use something other than RCU,
  1373. the fact remains that RCU must handle such workloads gracefully. This
  1374. requirement is another factor driving batching of grace periods, but it
  1375. is also the driving force behind the checks for large numbers of queued
  1376. RCU callbacks in the call_rcu() code path. Finally, high update
  1377. rates should not delay RCU read-side critical sections, although some
  1378. small read-side delays can occur when using
  1379. synchronize_rcu_expedited(), courtesy of this function's use of
  1380. smp_call_function_single().
  1381. Although all three of these corner cases were understood in the early
  1382. 1990s, a simple user-level test consisting of ``close(open(path))`` in a
  1383. tight loop in the early 2000s suddenly provided a much deeper
  1384. appreciation of the high-update-rate corner case. This test also
  1385. motivated addition of some RCU code to react to high update rates, for
  1386. example, if a given CPU finds itself with more than 10,000 RCU callbacks
  1387. queued, it will cause RCU to take evasive action by more aggressively
  1388. starting grace periods and more aggressively forcing completion of
  1389. grace-period processing. This evasive action causes the grace period to
  1390. complete more quickly, but at the cost of restricting RCU's batching
  1391. optimizations, thus increasing the CPU overhead incurred by that grace
  1392. period.
  1393. Software-Engineering Requirements
  1394. ---------------------------------
  1395. Between Murphy's Law and “To err is human”, it is necessary to guard
  1396. against mishaps and misuse:
  1397. #. It is all too easy to forget to use rcu_read_lock() everywhere
  1398. that it is needed, so kernels built with ``CONFIG_PROVE_RCU=y`` will
  1399. splat if rcu_dereference() is used outside of an RCU read-side
  1400. critical section. Update-side code can use
  1401. rcu_dereference_protected(), which takes a `lockdep
  1402. expression <https://lwn.net/Articles/371986/>`__ to indicate what is
  1403. providing the protection. If the indicated protection is not
  1404. provided, a lockdep splat is emitted.
  1405. Code shared between readers and updaters can use
  1406. rcu_dereference_check(), which also takes a lockdep expression,
  1407. and emits a lockdep splat if neither rcu_read_lock() nor the
  1408. indicated protection is in place. In addition,
  1409. rcu_dereference_raw() is used in those (hopefully rare) cases
  1410. where the required protection cannot be easily described. Finally,
  1411. rcu_read_lock_held() is provided to allow a function to verify
  1412. that it has been invoked within an RCU read-side critical section. I
  1413. was made aware of this set of requirements shortly after Thomas
  1414. Gleixner audited a number of RCU uses.
  1415. #. A given function might wish to check for RCU-related preconditions
  1416. upon entry, before using any other RCU API. The
  1417. rcu_lockdep_assert() does this job, asserting the expression in
  1418. kernels having lockdep enabled and doing nothing otherwise.
  1419. #. It is also easy to forget to use rcu_assign_pointer() and
  1420. rcu_dereference(), perhaps (incorrectly) substituting a simple
  1421. assignment. To catch this sort of error, a given RCU-protected
  1422. pointer may be tagged with ``__rcu``, after which sparse will
  1423. complain about simple-assignment accesses to that pointer. Arnd
  1424. Bergmann made me aware of this requirement, and also supplied the
  1425. needed `patch series <https://lwn.net/Articles/376011/>`__.
  1426. #. Kernels built with ``CONFIG_DEBUG_OBJECTS_RCU_HEAD=y`` will splat if
  1427. a data element is passed to call_rcu() twice in a row, without a
  1428. grace period in between. (This error is similar to a double free.)
  1429. The corresponding ``rcu_head`` structures that are dynamically
  1430. allocated are automatically tracked, but ``rcu_head`` structures
  1431. allocated on the stack must be initialized with
  1432. init_rcu_head_on_stack() and cleaned up with
  1433. destroy_rcu_head_on_stack(). Similarly, statically allocated
  1434. non-stack ``rcu_head`` structures must be initialized with
  1435. init_rcu_head() and cleaned up with destroy_rcu_head().
  1436. Mathieu Desnoyers made me aware of this requirement, and also
  1437. supplied the needed
  1438. `patch <https://lore.kernel.org/r/20100319013024.GA28456@Krystal>`__.
  1439. #. An infinite loop in an RCU read-side critical section will eventually
  1440. trigger an RCU CPU stall warning splat, with the duration of
  1441. “eventually” being controlled by the ``RCU_CPU_STALL_TIMEOUT``
  1442. ``Kconfig`` option, or, alternatively, by the
  1443. ``rcupdate.rcu_cpu_stall_timeout`` boot/sysfs parameter. However, RCU
  1444. is not obligated to produce this splat unless there is a grace period
  1445. waiting on that particular RCU read-side critical section.
  1446. Some extreme workloads might intentionally delay RCU grace periods,
  1447. and systems running those workloads can be booted with
  1448. ``rcupdate.rcu_cpu_stall_suppress`` to suppress the splats. This
  1449. kernel parameter may also be set via ``sysfs``. Furthermore, RCU CPU
  1450. stall warnings are counter-productive during sysrq dumps and during
  1451. panics. RCU therefore supplies the rcu_sysrq_start() and
  1452. rcu_sysrq_end() API members to be called before and after long
  1453. sysrq dumps. RCU also supplies the rcu_panic() notifier that is
  1454. automatically invoked at the beginning of a panic to suppress further
  1455. RCU CPU stall warnings.
  1456. This requirement made itself known in the early 1990s, pretty much
  1457. the first time that it was necessary to debug a CPU stall. That said,
  1458. the initial implementation in DYNIX/ptx was quite generic in
  1459. comparison with that of Linux.
  1460. #. Although it would be very good to detect pointers leaking out of RCU
  1461. read-side critical sections, there is currently no good way of doing
  1462. this. One complication is the need to distinguish between pointers
  1463. leaking and pointers that have been handed off from RCU to some other
  1464. synchronization mechanism, for example, reference counting.
  1465. #. In kernels built with ``CONFIG_RCU_TRACE=y``, RCU-related information
  1466. is provided via event tracing.
  1467. #. Open-coded use of rcu_assign_pointer() and rcu_dereference()
  1468. to create typical linked data structures can be surprisingly
  1469. error-prone. Therefore, RCU-protected `linked
  1470. lists <https://lwn.net/Articles/609973/#RCU%20List%20APIs>`__ and,
  1471. more recently, RCU-protected `hash
  1472. tables <https://lwn.net/Articles/612100/>`__ are available. Many
  1473. other special-purpose RCU-protected data structures are available in
  1474. the Linux kernel and the userspace RCU library.
  1475. #. Some linked structures are created at compile time, but still require
  1476. ``__rcu`` checking. The RCU_POINTER_INITIALIZER() macro serves
  1477. this purpose.
  1478. #. It is not necessary to use rcu_assign_pointer() when creating
  1479. linked structures that are to be published via a single external
  1480. pointer. The RCU_INIT_POINTER() macro is provided for this task.
  1481. This not a hard-and-fast list: RCU's diagnostic capabilities will
  1482. continue to be guided by the number and type of usage bugs found in
  1483. real-world RCU usage.
  1484. Linux Kernel Complications
  1485. --------------------------
  1486. The Linux kernel provides an interesting environment for all kinds of
  1487. software, including RCU. Some of the relevant points of interest are as
  1488. follows:
  1489. #. `Configuration`_
  1490. #. `Firmware Interface`_
  1491. #. `Early Boot`_
  1492. #. `Interrupts and NMIs`_
  1493. #. `Loadable Modules`_
  1494. #. `Hotplug CPU`_
  1495. #. `Scheduler and RCU`_
  1496. #. `Tracing and RCU`_
  1497. #. `Accesses to User Memory and RCU`_
  1498. #. `Energy Efficiency`_
  1499. #. `Scheduling-Clock Interrupts and RCU`_
  1500. #. `Memory Efficiency`_
  1501. #. `Performance, Scalability, Response Time, and Reliability`_
  1502. This list is probably incomplete, but it does give a feel for the most
  1503. notable Linux-kernel complications. Each of the following sections
  1504. covers one of the above topics.
  1505. Configuration
  1506. ~~~~~~~~~~~~~
  1507. RCU's goal is automatic configuration, so that almost nobody needs to
  1508. worry about RCU's ``Kconfig`` options. And for almost all users, RCU
  1509. does in fact work well “out of the box.”
  1510. However, there are specialized use cases that are handled by kernel boot
  1511. parameters and ``Kconfig`` options. Unfortunately, the ``Kconfig``
  1512. system will explicitly ask users about new ``Kconfig`` options, which
  1513. requires almost all of them be hidden behind a ``CONFIG_RCU_EXPERT``
  1514. ``Kconfig`` option.
  1515. This all should be quite obvious, but the fact remains that Linus
  1516. Torvalds recently had to
  1517. `remind <https://lore.kernel.org/r/CA+55aFy4wcCwaL4okTs8wXhGZ5h-ibecy_Meg9C4MNQrUnwMcg@mail.gmail.com>`__
  1518. me of this requirement.
  1519. Firmware Interface
  1520. ~~~~~~~~~~~~~~~~~~
  1521. In many cases, kernel obtains information about the system from the
  1522. firmware, and sometimes things are lost in translation. Or the
  1523. translation is accurate, but the original message is bogus.
  1524. For example, some systems' firmware overreports the number of CPUs,
  1525. sometimes by a large factor. If RCU naively believed the firmware, as it
  1526. used to do, it would create too many per-CPU kthreads. Although the
  1527. resulting system will still run correctly, the extra kthreads needlessly
  1528. consume memory and can cause confusion when they show up in ``ps``
  1529. listings.
  1530. RCU must therefore wait for a given CPU to actually come online before
  1531. it can allow itself to believe that the CPU actually exists. The
  1532. resulting “ghost CPUs” (which are never going to come online) cause a
  1533. number of `interesting
  1534. complications <https://paulmck.livejournal.com/37494.html>`__.
  1535. Early Boot
  1536. ~~~~~~~~~~
  1537. The Linux kernel's boot sequence is an interesting process, and RCU is
  1538. used early, even before rcu_init() is invoked. In fact, a number of
  1539. RCU's primitives can be used as soon as the initial task's
  1540. ``task_struct`` is available and the boot CPU's per-CPU variables are
  1541. set up. The read-side primitives (rcu_read_lock(),
  1542. rcu_read_unlock(), rcu_dereference(), and
  1543. rcu_access_pointer()) will operate normally very early on, as will
  1544. rcu_assign_pointer().
  1545. Although call_rcu() may be invoked at any time during boot,
  1546. callbacks are not guaranteed to be invoked until after all of RCU's
  1547. kthreads have been spawned, which occurs at early_initcall() time.
  1548. This delay in callback invocation is due to the fact that RCU does not
  1549. invoke callbacks until it is fully initialized, and this full
  1550. initialization cannot occur until after the scheduler has initialized
  1551. itself to the point where RCU can spawn and run its kthreads. In theory,
  1552. it would be possible to invoke callbacks earlier, however, this is not a
  1553. panacea because there would be severe restrictions on what operations
  1554. those callbacks could invoke.
  1555. Perhaps surprisingly, synchronize_rcu() and
  1556. synchronize_rcu_expedited(), will operate normally during very early
  1557. boot, the reason being that there is only one CPU and preemption is
  1558. disabled. This means that the call synchronize_rcu() (or friends)
  1559. itself is a quiescent state and thus a grace period, so the early-boot
  1560. implementation can be a no-op.
  1561. However, once the scheduler has spawned its first kthread, this early
  1562. boot trick fails for synchronize_rcu() (as well as for
  1563. synchronize_rcu_expedited()) in ``CONFIG_PREEMPTION=y`` kernels. The
  1564. reason is that an RCU read-side critical section might be preempted,
  1565. which means that a subsequent synchronize_rcu() really does have to
  1566. wait for something, as opposed to simply returning immediately.
  1567. Unfortunately, synchronize_rcu() can't do this until all of its
  1568. kthreads are spawned, which doesn't happen until some time during
  1569. early_initcalls() time. But this is no excuse: RCU is nevertheless
  1570. required to correctly handle synchronous grace periods during this time
  1571. period. Once all of its kthreads are up and running, RCU starts running
  1572. normally.
  1573. +-----------------------------------------------------------------------+
  1574. | **Quick Quiz**: |
  1575. +-----------------------------------------------------------------------+
  1576. | How can RCU possibly handle grace periods before all of its kthreads |
  1577. | have been spawned??? |
  1578. +-----------------------------------------------------------------------+
  1579. | **Answer**: |
  1580. +-----------------------------------------------------------------------+
  1581. | Very carefully! |
  1582. | During the “dead zone” between the time that the scheduler spawns the |
  1583. | first task and the time that all of RCU's kthreads have been spawned, |
  1584. | all synchronous grace periods are handled by the expedited |
  1585. | grace-period mechanism. At runtime, this expedited mechanism relies |
  1586. | on workqueues, but during the dead zone the requesting task itself |
  1587. | drives the desired expedited grace period. Because dead-zone |
  1588. | execution takes place within task context, everything works. Once the |
  1589. | dead zone ends, expedited grace periods go back to using workqueues, |
  1590. | as is required to avoid problems that would otherwise occur when a |
  1591. | user task received a POSIX signal while driving an expedited grace |
  1592. | period. |
  1593. | |
  1594. | And yes, this does mean that it is unhelpful to send POSIX signals to |
  1595. | random tasks between the time that the scheduler spawns its first |
  1596. | kthread and the time that RCU's kthreads have all been spawned. If |
  1597. | there ever turns out to be a good reason for sending POSIX signals |
  1598. | during that time, appropriate adjustments will be made. (If it turns |
  1599. | out that POSIX signals are sent during this time for no good reason, |
  1600. | other adjustments will be made, appropriate or otherwise.) |
  1601. +-----------------------------------------------------------------------+
  1602. I learned of these boot-time requirements as a result of a series of
  1603. system hangs.
  1604. Interrupts and NMIs
  1605. ~~~~~~~~~~~~~~~~~~~
  1606. The Linux kernel has interrupts, and RCU read-side critical sections are
  1607. legal within interrupt handlers and within interrupt-disabled regions of
  1608. code, as are invocations of call_rcu().
  1609. Some Linux-kernel architectures can enter an interrupt handler from
  1610. non-idle process context, and then just never leave it, instead
  1611. stealthily transitioning back to process context. This trick is
  1612. sometimes used to invoke system calls from inside the kernel. These
  1613. “half-interrupts” mean that RCU has to be very careful about how it
  1614. counts interrupt nesting levels. I learned of this requirement the hard
  1615. way during a rewrite of RCU's dyntick-idle code.
  1616. The Linux kernel has non-maskable interrupts (NMIs), and RCU read-side
  1617. critical sections are legal within NMI handlers. Thankfully, RCU
  1618. update-side primitives, including call_rcu(), are prohibited within
  1619. NMI handlers.
  1620. The name notwithstanding, some Linux-kernel architectures can have
  1621. nested NMIs, which RCU must handle correctly. Andy Lutomirski `surprised
  1622. me <https://lore.kernel.org/r/CALCETrXLq1y7e_dKFPgou-FKHB6Pu-r8+t-6Ds+8=va7anBWDA@mail.gmail.com>`__
  1623. with this requirement; he also kindly surprised me with `an
  1624. algorithm <https://lore.kernel.org/r/CALCETrXSY9JpW3uE6H8WYk81sg56qasA2aqmjMPsq5dOtzso=g@mail.gmail.com>`__
  1625. that meets this requirement.
  1626. Furthermore, NMI handlers can be interrupted by what appear to RCU to be
  1627. normal interrupts. One way that this can happen is for code that
  1628. directly invokes ct_irq_enter() and ct_irq_exit() to be called
  1629. from an NMI handler. This astonishing fact of life prompted the current
  1630. code structure, which has ct_irq_enter() invoking
  1631. ct_nmi_enter() and ct_irq_exit() invoking ct_nmi_exit().
  1632. And yes, I also learned of this requirement the hard way.
  1633. Loadable Modules
  1634. ~~~~~~~~~~~~~~~~
  1635. The Linux kernel has loadable modules, and these modules can also be
  1636. unloaded. After a given module has been unloaded, any attempt to call
  1637. one of its functions results in a segmentation fault. The module-unload
  1638. functions must therefore cancel any delayed calls to loadable-module
  1639. functions, for example, any outstanding mod_timer() must be dealt
  1640. with via del_timer_sync() or similar.
  1641. Unfortunately, there is no way to cancel an RCU callback; once you
  1642. invoke call_rcu(), the callback function is eventually going to be
  1643. invoked, unless the system goes down first. Because it is normally
  1644. considered socially irresponsible to crash the system in response to a
  1645. module unload request, we need some other way to deal with in-flight RCU
  1646. callbacks.
  1647. RCU therefore provides rcu_barrier(), which waits until all
  1648. in-flight RCU callbacks have been invoked. If a module uses
  1649. call_rcu(), its exit function should therefore prevent any future
  1650. invocation of call_rcu(), then invoke rcu_barrier(). In theory,
  1651. the underlying module-unload code could invoke rcu_barrier()
  1652. unconditionally, but in practice this would incur unacceptable
  1653. latencies.
  1654. Nikita Danilov noted this requirement for an analogous
  1655. filesystem-unmount situation, and Dipankar Sarma incorporated
  1656. rcu_barrier() into RCU. The need for rcu_barrier() for module
  1657. unloading became apparent later.
  1658. .. important::
  1659. The rcu_barrier() function is not, repeat,
  1660. *not*, obligated to wait for a grace period. It is instead only required
  1661. to wait for RCU callbacks that have already been posted. Therefore, if
  1662. there are no RCU callbacks posted anywhere in the system,
  1663. rcu_barrier() is within its rights to return immediately. Even if
  1664. there are callbacks posted, rcu_barrier() does not necessarily need
  1665. to wait for a grace period.
  1666. +-----------------------------------------------------------------------+
  1667. | **Quick Quiz**: |
  1668. +-----------------------------------------------------------------------+
  1669. | Wait a minute! Each RCU callbacks must wait for a grace period to |
  1670. | complete, and rcu_barrier() must wait for each pre-existing |
  1671. | callback to be invoked. Doesn't rcu_barrier() therefore need to |
  1672. | wait for a full grace period if there is even one callback posted |
  1673. | anywhere in the system? |
  1674. +-----------------------------------------------------------------------+
  1675. | **Answer**: |
  1676. +-----------------------------------------------------------------------+
  1677. | Absolutely not!!! |
  1678. | Yes, each RCU callbacks must wait for a grace period to complete, but |
  1679. | it might well be partly (or even completely) finished waiting by the |
  1680. | time rcu_barrier() is invoked. In that case, rcu_barrier() |
  1681. | need only wait for the remaining portion of the grace period to |
  1682. | elapse. So even if there are quite a few callbacks posted, |
  1683. | rcu_barrier() might well return quite quickly. |
  1684. | |
  1685. | So if you need to wait for a grace period as well as for all |
  1686. | pre-existing callbacks, you will need to invoke both |
  1687. | synchronize_rcu() and rcu_barrier(). If latency is a concern, |
  1688. | you can always use workqueues to invoke them concurrently. |
  1689. +-----------------------------------------------------------------------+
  1690. Hotplug CPU
  1691. ~~~~~~~~~~~
  1692. The Linux kernel supports CPU hotplug, which means that CPUs can come
  1693. and go. It is of course illegal to use any RCU API member from an
  1694. offline CPU, with the exception of `SRCU <Sleepable RCU_>`__ read-side
  1695. critical sections. This requirement was present from day one in
  1696. DYNIX/ptx, but on the other hand, the Linux kernel's CPU-hotplug
  1697. implementation is “interesting.”
  1698. The Linux-kernel CPU-hotplug implementation has notifiers that are used
  1699. to allow the various kernel subsystems (including RCU) to respond
  1700. appropriately to a given CPU-hotplug operation. Most RCU operations may
  1701. be invoked from CPU-hotplug notifiers, including even synchronous
  1702. grace-period operations such as (synchronize_rcu() and
  1703. synchronize_rcu_expedited()). However, these synchronous operations
  1704. do block and therefore cannot be invoked from notifiers that execute via
  1705. stop_machine(), specifically those between the ``CPUHP_AP_OFFLINE``
  1706. and ``CPUHP_AP_ONLINE`` states.
  1707. In addition, all-callback-wait operations such as rcu_barrier() may
  1708. not be invoked from any CPU-hotplug notifier. This restriction is due
  1709. to the fact that there are phases of CPU-hotplug operations where the
  1710. outgoing CPU's callbacks will not be invoked until after the CPU-hotplug
  1711. operation ends, which could also result in deadlock. Furthermore,
  1712. rcu_barrier() blocks CPU-hotplug operations during its execution,
  1713. which results in another type of deadlock when invoked from a CPU-hotplug
  1714. notifier.
  1715. Finally, RCU must avoid deadlocks due to interaction between hotplug,
  1716. timers and grace period processing. It does so by maintaining its own set
  1717. of books that duplicate the centrally maintained ``cpu_online_mask``,
  1718. and also by reporting quiescent states explicitly when a CPU goes
  1719. offline. This explicit reporting of quiescent states avoids any need
  1720. for the force-quiescent-state loop (FQS) to report quiescent states for
  1721. offline CPUs. However, as a debugging measure, the FQS loop does splat
  1722. if offline CPUs block an RCU grace period for too long.
  1723. An offline CPU's quiescent state will be reported either:
  1724. 1. As the CPU goes offline using RCU's hotplug notifier (rcu_report_dead()).
  1725. 2. When grace period initialization (rcu_gp_init()) detects a
  1726. race either with CPU offlining or with a task unblocking on a leaf
  1727. ``rcu_node`` structure whose CPUs are all offline.
  1728. The CPU-online path (rcu_cpu_starting()) should never need to report
  1729. a quiescent state for an offline CPU. However, as a debugging measure,
  1730. it does emit a warning if a quiescent state was not already reported
  1731. for that CPU.
  1732. During the checking/modification of RCU's hotplug bookkeeping, the
  1733. corresponding CPU's leaf node lock is held. This avoids race conditions
  1734. between RCU's hotplug notifier hooks, the grace period initialization
  1735. code, and the FQS loop, all of which refer to or modify this bookkeeping.
  1736. Scheduler and RCU
  1737. ~~~~~~~~~~~~~~~~~
  1738. RCU makes use of kthreads, and it is necessary to avoid excessive CPU-time
  1739. accumulation by these kthreads. This requirement was no surprise, but
  1740. RCU's violation of it when running context-switch-heavy workloads when
  1741. built with ``CONFIG_NO_HZ_FULL=y`` `did come as a surprise
  1742. [PDF] <http://www.rdrop.com/users/paulmck/scalability/paper/BareMetal.2015.01.15b.pdf>`__.
  1743. RCU has made good progress towards meeting this requirement, even for
  1744. context-switch-heavy ``CONFIG_NO_HZ_FULL=y`` workloads, but there is
  1745. room for further improvement.
  1746. There is no longer any prohibition against holding any of
  1747. scheduler's runqueue or priority-inheritance spinlocks across an
  1748. rcu_read_unlock(), even if interrupts and preemption were enabled
  1749. somewhere within the corresponding RCU read-side critical section.
  1750. Therefore, it is now perfectly legal to execute rcu_read_lock()
  1751. with preemption enabled, acquire one of the scheduler locks, and hold
  1752. that lock across the matching rcu_read_unlock().
  1753. Similarly, the RCU flavor consolidation has removed the need for negative
  1754. nesting. The fact that interrupt-disabled regions of code act as RCU
  1755. read-side critical sections implicitly avoids earlier issues that used
  1756. to result in destructive recursion via interrupt handler's use of RCU.
  1757. Tracing and RCU
  1758. ~~~~~~~~~~~~~~~
  1759. It is possible to use tracing on RCU code, but tracing itself uses RCU.
  1760. For this reason, rcu_dereference_raw_check() is provided for use
  1761. by tracing, which avoids the destructive recursion that could otherwise
  1762. ensue. This API is also used by virtualization in some architectures,
  1763. where RCU readers execute in environments in which tracing cannot be
  1764. used. The tracing folks both located the requirement and provided the
  1765. needed fix, so this surprise requirement was relatively painless.
  1766. Accesses to User Memory and RCU
  1767. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1768. The kernel needs to access user-space memory, for example, to access data
  1769. referenced by system-call parameters. The get_user() macro does this job.
  1770. However, user-space memory might well be paged out, which means that
  1771. get_user() might well page-fault and thus block while waiting for the
  1772. resulting I/O to complete. It would be a very bad thing for the compiler to
  1773. reorder a get_user() invocation into an RCU read-side critical section.
  1774. For example, suppose that the source code looked like this:
  1775. ::
  1776. 1 rcu_read_lock();
  1777. 2 p = rcu_dereference(gp);
  1778. 3 v = p->value;
  1779. 4 rcu_read_unlock();
  1780. 5 get_user(user_v, user_p);
  1781. 6 do_something_with(v, user_v);
  1782. The compiler must not be permitted to transform this source code into
  1783. the following:
  1784. ::
  1785. 1 rcu_read_lock();
  1786. 2 p = rcu_dereference(gp);
  1787. 3 get_user(user_v, user_p); // BUG: POSSIBLE PAGE FAULT!!!
  1788. 4 v = p->value;
  1789. 5 rcu_read_unlock();
  1790. 6 do_something_with(v, user_v);
  1791. If the compiler did make this transformation in a ``CONFIG_PREEMPTION=n`` kernel
  1792. build, and if get_user() did page fault, the result would be a quiescent
  1793. state in the middle of an RCU read-side critical section. This misplaced
  1794. quiescent state could result in line 4 being a use-after-free access,
  1795. which could be bad for your kernel's actuarial statistics. Similar examples
  1796. can be constructed with the call to get_user() preceding the
  1797. rcu_read_lock().
  1798. Unfortunately, get_user() doesn't have any particular ordering properties,
  1799. and in some architectures the underlying ``asm`` isn't even marked
  1800. ``volatile``. And even if it was marked ``volatile``, the above access to
  1801. ``p->value`` is not volatile, so the compiler would not have any reason to keep
  1802. those two accesses in order.
  1803. Therefore, the Linux-kernel definitions of rcu_read_lock() and
  1804. rcu_read_unlock() must act as compiler barriers, at least for outermost
  1805. instances of rcu_read_lock() and rcu_read_unlock() within a nested set
  1806. of RCU read-side critical sections.
  1807. Energy Efficiency
  1808. ~~~~~~~~~~~~~~~~~
  1809. Interrupting idle CPUs is considered socially unacceptable, especially
  1810. by people with battery-powered embedded systems. RCU therefore conserves
  1811. energy by detecting which CPUs are idle, including tracking CPUs that
  1812. have been interrupted from idle. This is a large part of the
  1813. energy-efficiency requirement, so I learned of this via an irate phone
  1814. call.
  1815. Because RCU avoids interrupting idle CPUs, it is illegal to execute an
  1816. RCU read-side critical section on an idle CPU. (Kernels built with
  1817. ``CONFIG_PROVE_RCU=y`` will splat if you try it.) The RCU_NONIDLE()
  1818. macro and ``_rcuidle`` event tracing is provided to work around this
  1819. restriction. In addition, rcu_is_watching() may be used to test
  1820. whether or not it is currently legal to run RCU read-side critical
  1821. sections on this CPU. I learned of the need for diagnostics on the one
  1822. hand and RCU_NONIDLE() on the other while inspecting idle-loop code.
  1823. Steven Rostedt supplied ``_rcuidle`` event tracing, which is used quite
  1824. heavily in the idle loop. However, there are some restrictions on the
  1825. code placed within RCU_NONIDLE():
  1826. #. Blocking is prohibited. In practice, this is not a serious
  1827. restriction given that idle tasks are prohibited from blocking to
  1828. begin with.
  1829. #. Although nesting RCU_NONIDLE() is permitted, they cannot nest
  1830. indefinitely deeply. However, given that they can be nested on the
  1831. order of a million deep, even on 32-bit systems, this should not be a
  1832. serious restriction. This nesting limit would probably be reached
  1833. long after the compiler OOMed or the stack overflowed.
  1834. #. Any code path that enters RCU_NONIDLE() must sequence out of that
  1835. same RCU_NONIDLE(). For example, the following is grossly
  1836. illegal:
  1837. ::
  1838. 1 RCU_NONIDLE({
  1839. 2 do_something();
  1840. 3 goto bad_idea; /* BUG!!! */
  1841. 4 do_something_else();});
  1842. 5 bad_idea:
  1843. It is just as illegal to transfer control into the middle of
  1844. RCU_NONIDLE()'s argument. Yes, in theory, you could transfer in
  1845. as long as you also transferred out, but in practice you could also
  1846. expect to get sharply worded review comments.
  1847. It is similarly socially unacceptable to interrupt an ``nohz_full`` CPU
  1848. running in userspace. RCU must therefore track ``nohz_full`` userspace
  1849. execution. RCU must therefore be able to sample state at two points in
  1850. time, and be able to determine whether or not some other CPU spent any
  1851. time idle and/or executing in userspace.
  1852. These energy-efficiency requirements have proven quite difficult to
  1853. understand and to meet, for example, there have been more than five
  1854. clean-sheet rewrites of RCU's energy-efficiency code, the last of which
  1855. was finally able to demonstrate `real energy savings running on real
  1856. hardware
  1857. [PDF] <http://www.rdrop.com/users/paulmck/realtime/paper/AMPenergy.2013.04.19a.pdf>`__.
  1858. As noted earlier, I learned of many of these requirements via angry
  1859. phone calls: Flaming me on the Linux-kernel mailing list was apparently
  1860. not sufficient to fully vent their ire at RCU's energy-efficiency bugs!
  1861. Scheduling-Clock Interrupts and RCU
  1862. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1863. The kernel transitions between in-kernel non-idle execution, userspace
  1864. execution, and the idle loop. Depending on kernel configuration, RCU
  1865. handles these states differently:
  1866. +-----------------+------------------+------------------+-----------------+
  1867. | ``HZ`` Kconfig | In-Kernel | Usermode | Idle |
  1868. +=================+==================+==================+=================+
  1869. | ``HZ_PERIODIC`` | Can rely on | Can rely on | Can rely on |
  1870. | | scheduling-clock | scheduling-clock | RCU's |
  1871. | | interrupt. | interrupt and | dyntick-idle |
  1872. | | | its detection | detection. |
  1873. | | | of interrupt | |
  1874. | | | from usermode. | |
  1875. +-----------------+------------------+------------------+-----------------+
  1876. | ``NO_HZ_IDLE`` | Can rely on | Can rely on | Can rely on |
  1877. | | scheduling-clock | scheduling-clock | RCU's |
  1878. | | interrupt. | interrupt and | dyntick-idle |
  1879. | | | its detection | detection. |
  1880. | | | of interrupt | |
  1881. | | | from usermode. | |
  1882. +-----------------+------------------+------------------+-----------------+
  1883. | ``NO_HZ_FULL`` | Can only | Can rely on | Can rely on |
  1884. | | sometimes rely | RCU's | RCU's |
  1885. | | on | dyntick-idle | dyntick-idle |
  1886. | | scheduling-clock | detection. | detection. |
  1887. | | interrupt. In | | |
  1888. | | other cases, it | | |
  1889. | | is necessary to | | |
  1890. | | bound kernel | | |
  1891. | | execution times | | |
  1892. | | and/or use | | |
  1893. | | IPIs. | | |
  1894. +-----------------+------------------+------------------+-----------------+
  1895. +-----------------------------------------------------------------------+
  1896. | **Quick Quiz**: |
  1897. +-----------------------------------------------------------------------+
  1898. | Why can't ``NO_HZ_FULL`` in-kernel execution rely on the |
  1899. | scheduling-clock interrupt, just like ``HZ_PERIODIC`` and |
  1900. | ``NO_HZ_IDLE`` do? |
  1901. +-----------------------------------------------------------------------+
  1902. | **Answer**: |
  1903. +-----------------------------------------------------------------------+
  1904. | Because, as a performance optimization, ``NO_HZ_FULL`` does not |
  1905. | necessarily re-enable the scheduling-clock interrupt on entry to each |
  1906. | and every system call. |
  1907. +-----------------------------------------------------------------------+
  1908. However, RCU must be reliably informed as to whether any given CPU is
  1909. currently in the idle loop, and, for ``NO_HZ_FULL``, also whether that
  1910. CPU is executing in usermode, as discussed
  1911. `earlier <Energy Efficiency_>`__. It also requires that the
  1912. scheduling-clock interrupt be enabled when RCU needs it to be:
  1913. #. If a CPU is either idle or executing in usermode, and RCU believes it
  1914. is non-idle, the scheduling-clock tick had better be running.
  1915. Otherwise, you will get RCU CPU stall warnings. Or at best, very long
  1916. (11-second) grace periods, with a pointless IPI waking the CPU from
  1917. time to time.
  1918. #. If a CPU is in a portion of the kernel that executes RCU read-side
  1919. critical sections, and RCU believes this CPU to be idle, you will get
  1920. random memory corruption. **DON'T DO THIS!!!**
  1921. This is one reason to test with lockdep, which will complain about
  1922. this sort of thing.
  1923. #. If a CPU is in a portion of the kernel that is absolutely positively
  1924. no-joking guaranteed to never execute any RCU read-side critical
  1925. sections, and RCU believes this CPU to be idle, no problem. This
  1926. sort of thing is used by some architectures for light-weight
  1927. exception handlers, which can then avoid the overhead of
  1928. ct_irq_enter() and ct_irq_exit() at exception entry and
  1929. exit, respectively. Some go further and avoid the entireties of
  1930. irq_enter() and irq_exit().
  1931. Just make very sure you are running some of your tests with
  1932. ``CONFIG_PROVE_RCU=y``, just in case one of your code paths was in
  1933. fact joking about not doing RCU read-side critical sections.
  1934. #. If a CPU is executing in the kernel with the scheduling-clock
  1935. interrupt disabled and RCU believes this CPU to be non-idle, and if
  1936. the CPU goes idle (from an RCU perspective) every few jiffies, no
  1937. problem. It is usually OK for there to be the occasional gap between
  1938. idle periods of up to a second or so.
  1939. If the gap grows too long, you get RCU CPU stall warnings.
  1940. #. If a CPU is either idle or executing in usermode, and RCU believes it
  1941. to be idle, of course no problem.
  1942. #. If a CPU is executing in the kernel, the kernel code path is passing
  1943. through quiescent states at a reasonable frequency (preferably about
  1944. once per few jiffies, but the occasional excursion to a second or so
  1945. is usually OK) and the scheduling-clock interrupt is enabled, of
  1946. course no problem.
  1947. If the gap between a successive pair of quiescent states grows too
  1948. long, you get RCU CPU stall warnings.
  1949. +-----------------------------------------------------------------------+
  1950. | **Quick Quiz**: |
  1951. +-----------------------------------------------------------------------+
  1952. | But what if my driver has a hardware interrupt handler that can run |
  1953. | for many seconds? I cannot invoke schedule() from an hardware |
  1954. | interrupt handler, after all! |
  1955. +-----------------------------------------------------------------------+
  1956. | **Answer**: |
  1957. +-----------------------------------------------------------------------+
  1958. | One approach is to do ``ct_irq_exit();ct_irq_enter();`` every so |
  1959. | often. But given that long-running interrupt handlers can cause other |
  1960. | problems, not least for response time, shouldn't you work to keep |
  1961. | your interrupt handler's runtime within reasonable bounds? |
  1962. +-----------------------------------------------------------------------+
  1963. But as long as RCU is properly informed of kernel state transitions
  1964. between in-kernel execution, usermode execution, and idle, and as long
  1965. as the scheduling-clock interrupt is enabled when RCU needs it to be,
  1966. you can rest assured that the bugs you encounter will be in some other
  1967. part of RCU or some other part of the kernel!
  1968. Memory Efficiency
  1969. ~~~~~~~~~~~~~~~~~
  1970. Although small-memory non-realtime systems can simply use Tiny RCU, code
  1971. size is only one aspect of memory efficiency. Another aspect is the size
  1972. of the ``rcu_head`` structure used by call_rcu() and
  1973. kfree_rcu(). Although this structure contains nothing more than a
  1974. pair of pointers, it does appear in many RCU-protected data structures,
  1975. including some that are size critical. The ``page`` structure is a case
  1976. in point, as evidenced by the many occurrences of the ``union`` keyword
  1977. within that structure.
  1978. This need for memory efficiency is one reason that RCU uses hand-crafted
  1979. singly linked lists to track the ``rcu_head`` structures that are
  1980. waiting for a grace period to elapse. It is also the reason why
  1981. ``rcu_head`` structures do not contain debug information, such as fields
  1982. tracking the file and line of the call_rcu() or kfree_rcu() that
  1983. posted them. Although this information might appear in debug-only kernel
  1984. builds at some point, in the meantime, the ``->func`` field will often
  1985. provide the needed debug information.
  1986. However, in some cases, the need for memory efficiency leads to even
  1987. more extreme measures. Returning to the ``page`` structure, the
  1988. ``rcu_head`` field shares storage with a great many other structures
  1989. that are used at various points in the corresponding page's lifetime. In
  1990. order to correctly resolve certain `race
  1991. conditions <https://lore.kernel.org/r/1439976106-137226-1-git-send-email-kirill.shutemov@linux.intel.com>`__,
  1992. the Linux kernel's memory-management subsystem needs a particular bit to
  1993. remain zero during all phases of grace-period processing, and that bit
  1994. happens to map to the bottom bit of the ``rcu_head`` structure's
  1995. ``->next`` field. RCU makes this guarantee as long as call_rcu() is
  1996. used to post the callback, as opposed to kfree_rcu() or some future
  1997. “lazy” variant of call_rcu() that might one day be created for
  1998. energy-efficiency purposes.
  1999. That said, there are limits. RCU requires that the ``rcu_head``
  2000. structure be aligned to a two-byte boundary, and passing a misaligned
  2001. ``rcu_head`` structure to one of the call_rcu() family of functions
  2002. will result in a splat. It is therefore necessary to exercise caution
  2003. when packing structures containing fields of type ``rcu_head``. Why not
  2004. a four-byte or even eight-byte alignment requirement? Because the m68k
  2005. architecture provides only two-byte alignment, and thus acts as
  2006. alignment's least common denominator.
  2007. The reason for reserving the bottom bit of pointers to ``rcu_head``
  2008. structures is to leave the door open to “lazy” callbacks whose
  2009. invocations can safely be deferred. Deferring invocation could
  2010. potentially have energy-efficiency benefits, but only if the rate of
  2011. non-lazy callbacks decreases significantly for some important workload.
  2012. In the meantime, reserving the bottom bit keeps this option open in case
  2013. it one day becomes useful.
  2014. Performance, Scalability, Response Time, and Reliability
  2015. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2016. Expanding on the `earlier
  2017. discussion <Performance and Scalability_>`__, RCU is used heavily by
  2018. hot code paths in performance-critical portions of the Linux kernel's
  2019. networking, security, virtualization, and scheduling code paths. RCU
  2020. must therefore use efficient implementations, especially in its
  2021. read-side primitives. To that end, it would be good if preemptible RCU's
  2022. implementation of rcu_read_lock() could be inlined, however, doing
  2023. this requires resolving ``#include`` issues with the ``task_struct``
  2024. structure.
  2025. The Linux kernel supports hardware configurations with up to 4096 CPUs,
  2026. which means that RCU must be extremely scalable. Algorithms that involve
  2027. frequent acquisitions of global locks or frequent atomic operations on
  2028. global variables simply cannot be tolerated within the RCU
  2029. implementation. RCU therefore makes heavy use of a combining tree based
  2030. on the ``rcu_node`` structure. RCU is required to tolerate all CPUs
  2031. continuously invoking any combination of RCU's runtime primitives with
  2032. minimal per-operation overhead. In fact, in many cases, increasing load
  2033. must *decrease* the per-operation overhead, witness the batching
  2034. optimizations for synchronize_rcu(), call_rcu(),
  2035. synchronize_rcu_expedited(), and rcu_barrier(). As a general
  2036. rule, RCU must cheerfully accept whatever the rest of the Linux kernel
  2037. decides to throw at it.
  2038. The Linux kernel is used for real-time workloads, especially in
  2039. conjunction with the `-rt
  2040. patchset <https://wiki.linuxfoundation.org/realtime/>`__. The
  2041. real-time-latency response requirements are such that the traditional
  2042. approach of disabling preemption across RCU read-side critical sections
  2043. is inappropriate. Kernels built with ``CONFIG_PREEMPTION=y`` therefore use
  2044. an RCU implementation that allows RCU read-side critical sections to be
  2045. preempted. This requirement made its presence known after users made it
  2046. clear that an earlier `real-time
  2047. patch <https://lwn.net/Articles/107930/>`__ did not meet their needs, in
  2048. conjunction with some `RCU
  2049. issues <https://lore.kernel.org/r/[email protected]>`__
  2050. encountered by a very early version of the -rt patchset.
  2051. In addition, RCU must make do with a sub-100-microsecond real-time
  2052. latency budget. In fact, on smaller systems with the -rt patchset, the
  2053. Linux kernel provides sub-20-microsecond real-time latencies for the
  2054. whole kernel, including RCU. RCU's scalability and latency must
  2055. therefore be sufficient for these sorts of configurations. To my
  2056. surprise, the sub-100-microsecond real-time latency budget `applies to
  2057. even the largest systems
  2058. [PDF] <http://www.rdrop.com/users/paulmck/realtime/paper/bigrt.2013.01.31a.LCA.pdf>`__,
  2059. up to and including systems with 4096 CPUs. This real-time requirement
  2060. motivated the grace-period kthread, which also simplified handling of a
  2061. number of race conditions.
  2062. RCU must avoid degrading real-time response for CPU-bound threads,
  2063. whether executing in usermode (which is one use case for
  2064. ``CONFIG_NO_HZ_FULL=y``) or in the kernel. That said, CPU-bound loops in
  2065. the kernel must execute cond_resched() at least once per few tens of
  2066. milliseconds in order to avoid receiving an IPI from RCU.
  2067. Finally, RCU's status as a synchronization primitive means that any RCU
  2068. failure can result in arbitrary memory corruption that can be extremely
  2069. difficult to debug. This means that RCU must be extremely reliable,
  2070. which in practice also means that RCU must have an aggressive
  2071. stress-test suite. This stress-test suite is called ``rcutorture``.
  2072. Although the need for ``rcutorture`` was no surprise, the current
  2073. immense popularity of the Linux kernel is posing interesting—and perhaps
  2074. unprecedented—validation challenges. To see this, keep in mind that
  2075. there are well over one billion instances of the Linux kernel running
  2076. today, given Android smartphones, Linux-powered televisions, and
  2077. servers. This number can be expected to increase sharply with the advent
  2078. of the celebrated Internet of Things.
  2079. Suppose that RCU contains a race condition that manifests on average
  2080. once per million years of runtime. This bug will be occurring about
  2081. three times per *day* across the installed base. RCU could simply hide
  2082. behind hardware error rates, given that no one should really expect
  2083. their smartphone to last for a million years. However, anyone taking too
  2084. much comfort from this thought should consider the fact that in most
  2085. jurisdictions, a successful multi-year test of a given mechanism, which
  2086. might include a Linux kernel, suffices for a number of types of
  2087. safety-critical certifications. In fact, rumor has it that the Linux
  2088. kernel is already being used in production for safety-critical
  2089. applications. I don't know about you, but I would feel quite bad if a
  2090. bug in RCU killed someone. Which might explain my recent focus on
  2091. validation and verification.
  2092. Other RCU Flavors
  2093. -----------------
  2094. One of the more surprising things about RCU is that there are now no
  2095. fewer than five *flavors*, or API families. In addition, the primary
  2096. flavor that has been the sole focus up to this point has two different
  2097. implementations, non-preemptible and preemptible. The other four flavors
  2098. are listed below, with requirements for each described in a separate
  2099. section.
  2100. #. `Bottom-Half Flavor (Historical)`_
  2101. #. `Sched Flavor (Historical)`_
  2102. #. `Sleepable RCU`_
  2103. #. `Tasks RCU`_
  2104. Bottom-Half Flavor (Historical)
  2105. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2106. The RCU-bh flavor of RCU has since been expressed in terms of the other
  2107. RCU flavors as part of a consolidation of the three flavors into a
  2108. single flavor. The read-side API remains, and continues to disable
  2109. softirq and to be accounted for by lockdep. Much of the material in this
  2110. section is therefore strictly historical in nature.
  2111. The softirq-disable (AKA “bottom-half”, hence the “_bh” abbreviations)
  2112. flavor of RCU, or *RCU-bh*, was developed by Dipankar Sarma to provide a
  2113. flavor of RCU that could withstand the network-based denial-of-service
  2114. attacks researched by Robert Olsson. These attacks placed so much
  2115. networking load on the system that some of the CPUs never exited softirq
  2116. execution, which in turn prevented those CPUs from ever executing a
  2117. context switch, which, in the RCU implementation of that time, prevented
  2118. grace periods from ever ending. The result was an out-of-memory
  2119. condition and a system hang.
  2120. The solution was the creation of RCU-bh, which does
  2121. local_bh_disable() across its read-side critical sections, and which
  2122. uses the transition from one type of softirq processing to another as a
  2123. quiescent state in addition to context switch, idle, user mode, and
  2124. offline. This means that RCU-bh grace periods can complete even when
  2125. some of the CPUs execute in softirq indefinitely, thus allowing
  2126. algorithms based on RCU-bh to withstand network-based denial-of-service
  2127. attacks.
  2128. Because rcu_read_lock_bh() and rcu_read_unlock_bh() disable and
  2129. re-enable softirq handlers, any attempt to start a softirq handlers
  2130. during the RCU-bh read-side critical section will be deferred. In this
  2131. case, rcu_read_unlock_bh() will invoke softirq processing, which can
  2132. take considerable time. One can of course argue that this softirq
  2133. overhead should be associated with the code following the RCU-bh
  2134. read-side critical section rather than rcu_read_unlock_bh(), but the
  2135. fact is that most profiling tools cannot be expected to make this sort
  2136. of fine distinction. For example, suppose that a three-millisecond-long
  2137. RCU-bh read-side critical section executes during a time of heavy
  2138. networking load. There will very likely be an attempt to invoke at least
  2139. one softirq handler during that three milliseconds, but any such
  2140. invocation will be delayed until the time of the
  2141. rcu_read_unlock_bh(). This can of course make it appear at first
  2142. glance as if rcu_read_unlock_bh() was executing very slowly.
  2143. The `RCU-bh
  2144. API <https://lwn.net/Articles/609973/#RCU%20Per-Flavor%20API%20Table>`__
  2145. includes rcu_read_lock_bh(), rcu_read_unlock_bh(), rcu_dereference_bh(),
  2146. rcu_dereference_bh_check(), and rcu_read_lock_bh_held(). However, the
  2147. old RCU-bh update-side APIs are now gone, replaced by synchronize_rcu(),
  2148. synchronize_rcu_expedited(), call_rcu(), and rcu_barrier(). In addition,
  2149. anything that disables bottom halves also marks an RCU-bh read-side
  2150. critical section, including local_bh_disable() and local_bh_enable(),
  2151. local_irq_save() and local_irq_restore(), and so on.
  2152. Sched Flavor (Historical)
  2153. ~~~~~~~~~~~~~~~~~~~~~~~~~
  2154. The RCU-sched flavor of RCU has since been expressed in terms of the
  2155. other RCU flavors as part of a consolidation of the three flavors into a
  2156. single flavor. The read-side API remains, and continues to disable
  2157. preemption and to be accounted for by lockdep. Much of the material in
  2158. this section is therefore strictly historical in nature.
  2159. Before preemptible RCU, waiting for an RCU grace period had the side
  2160. effect of also waiting for all pre-existing interrupt and NMI handlers.
  2161. However, there are legitimate preemptible-RCU implementations that do
  2162. not have this property, given that any point in the code outside of an
  2163. RCU read-side critical section can be a quiescent state. Therefore,
  2164. *RCU-sched* was created, which follows “classic” RCU in that an
  2165. RCU-sched grace period waits for pre-existing interrupt and NMI
  2166. handlers. In kernels built with ``CONFIG_PREEMPTION=n``, the RCU and
  2167. RCU-sched APIs have identical implementations, while kernels built with
  2168. ``CONFIG_PREEMPTION=y`` provide a separate implementation for each.
  2169. Note well that in ``CONFIG_PREEMPTION=y`` kernels,
  2170. rcu_read_lock_sched() and rcu_read_unlock_sched() disable and
  2171. re-enable preemption, respectively. This means that if there was a
  2172. preemption attempt during the RCU-sched read-side critical section,
  2173. rcu_read_unlock_sched() will enter the scheduler, with all the
  2174. latency and overhead entailed. Just as with rcu_read_unlock_bh(),
  2175. this can make it look as if rcu_read_unlock_sched() was executing
  2176. very slowly. However, the highest-priority task won't be preempted, so
  2177. that task will enjoy low-overhead rcu_read_unlock_sched()
  2178. invocations.
  2179. The `RCU-sched
  2180. API <https://lwn.net/Articles/609973/#RCU%20Per-Flavor%20API%20Table>`__
  2181. includes rcu_read_lock_sched(), rcu_read_unlock_sched(),
  2182. rcu_read_lock_sched_notrace(), rcu_read_unlock_sched_notrace(),
  2183. rcu_dereference_sched(), rcu_dereference_sched_check(), and
  2184. rcu_read_lock_sched_held(). However, the old RCU-sched update-side APIs
  2185. are now gone, replaced by synchronize_rcu(), synchronize_rcu_expedited(),
  2186. call_rcu(), and rcu_barrier(). In addition, anything that disables
  2187. preemption also marks an RCU-sched read-side critical section,
  2188. including preempt_disable() and preempt_enable(), local_irq_save()
  2189. and local_irq_restore(), and so on.
  2190. Sleepable RCU
  2191. ~~~~~~~~~~~~~
  2192. For well over a decade, someone saying “I need to block within an RCU
  2193. read-side critical section” was a reliable indication that this someone
  2194. did not understand RCU. After all, if you are always blocking in an RCU
  2195. read-side critical section, you can probably afford to use a
  2196. higher-overhead synchronization mechanism. However, that changed with
  2197. the advent of the Linux kernel's notifiers, whose RCU read-side critical
  2198. sections almost never sleep, but sometimes need to. This resulted in the
  2199. introduction of `sleepable RCU <https://lwn.net/Articles/202847/>`__, or
  2200. *SRCU*.
  2201. SRCU allows different domains to be defined, with each such domain
  2202. defined by an instance of an ``srcu_struct`` structure. A pointer to
  2203. this structure must be passed in to each SRCU function, for example,
  2204. ``synchronize_srcu(&ss)``, where ``ss`` is the ``srcu_struct``
  2205. structure. The key benefit of these domains is that a slow SRCU reader
  2206. in one domain does not delay an SRCU grace period in some other domain.
  2207. That said, one consequence of these domains is that read-side code must
  2208. pass a “cookie” from srcu_read_lock() to srcu_read_unlock(), for
  2209. example, as follows:
  2210. ::
  2211. 1 int idx;
  2212. 2
  2213. 3 idx = srcu_read_lock(&ss);
  2214. 4 do_something();
  2215. 5 srcu_read_unlock(&ss, idx);
  2216. As noted above, it is legal to block within SRCU read-side critical
  2217. sections, however, with great power comes great responsibility. If you
  2218. block forever in one of a given domain's SRCU read-side critical
  2219. sections, then that domain's grace periods will also be blocked forever.
  2220. Of course, one good way to block forever is to deadlock, which can
  2221. happen if any operation in a given domain's SRCU read-side critical
  2222. section can wait, either directly or indirectly, for that domain's grace
  2223. period to elapse. For example, this results in a self-deadlock:
  2224. ::
  2225. 1 int idx;
  2226. 2
  2227. 3 idx = srcu_read_lock(&ss);
  2228. 4 do_something();
  2229. 5 synchronize_srcu(&ss);
  2230. 6 srcu_read_unlock(&ss, idx);
  2231. However, if line 5 acquired a mutex that was held across a
  2232. synchronize_srcu() for domain ``ss``, deadlock would still be
  2233. possible. Furthermore, if line 5 acquired a mutex that was held across a
  2234. synchronize_srcu() for some other domain ``ss1``, and if an
  2235. ``ss1``-domain SRCU read-side critical section acquired another mutex
  2236. that was held across as ``ss``-domain synchronize_srcu(), deadlock
  2237. would again be possible. Such a deadlock cycle could extend across an
  2238. arbitrarily large number of different SRCU domains. Again, with great
  2239. power comes great responsibility.
  2240. Unlike the other RCU flavors, SRCU read-side critical sections can run
  2241. on idle and even offline CPUs. This ability requires that
  2242. srcu_read_lock() and srcu_read_unlock() contain memory barriers,
  2243. which means that SRCU readers will run a bit slower than would RCU
  2244. readers. It also motivates the smp_mb__after_srcu_read_unlock() API,
  2245. which, in combination with srcu_read_unlock(), guarantees a full
  2246. memory barrier.
  2247. Also unlike other RCU flavors, synchronize_srcu() may **not** be
  2248. invoked from CPU-hotplug notifiers, due to the fact that SRCU grace
  2249. periods make use of timers and the possibility of timers being
  2250. temporarily “stranded” on the outgoing CPU. This stranding of timers
  2251. means that timers posted to the outgoing CPU will not fire until late in
  2252. the CPU-hotplug process. The problem is that if a notifier is waiting on
  2253. an SRCU grace period, that grace period is waiting on a timer, and that
  2254. timer is stranded on the outgoing CPU, then the notifier will never be
  2255. awakened, in other words, deadlock has occurred. This same situation of
  2256. course also prohibits srcu_barrier() from being invoked from
  2257. CPU-hotplug notifiers.
  2258. SRCU also differs from other RCU flavors in that SRCU's expedited and
  2259. non-expedited grace periods are implemented by the same mechanism. This
  2260. means that in the current SRCU implementation, expediting a future grace
  2261. period has the side effect of expediting all prior grace periods that
  2262. have not yet completed. (But please note that this is a property of the
  2263. current implementation, not necessarily of future implementations.) In
  2264. addition, if SRCU has been idle for longer than the interval specified
  2265. by the ``srcutree.exp_holdoff`` kernel boot parameter (25 microseconds
  2266. by default), and if a synchronize_srcu() invocation ends this idle
  2267. period, that invocation will be automatically expedited.
  2268. As of v4.12, SRCU's callbacks are maintained per-CPU, eliminating a
  2269. locking bottleneck present in prior kernel versions. Although this will
  2270. allow users to put much heavier stress on call_srcu(), it is
  2271. important to note that SRCU does not yet take any special steps to deal
  2272. with callback flooding. So if you are posting (say) 10,000 SRCU
  2273. callbacks per second per CPU, you are probably totally OK, but if you
  2274. intend to post (say) 1,000,000 SRCU callbacks per second per CPU, please
  2275. run some tests first. SRCU just might need a few adjustment to deal with
  2276. that sort of load. Of course, your mileage may vary based on the speed
  2277. of your CPUs and the size of your memory.
  2278. The `SRCU
  2279. API <https://lwn.net/Articles/609973/#RCU%20Per-Flavor%20API%20Table>`__
  2280. includes srcu_read_lock(), srcu_read_unlock(),
  2281. srcu_dereference(), srcu_dereference_check(),
  2282. synchronize_srcu(), synchronize_srcu_expedited(),
  2283. call_srcu(), srcu_barrier(), and srcu_read_lock_held(). It
  2284. also includes DEFINE_SRCU(), DEFINE_STATIC_SRCU(), and
  2285. init_srcu_struct() APIs for defining and initializing
  2286. ``srcu_struct`` structures.
  2287. More recently, the SRCU API has added polling interfaces:
  2288. #. start_poll_synchronize_srcu() returns a cookie identifying
  2289. the completion of a future SRCU grace period and ensures
  2290. that this grace period will be started.
  2291. #. poll_state_synchronize_srcu() returns ``true`` iff the
  2292. specified cookie corresponds to an already-completed
  2293. SRCU grace period.
  2294. #. get_state_synchronize_srcu() returns a cookie just like
  2295. start_poll_synchronize_srcu() does, but differs in that
  2296. it does nothing to ensure that any future SRCU grace period
  2297. will be started.
  2298. These functions are used to avoid unnecessary SRCU grace periods in
  2299. certain types of buffer-cache algorithms having multi-stage age-out
  2300. mechanisms. The idea is that by the time the block has aged completely
  2301. from the cache, an SRCU grace period will be very likely to have elapsed.
  2302. Tasks RCU
  2303. ~~~~~~~~~
  2304. Some forms of tracing use “trampolines” to handle the binary rewriting
  2305. required to install different types of probes. It would be good to be
  2306. able to free old trampolines, which sounds like a job for some form of
  2307. RCU. However, because it is necessary to be able to install a trace
  2308. anywhere in the code, it is not possible to use read-side markers such
  2309. as rcu_read_lock() and rcu_read_unlock(). In addition, it does
  2310. not work to have these markers in the trampoline itself, because there
  2311. would need to be instructions following rcu_read_unlock(). Although
  2312. synchronize_rcu() would guarantee that execution reached the
  2313. rcu_read_unlock(), it would not be able to guarantee that execution
  2314. had completely left the trampoline. Worse yet, in some situations
  2315. the trampoline's protection must extend a few instructions *prior* to
  2316. execution reaching the trampoline. For example, these few instructions
  2317. might calculate the address of the trampoline, so that entering the
  2318. trampoline would be pre-ordained a surprisingly long time before execution
  2319. actually reached the trampoline itself.
  2320. The solution, in the form of `Tasks
  2321. RCU <https://lwn.net/Articles/607117/>`__, is to have implicit read-side
  2322. critical sections that are delimited by voluntary context switches, that
  2323. is, calls to schedule(), cond_resched(), and
  2324. synchronize_rcu_tasks(). In addition, transitions to and from
  2325. userspace execution also delimit tasks-RCU read-side critical sections.
  2326. The tasks-RCU API is quite compact, consisting only of
  2327. call_rcu_tasks(), synchronize_rcu_tasks(), and
  2328. rcu_barrier_tasks(). In ``CONFIG_PREEMPTION=n`` kernels, trampolines
  2329. cannot be preempted, so these APIs map to call_rcu(),
  2330. synchronize_rcu(), and rcu_barrier(), respectively. In
  2331. ``CONFIG_PREEMPTION=y`` kernels, trampolines can be preempted, and these
  2332. three APIs are therefore implemented by separate functions that check
  2333. for voluntary context switches.
  2334. Tasks Rude RCU
  2335. ~~~~~~~~~~~~~~
  2336. Some forms of tracing need to wait for all preemption-disabled regions
  2337. of code running on any online CPU, including those executed when RCU is
  2338. not watching. This means that synchronize_rcu() is insufficient, and
  2339. Tasks Rude RCU must be used instead. This flavor of RCU does its work by
  2340. forcing a workqueue to be scheduled on each online CPU, hence the "Rude"
  2341. moniker. And this operation is considered to be quite rude by real-time
  2342. workloads that don't want their ``nohz_full`` CPUs receiving IPIs and
  2343. by battery-powered systems that don't want their idle CPUs to be awakened.
  2344. The tasks-rude-RCU API is also reader-marking-free and thus quite compact,
  2345. consisting of call_rcu_tasks_rude(), synchronize_rcu_tasks_rude(),
  2346. and rcu_barrier_tasks_rude().
  2347. Tasks Trace RCU
  2348. ~~~~~~~~~~~~~~~
  2349. Some forms of tracing need to sleep in readers, but cannot tolerate
  2350. SRCU's read-side overhead, which includes a full memory barrier in both
  2351. srcu_read_lock() and srcu_read_unlock(). This need is handled by a
  2352. Tasks Trace RCU that uses scheduler locking and IPIs to synchronize with
  2353. readers. Real-time systems that cannot tolerate IPIs may build their
  2354. kernels with ``CONFIG_TASKS_TRACE_RCU_READ_MB=y``, which avoids the IPIs at
  2355. the expense of adding full memory barriers to the read-side primitives.
  2356. The tasks-trace-RCU API is also reasonably compact,
  2357. consisting of rcu_read_lock_trace(), rcu_read_unlock_trace(),
  2358. rcu_read_lock_trace_held(), call_rcu_tasks_trace(),
  2359. synchronize_rcu_tasks_trace(), and rcu_barrier_tasks_trace().
  2360. Possible Future Changes
  2361. -----------------------
  2362. One of the tricks that RCU uses to attain update-side scalability is to
  2363. increase grace-period latency with increasing numbers of CPUs. If this
  2364. becomes a serious problem, it will be necessary to rework the
  2365. grace-period state machine so as to avoid the need for the additional
  2366. latency.
  2367. RCU disables CPU hotplug in a few places, perhaps most notably in the
  2368. rcu_barrier() operations. If there is a strong reason to use
  2369. rcu_barrier() in CPU-hotplug notifiers, it will be necessary to
  2370. avoid disabling CPU hotplug. This would introduce some complexity, so
  2371. there had better be a *very* good reason.
  2372. The tradeoff between grace-period latency on the one hand and
  2373. interruptions of other CPUs on the other hand may need to be
  2374. re-examined. The desire is of course for zero grace-period latency as
  2375. well as zero interprocessor interrupts undertaken during an expedited
  2376. grace period operation. While this ideal is unlikely to be achievable,
  2377. it is quite possible that further improvements can be made.
  2378. The multiprocessor implementations of RCU use a combining tree that
  2379. groups CPUs so as to reduce lock contention and increase cache locality.
  2380. However, this combining tree does not spread its memory across NUMA
  2381. nodes nor does it align the CPU groups with hardware features such as
  2382. sockets or cores. Such spreading and alignment is currently believed to
  2383. be unnecessary because the hotpath read-side primitives do not access
  2384. the combining tree, nor does call_rcu() in the common case. If you
  2385. believe that your architecture needs such spreading and alignment, then
  2386. your architecture should also benefit from the
  2387. ``rcutree.rcu_fanout_leaf`` boot parameter, which can be set to the
  2388. number of CPUs in a socket, NUMA node, or whatever. If the number of
  2389. CPUs is too large, use a fraction of the number of CPUs. If the number
  2390. of CPUs is a large prime number, well, that certainly is an
  2391. “interesting” architectural choice! More flexible arrangements might be
  2392. considered, but only if ``rcutree.rcu_fanout_leaf`` has proven
  2393. inadequate, and only if the inadequacy has been demonstrated by a
  2394. carefully run and realistic system-level workload.
  2395. Please note that arrangements that require RCU to remap CPU numbers will
  2396. require extremely good demonstration of need and full exploration of
  2397. alternatives.
  2398. RCU's various kthreads are reasonably recent additions. It is quite
  2399. likely that adjustments will be required to more gracefully handle
  2400. extreme loads. It might also be necessary to be able to relate CPU
  2401. utilization by RCU's kthreads and softirq handlers to the code that
  2402. instigated this CPU utilization. For example, RCU callback overhead
  2403. might be charged back to the originating call_rcu() instance, though
  2404. probably not in production kernels.
  2405. Additional work may be required to provide reasonable forward-progress
  2406. guarantees under heavy load for grace periods and for callback
  2407. invocation.
  2408. Summary
  2409. -------
  2410. This document has presented more than two decade's worth of RCU
  2411. requirements. Given that the requirements keep changing, this will not
  2412. be the last word on this subject, but at least it serves to get an
  2413. important subset of the requirements set forth.
  2414. Acknowledgments
  2415. ---------------
  2416. I am grateful to Steven Rostedt, Lai Jiangshan, Ingo Molnar, Oleg
  2417. Nesterov, Borislav Petkov, Peter Zijlstra, Boqun Feng, and Andy
  2418. Lutomirski for their help in rendering this article human readable, and
  2419. to Michelle Rankin for her support of this effort. Other contributions
  2420. are acknowledged in the Linux kernel's git archive.