whatisRCU.txt 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. What is RCU?
  2. RCU is a synchronization mechanism that was added to the Linux kernel
  3. during the 2.5 development effort that is optimized for read-mostly
  4. situations. Although RCU is actually quite simple once you understand it,
  5. getting there can sometimes be a challenge. Part of the problem is that
  6. most of the past descriptions of RCU have been written with the mistaken
  7. assumption that there is "one true way" to describe RCU. Instead,
  8. the experience has been that different people must take different paths
  9. to arrive at an understanding of RCU. This document provides several
  10. different paths, as follows:
  11. 1. RCU OVERVIEW
  12. 2. WHAT IS RCU'S CORE API?
  13. 3. WHAT ARE SOME EXAMPLE USES OF CORE RCU API?
  14. 4. WHAT IF MY UPDATING THREAD CANNOT BLOCK?
  15. 5. WHAT ARE SOME SIMPLE IMPLEMENTATIONS OF RCU?
  16. 6. ANALOGY WITH READER-WRITER LOCKING
  17. 7. FULL LIST OF RCU APIs
  18. 8. ANSWERS TO QUICK QUIZZES
  19. People who prefer starting with a conceptual overview should focus on
  20. Section 1, though most readers will profit by reading this section at
  21. some point. People who prefer to start with an API that they can then
  22. experiment with should focus on Section 2. People who prefer to start
  23. with example uses should focus on Sections 3 and 4. People who need to
  24. understand the RCU implementation should focus on Section 5, then dive
  25. into the kernel source code. People who reason best by analogy should
  26. focus on Section 6. Section 7 serves as an index to the docbook API
  27. documentation, and Section 8 is the traditional answer key.
  28. So, start with the section that makes the most sense to you and your
  29. preferred method of learning. If you need to know everything about
  30. everything, feel free to read the whole thing -- but if you are really
  31. that type of person, you have perused the source code and will therefore
  32. never need this document anyway. ;-)
  33. 1. RCU OVERVIEW
  34. The basic idea behind RCU is to split updates into "removal" and
  35. "reclamation" phases. The removal phase removes references to data items
  36. within a data structure (possibly by replacing them with references to
  37. new versions of these data items), and can run concurrently with readers.
  38. The reason that it is safe to run the removal phase concurrently with
  39. readers is the semantics of modern CPUs guarantee that readers will see
  40. either the old or the new version of the data structure rather than a
  41. partially updated reference. The reclamation phase does the work of reclaiming
  42. (e.g., freeing) the data items removed from the data structure during the
  43. removal phase. Because reclaiming data items can disrupt any readers
  44. concurrently referencing those data items, the reclamation phase must
  45. not start until readers no longer hold references to those data items.
  46. Splitting the update into removal and reclamation phases permits the
  47. updater to perform the removal phase immediately, and to defer the
  48. reclamation phase until all readers active during the removal phase have
  49. completed, either by blocking until they finish or by registering a
  50. callback that is invoked after they finish. Only readers that are active
  51. during the removal phase need be considered, because any reader starting
  52. after the removal phase will be unable to gain a reference to the removed
  53. data items, and therefore cannot be disrupted by the reclamation phase.
  54. So the typical RCU update sequence goes something like the following:
  55. a. Remove pointers to a data structure, so that subsequent
  56. readers cannot gain a reference to it.
  57. b. Wait for all previous readers to complete their RCU read-side
  58. critical sections.
  59. c. At this point, there cannot be any readers who hold references
  60. to the data structure, so it now may safely be reclaimed
  61. (e.g., kfree()d).
  62. Step (b) above is the key idea underlying RCU's deferred destruction.
  63. The ability to wait until all readers are done allows RCU readers to
  64. use much lighter-weight synchronization, in some cases, absolutely no
  65. synchronization at all. In contrast, in more conventional lock-based
  66. schemes, readers must use heavy-weight synchronization in order to
  67. prevent an updater from deleting the data structure out from under them.
  68. This is because lock-based updaters typically update data items in place,
  69. and must therefore exclude readers. In contrast, RCU-based updaters
  70. typically take advantage of the fact that writes to single aligned
  71. pointers are atomic on modern CPUs, allowing atomic insertion, removal,
  72. and replacement of data items in a linked structure without disrupting
  73. readers. Concurrent RCU readers can then continue accessing the old
  74. versions, and can dispense with the atomic operations, memory barriers,
  75. and communications cache misses that are so expensive on present-day
  76. SMP computer systems, even in absence of lock contention.
  77. In the three-step procedure shown above, the updater is performing both
  78. the removal and the reclamation step, but it is often helpful for an
  79. entirely different thread to do the reclamation, as is in fact the case
  80. in the Linux kernel's directory-entry cache (dcache). Even if the same
  81. thread performs both the update step (step (a) above) and the reclamation
  82. step (step (c) above), it is often helpful to think of them separately.
  83. For example, RCU readers and updaters need not communicate at all,
  84. but RCU provides implicit low-overhead communication between readers
  85. and reclaimers, namely, in step (b) above.
  86. So how the heck can a reclaimer tell when a reader is done, given
  87. that readers are not doing any sort of synchronization operations???
  88. Read on to learn about how RCU's API makes this easy.
  89. 2. WHAT IS RCU'S CORE API?
  90. The core RCU API is quite small:
  91. a. rcu_read_lock()
  92. b. rcu_read_unlock()
  93. c. synchronize_rcu() / call_rcu()
  94. d. rcu_assign_pointer()
  95. e. rcu_dereference()
  96. There are many other members of the RCU API, but the rest can be
  97. expressed in terms of these five, though most implementations instead
  98. express synchronize_rcu() in terms of the call_rcu() callback API.
  99. The five core RCU APIs are described below, the other 18 will be enumerated
  100. later. See the kernel docbook documentation for more info, or look directly
  101. at the function header comments.
  102. rcu_read_lock()
  103. void rcu_read_lock(void);
  104. Used by a reader to inform the reclaimer that the reader is
  105. entering an RCU read-side critical section. It is illegal
  106. to block while in an RCU read-side critical section, though
  107. kernels built with CONFIG_PREEMPT_RCU can preempt RCU read-side
  108. critical sections. Any RCU-protected data structure accessed
  109. during an RCU read-side critical section is guaranteed to remain
  110. unreclaimed for the full duration of that critical section.
  111. Reference counts may be used in conjunction with RCU to maintain
  112. longer-term references to data structures.
  113. rcu_read_unlock()
  114. void rcu_read_unlock(void);
  115. Used by a reader to inform the reclaimer that the reader is
  116. exiting an RCU read-side critical section. Note that RCU
  117. read-side critical sections may be nested and/or overlapping.
  118. synchronize_rcu()
  119. void synchronize_rcu(void);
  120. Marks the end of updater code and the beginning of reclaimer
  121. code. It does this by blocking until all pre-existing RCU
  122. read-side critical sections on all CPUs have completed.
  123. Note that synchronize_rcu() will -not- necessarily wait for
  124. any subsequent RCU read-side critical sections to complete.
  125. For example, consider the following sequence of events:
  126. CPU 0 CPU 1 CPU 2
  127. ----------------- ------------------------- ---------------
  128. 1. rcu_read_lock()
  129. 2. enters synchronize_rcu()
  130. 3. rcu_read_lock()
  131. 4. rcu_read_unlock()
  132. 5. exits synchronize_rcu()
  133. 6. rcu_read_unlock()
  134. To reiterate, synchronize_rcu() waits only for ongoing RCU
  135. read-side critical sections to complete, not necessarily for
  136. any that begin after synchronize_rcu() is invoked.
  137. Of course, synchronize_rcu() does not necessarily return
  138. -immediately- after the last pre-existing RCU read-side critical
  139. section completes. For one thing, there might well be scheduling
  140. delays. For another thing, many RCU implementations process
  141. requests in batches in order to improve efficiencies, which can
  142. further delay synchronize_rcu().
  143. Since synchronize_rcu() is the API that must figure out when
  144. readers are done, its implementation is key to RCU. For RCU
  145. to be useful in all but the most read-intensive situations,
  146. synchronize_rcu()'s overhead must also be quite small.
  147. The call_rcu() API is a callback form of synchronize_rcu(),
  148. and is described in more detail in a later section. Instead of
  149. blocking, it registers a function and argument which are invoked
  150. after all ongoing RCU read-side critical sections have completed.
  151. This callback variant is particularly useful in situations where
  152. it is illegal to block or where update-side performance is
  153. critically important.
  154. However, the call_rcu() API should not be used lightly, as use
  155. of the synchronize_rcu() API generally results in simpler code.
  156. In addition, the synchronize_rcu() API has the nice property
  157. of automatically limiting update rate should grace periods
  158. be delayed. This property results in system resilience in face
  159. of denial-of-service attacks. Code using call_rcu() should limit
  160. update rate in order to gain this same sort of resilience. See
  161. checklist.txt for some approaches to limiting the update rate.
  162. rcu_assign_pointer()
  163. typeof(p) rcu_assign_pointer(p, typeof(p) v);
  164. Yes, rcu_assign_pointer() -is- implemented as a macro, though it
  165. would be cool to be able to declare a function in this manner.
  166. (Compiler experts will no doubt disagree.)
  167. The updater uses this function to assign a new value to an
  168. RCU-protected pointer, in order to safely communicate the change
  169. in value from the updater to the reader. This function returns
  170. the new value, and also executes any memory-barrier instructions
  171. required for a given CPU architecture.
  172. Perhaps just as important, it serves to document (1) which
  173. pointers are protected by RCU and (2) the point at which a
  174. given structure becomes accessible to other CPUs. That said,
  175. rcu_assign_pointer() is most frequently used indirectly, via
  176. the _rcu list-manipulation primitives such as list_add_rcu().
  177. rcu_dereference()
  178. typeof(p) rcu_dereference(p);
  179. Like rcu_assign_pointer(), rcu_dereference() must be implemented
  180. as a macro.
  181. The reader uses rcu_dereference() to fetch an RCU-protected
  182. pointer, which returns a value that may then be safely
  183. dereferenced. Note that rcu_deference() does not actually
  184. dereference the pointer, instead, it protects the pointer for
  185. later dereferencing. It also executes any needed memory-barrier
  186. instructions for a given CPU architecture. Currently, only Alpha
  187. needs memory barriers within rcu_dereference() -- on other CPUs,
  188. it compiles to nothing, not even a compiler directive.
  189. Common coding practice uses rcu_dereference() to copy an
  190. RCU-protected pointer to a local variable, then dereferences
  191. this local variable, for example as follows:
  192. p = rcu_dereference(head.next);
  193. return p->data;
  194. However, in this case, one could just as easily combine these
  195. into one statement:
  196. return rcu_dereference(head.next)->data;
  197. If you are going to be fetching multiple fields from the
  198. RCU-protected structure, using the local variable is of
  199. course preferred. Repeated rcu_dereference() calls look
  200. ugly and incur unnecessary overhead on Alpha CPUs.
  201. Note that the value returned by rcu_dereference() is valid
  202. only within the enclosing RCU read-side critical section.
  203. For example, the following is -not- legal:
  204. rcu_read_lock();
  205. p = rcu_dereference(head.next);
  206. rcu_read_unlock();
  207. x = p->address;
  208. rcu_read_lock();
  209. y = p->data;
  210. rcu_read_unlock();
  211. Holding a reference from one RCU read-side critical section
  212. to another is just as illegal as holding a reference from
  213. one lock-based critical section to another! Similarly,
  214. using a reference outside of the critical section in which
  215. it was acquired is just as illegal as doing so with normal
  216. locking.
  217. As with rcu_assign_pointer(), an important function of
  218. rcu_dereference() is to document which pointers are protected by
  219. RCU, in particular, flagging a pointer that is subject to changing
  220. at any time, including immediately after the rcu_dereference().
  221. And, again like rcu_assign_pointer(), rcu_dereference() is
  222. typically used indirectly, via the _rcu list-manipulation
  223. primitives, such as list_for_each_entry_rcu().
  224. The following diagram shows how each API communicates among the
  225. reader, updater, and reclaimer.
  226. rcu_assign_pointer()
  227. +--------+
  228. +---------------------->| reader |---------+
  229. | +--------+ |
  230. | | |
  231. | | | Protect:
  232. | | | rcu_read_lock()
  233. | | | rcu_read_unlock()
  234. | rcu_dereference() | |
  235. +---------+ | |
  236. | updater |<---------------------+ |
  237. +---------+ V
  238. | +-----------+
  239. +----------------------------------->| reclaimer |
  240. +-----------+
  241. Defer:
  242. synchronize_rcu() & call_rcu()
  243. The RCU infrastructure observes the time sequence of rcu_read_lock(),
  244. rcu_read_unlock(), synchronize_rcu(), and call_rcu() invocations in
  245. order to determine when (1) synchronize_rcu() invocations may return
  246. to their callers and (2) call_rcu() callbacks may be invoked. Efficient
  247. implementations of the RCU infrastructure make heavy use of batching in
  248. order to amortize their overhead over many uses of the corresponding APIs.
  249. There are no fewer than three RCU mechanisms in the Linux kernel; the
  250. diagram above shows the first one, which is by far the most commonly used.
  251. The rcu_dereference() and rcu_assign_pointer() primitives are used for
  252. all three mechanisms, but different defer and protect primitives are
  253. used as follows:
  254. Defer Protect
  255. a. synchronize_rcu() rcu_read_lock() / rcu_read_unlock()
  256. call_rcu()
  257. b. call_rcu_bh() rcu_read_lock_bh() / rcu_read_unlock_bh()
  258. c. synchronize_sched() preempt_disable() / preempt_enable()
  259. local_irq_save() / local_irq_restore()
  260. hardirq enter / hardirq exit
  261. NMI enter / NMI exit
  262. These three mechanisms are used as follows:
  263. a. RCU applied to normal data structures.
  264. b. RCU applied to networking data structures that may be subjected
  265. to remote denial-of-service attacks.
  266. c. RCU applied to scheduler and interrupt/NMI-handler tasks.
  267. Again, most uses will be of (a). The (b) and (c) cases are important
  268. for specialized uses, but are relatively uncommon.
  269. 3. WHAT ARE SOME EXAMPLE USES OF CORE RCU API?
  270. This section shows a simple use of the core RCU API to protect a
  271. global pointer to a dynamically allocated structure. More-typical
  272. uses of RCU may be found in listRCU.txt, arrayRCU.txt, and NMI-RCU.txt.
  273. struct foo {
  274. int a;
  275. char b;
  276. long c;
  277. };
  278. DEFINE_SPINLOCK(foo_mutex);
  279. struct foo *gbl_foo;
  280. /*
  281. * Create a new struct foo that is the same as the one currently
  282. * pointed to by gbl_foo, except that field "a" is replaced
  283. * with "new_a". Points gbl_foo to the new structure, and
  284. * frees up the old structure after a grace period.
  285. *
  286. * Uses rcu_assign_pointer() to ensure that concurrent readers
  287. * see the initialized version of the new structure.
  288. *
  289. * Uses synchronize_rcu() to ensure that any readers that might
  290. * have references to the old structure complete before freeing
  291. * the old structure.
  292. */
  293. void foo_update_a(int new_a)
  294. {
  295. struct foo *new_fp;
  296. struct foo *old_fp;
  297. new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL);
  298. spin_lock(&foo_mutex);
  299. old_fp = gbl_foo;
  300. *new_fp = *old_fp;
  301. new_fp->a = new_a;
  302. rcu_assign_pointer(gbl_foo, new_fp);
  303. spin_unlock(&foo_mutex);
  304. synchronize_rcu();
  305. kfree(old_fp);
  306. }
  307. /*
  308. * Return the value of field "a" of the current gbl_foo
  309. * structure. Use rcu_read_lock() and rcu_read_unlock()
  310. * to ensure that the structure does not get deleted out
  311. * from under us, and use rcu_dereference() to ensure that
  312. * we see the initialized version of the structure (important
  313. * for DEC Alpha and for people reading the code).
  314. */
  315. int foo_get_a(void)
  316. {
  317. int retval;
  318. rcu_read_lock();
  319. retval = rcu_dereference(gbl_foo)->a;
  320. rcu_read_unlock();
  321. return retval;
  322. }
  323. So, to sum up:
  324. o Use rcu_read_lock() and rcu_read_unlock() to guard RCU
  325. read-side critical sections.
  326. o Within an RCU read-side critical section, use rcu_dereference()
  327. to dereference RCU-protected pointers.
  328. o Use some solid scheme (such as locks or semaphores) to
  329. keep concurrent updates from interfering with each other.
  330. o Use rcu_assign_pointer() to update an RCU-protected pointer.
  331. This primitive protects concurrent readers from the updater,
  332. -not- concurrent updates from each other! You therefore still
  333. need to use locking (or something similar) to keep concurrent
  334. rcu_assign_pointer() primitives from interfering with each other.
  335. o Use synchronize_rcu() -after- removing a data element from an
  336. RCU-protected data structure, but -before- reclaiming/freeing
  337. the data element, in order to wait for the completion of all
  338. RCU read-side critical sections that might be referencing that
  339. data item.
  340. See checklist.txt for additional rules to follow when using RCU.
  341. And again, more-typical uses of RCU may be found in listRCU.txt,
  342. arrayRCU.txt, and NMI-RCU.txt.
  343. 4. WHAT IF MY UPDATING THREAD CANNOT BLOCK?
  344. In the example above, foo_update_a() blocks until a grace period elapses.
  345. This is quite simple, but in some cases one cannot afford to wait so
  346. long -- there might be other high-priority work to be done.
  347. In such cases, one uses call_rcu() rather than synchronize_rcu().
  348. The call_rcu() API is as follows:
  349. void call_rcu(struct rcu_head * head,
  350. void (*func)(struct rcu_head *head));
  351. This function invokes func(head) after a grace period has elapsed.
  352. This invocation might happen from either softirq or process context,
  353. so the function is not permitted to block. The foo struct needs to
  354. have an rcu_head structure added, perhaps as follows:
  355. struct foo {
  356. int a;
  357. char b;
  358. long c;
  359. struct rcu_head rcu;
  360. };
  361. The foo_update_a() function might then be written as follows:
  362. /*
  363. * Create a new struct foo that is the same as the one currently
  364. * pointed to by gbl_foo, except that field "a" is replaced
  365. * with "new_a". Points gbl_foo to the new structure, and
  366. * frees up the old structure after a grace period.
  367. *
  368. * Uses rcu_assign_pointer() to ensure that concurrent readers
  369. * see the initialized version of the new structure.
  370. *
  371. * Uses call_rcu() to ensure that any readers that might have
  372. * references to the old structure complete before freeing the
  373. * old structure.
  374. */
  375. void foo_update_a(int new_a)
  376. {
  377. struct foo *new_fp;
  378. struct foo *old_fp;
  379. new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL);
  380. spin_lock(&foo_mutex);
  381. old_fp = gbl_foo;
  382. *new_fp = *old_fp;
  383. new_fp->a = new_a;
  384. rcu_assign_pointer(gbl_foo, new_fp);
  385. spin_unlock(&foo_mutex);
  386. call_rcu(&old_fp->rcu, foo_reclaim);
  387. }
  388. The foo_reclaim() function might appear as follows:
  389. void foo_reclaim(struct rcu_head *rp)
  390. {
  391. struct foo *fp = container_of(rp, struct foo, rcu);
  392. kfree(fp);
  393. }
  394. The container_of() primitive is a macro that, given a pointer into a
  395. struct, the type of the struct, and the pointed-to field within the
  396. struct, returns a pointer to the beginning of the struct.
  397. The use of call_rcu() permits the caller of foo_update_a() to
  398. immediately regain control, without needing to worry further about the
  399. old version of the newly updated element. It also clearly shows the
  400. RCU distinction between updater, namely foo_update_a(), and reclaimer,
  401. namely foo_reclaim().
  402. The summary of advice is the same as for the previous section, except
  403. that we are now using call_rcu() rather than synchronize_rcu():
  404. o Use call_rcu() -after- removing a data element from an
  405. RCU-protected data structure in order to register a callback
  406. function that will be invoked after the completion of all RCU
  407. read-side critical sections that might be referencing that
  408. data item.
  409. Again, see checklist.txt for additional rules governing the use of RCU.
  410. 5. WHAT ARE SOME SIMPLE IMPLEMENTATIONS OF RCU?
  411. One of the nice things about RCU is that it has extremely simple "toy"
  412. implementations that are a good first step towards understanding the
  413. production-quality implementations in the Linux kernel. This section
  414. presents two such "toy" implementations of RCU, one that is implemented
  415. in terms of familiar locking primitives, and another that more closely
  416. resembles "classic" RCU. Both are way too simple for real-world use,
  417. lacking both functionality and performance. However, they are useful
  418. in getting a feel for how RCU works. See kernel/rcupdate.c for a
  419. production-quality implementation, and see:
  420. http://www.rdrop.com/users/paulmck/RCU
  421. for papers describing the Linux kernel RCU implementation. The OLS'01
  422. and OLS'02 papers are a good introduction, and the dissertation provides
  423. more details on the current implementation as of early 2004.
  424. 5A. "TOY" IMPLEMENTATION #1: LOCKING
  425. This section presents a "toy" RCU implementation that is based on
  426. familiar locking primitives. Its overhead makes it a non-starter for
  427. real-life use, as does its lack of scalability. It is also unsuitable
  428. for realtime use, since it allows scheduling latency to "bleed" from
  429. one read-side critical section to another.
  430. However, it is probably the easiest implementation to relate to, so is
  431. a good starting point.
  432. It is extremely simple:
  433. static DEFINE_RWLOCK(rcu_gp_mutex);
  434. void rcu_read_lock(void)
  435. {
  436. read_lock(&rcu_gp_mutex);
  437. }
  438. void rcu_read_unlock(void)
  439. {
  440. read_unlock(&rcu_gp_mutex);
  441. }
  442. void synchronize_rcu(void)
  443. {
  444. write_lock(&rcu_gp_mutex);
  445. write_unlock(&rcu_gp_mutex);
  446. }
  447. [You can ignore rcu_assign_pointer() and rcu_dereference() without
  448. missing much. But here they are anyway. And whatever you do, don't
  449. forget about them when submitting patches making use of RCU!]
  450. #define rcu_assign_pointer(p, v) ({ \
  451. smp_wmb(); \
  452. (p) = (v); \
  453. })
  454. #define rcu_dereference(p) ({ \
  455. typeof(p) _________p1 = p; \
  456. smp_read_barrier_depends(); \
  457. (_________p1); \
  458. })
  459. The rcu_read_lock() and rcu_read_unlock() primitive read-acquire
  460. and release a global reader-writer lock. The synchronize_rcu()
  461. primitive write-acquires this same lock, then immediately releases
  462. it. This means that once synchronize_rcu() exits, all RCU read-side
  463. critical sections that were in progress before synchronize_rcu() was
  464. called are guaranteed to have completed -- there is no way that
  465. synchronize_rcu() would have been able to write-acquire the lock
  466. otherwise.
  467. It is possible to nest rcu_read_lock(), since reader-writer locks may
  468. be recursively acquired. Note also that rcu_read_lock() is immune
  469. from deadlock (an important property of RCU). The reason for this is
  470. that the only thing that can block rcu_read_lock() is a synchronize_rcu().
  471. But synchronize_rcu() does not acquire any locks while holding rcu_gp_mutex,
  472. so there can be no deadlock cycle.
  473. Quick Quiz #1: Why is this argument naive? How could a deadlock
  474. occur when using this algorithm in a real-world Linux
  475. kernel? How could this deadlock be avoided?
  476. 5B. "TOY" EXAMPLE #2: CLASSIC RCU
  477. This section presents a "toy" RCU implementation that is based on
  478. "classic RCU". It is also short on performance (but only for updates) and
  479. on features such as hotplug CPU and the ability to run in CONFIG_PREEMPT
  480. kernels. The definitions of rcu_dereference() and rcu_assign_pointer()
  481. are the same as those shown in the preceding section, so they are omitted.
  482. void rcu_read_lock(void) { }
  483. void rcu_read_unlock(void) { }
  484. void synchronize_rcu(void)
  485. {
  486. int cpu;
  487. for_each_possible_cpu(cpu)
  488. run_on(cpu);
  489. }
  490. Note that rcu_read_lock() and rcu_read_unlock() do absolutely nothing.
  491. This is the great strength of classic RCU in a non-preemptive kernel:
  492. read-side overhead is precisely zero, at least on non-Alpha CPUs.
  493. And there is absolutely no way that rcu_read_lock() can possibly
  494. participate in a deadlock cycle!
  495. The implementation of synchronize_rcu() simply schedules itself on each
  496. CPU in turn. The run_on() primitive can be implemented straightforwardly
  497. in terms of the sched_setaffinity() primitive. Of course, a somewhat less
  498. "toy" implementation would restore the affinity upon completion rather
  499. than just leaving all tasks running on the last CPU, but when I said
  500. "toy", I meant -toy-!
  501. So how the heck is this supposed to work???
  502. Remember that it is illegal to block while in an RCU read-side critical
  503. section. Therefore, if a given CPU executes a context switch, we know
  504. that it must have completed all preceding RCU read-side critical sections.
  505. Once -all- CPUs have executed a context switch, then -all- preceding
  506. RCU read-side critical sections will have completed.
  507. So, suppose that we remove a data item from its structure and then invoke
  508. synchronize_rcu(). Once synchronize_rcu() returns, we are guaranteed
  509. that there are no RCU read-side critical sections holding a reference
  510. to that data item, so we can safely reclaim it.
  511. Quick Quiz #2: Give an example where Classic RCU's read-side
  512. overhead is -negative-.
  513. Quick Quiz #3: If it is illegal to block in an RCU read-side
  514. critical section, what the heck do you do in
  515. PREEMPT_RT, where normal spinlocks can block???
  516. 6. ANALOGY WITH READER-WRITER LOCKING
  517. Although RCU can be used in many different ways, a very common use of
  518. RCU is analogous to reader-writer locking. The following unified
  519. diff shows how closely related RCU and reader-writer locking can be.
  520. @@ -13,15 +14,15 @@
  521. struct list_head *lp;
  522. struct el *p;
  523. - read_lock();
  524. - list_for_each_entry(p, head, lp) {
  525. + rcu_read_lock();
  526. + list_for_each_entry_rcu(p, head, lp) {
  527. if (p->key == key) {
  528. *result = p->data;
  529. - read_unlock();
  530. + rcu_read_unlock();
  531. return 1;
  532. }
  533. }
  534. - read_unlock();
  535. + rcu_read_unlock();
  536. return 0;
  537. }
  538. @@ -29,15 +30,16 @@
  539. {
  540. struct el *p;
  541. - write_lock(&listmutex);
  542. + spin_lock(&listmutex);
  543. list_for_each_entry(p, head, lp) {
  544. if (p->key == key) {
  545. - list_del(&p->list);
  546. - write_unlock(&listmutex);
  547. + list_del_rcu(&p->list);
  548. + spin_unlock(&listmutex);
  549. + synchronize_rcu();
  550. kfree(p);
  551. return 1;
  552. }
  553. }
  554. - write_unlock(&listmutex);
  555. + spin_unlock(&listmutex);
  556. return 0;
  557. }
  558. Or, for those who prefer a side-by-side listing:
  559. 1 struct el { 1 struct el {
  560. 2 struct list_head list; 2 struct list_head list;
  561. 3 long key; 3 long key;
  562. 4 spinlock_t mutex; 4 spinlock_t mutex;
  563. 5 int data; 5 int data;
  564. 6 /* Other data fields */ 6 /* Other data fields */
  565. 7 }; 7 };
  566. 8 spinlock_t listmutex; 8 spinlock_t listmutex;
  567. 9 struct el head; 9 struct el head;
  568. 1 int search(long key, int *result) 1 int search(long key, int *result)
  569. 2 { 2 {
  570. 3 struct list_head *lp; 3 struct list_head *lp;
  571. 4 struct el *p; 4 struct el *p;
  572. 5 5
  573. 6 read_lock(); 6 rcu_read_lock();
  574. 7 list_for_each_entry(p, head, lp) { 7 list_for_each_entry_rcu(p, head, lp) {
  575. 8 if (p->key == key) { 8 if (p->key == key) {
  576. 9 *result = p->data; 9 *result = p->data;
  577. 10 read_unlock(); 10 rcu_read_unlock();
  578. 11 return 1; 11 return 1;
  579. 12 } 12 }
  580. 13 } 13 }
  581. 14 read_unlock(); 14 rcu_read_unlock();
  582. 15 return 0; 15 return 0;
  583. 16 } 16 }
  584. 1 int delete(long key) 1 int delete(long key)
  585. 2 { 2 {
  586. 3 struct el *p; 3 struct el *p;
  587. 4 4
  588. 5 write_lock(&listmutex); 5 spin_lock(&listmutex);
  589. 6 list_for_each_entry(p, head, lp) { 6 list_for_each_entry(p, head, lp) {
  590. 7 if (p->key == key) { 7 if (p->key == key) {
  591. 8 list_del(&p->list); 8 list_del_rcu(&p->list);
  592. 9 write_unlock(&listmutex); 9 spin_unlock(&listmutex);
  593. 10 synchronize_rcu();
  594. 10 kfree(p); 11 kfree(p);
  595. 11 return 1; 12 return 1;
  596. 12 } 13 }
  597. 13 } 14 }
  598. 14 write_unlock(&listmutex); 15 spin_unlock(&listmutex);
  599. 15 return 0; 16 return 0;
  600. 16 } 17 }
  601. Either way, the differences are quite small. Read-side locking moves
  602. to rcu_read_lock() and rcu_read_unlock, update-side locking moves from
  603. a reader-writer lock to a simple spinlock, and a synchronize_rcu()
  604. precedes the kfree().
  605. However, there is one potential catch: the read-side and update-side
  606. critical sections can now run concurrently. In many cases, this will
  607. not be a problem, but it is necessary to check carefully regardless.
  608. For example, if multiple independent list updates must be seen as
  609. a single atomic update, converting to RCU will require special care.
  610. Also, the presence of synchronize_rcu() means that the RCU version of
  611. delete() can now block. If this is a problem, there is a callback-based
  612. mechanism that never blocks, namely call_rcu(), that can be used in
  613. place of synchronize_rcu().
  614. 7. FULL LIST OF RCU APIs
  615. The RCU APIs are documented in docbook-format header comments in the
  616. Linux-kernel source code, but it helps to have a full list of the
  617. APIs, since there does not appear to be a way to categorize them
  618. in docbook. Here is the list, by category.
  619. Markers for RCU read-side critical sections:
  620. rcu_read_lock
  621. rcu_read_unlock
  622. rcu_read_lock_bh
  623. rcu_read_unlock_bh
  624. srcu_read_lock
  625. srcu_read_unlock
  626. RCU pointer/list traversal:
  627. rcu_dereference
  628. list_for_each_rcu (to be deprecated in favor of
  629. list_for_each_entry_rcu)
  630. list_for_each_entry_rcu
  631. list_for_each_continue_rcu (to be deprecated in favor of new
  632. list_for_each_entry_continue_rcu)
  633. hlist_for_each_entry_rcu
  634. RCU pointer update:
  635. rcu_assign_pointer
  636. list_add_rcu
  637. list_add_tail_rcu
  638. list_del_rcu
  639. list_replace_rcu
  640. hlist_del_rcu
  641. hlist_add_head_rcu
  642. RCU grace period:
  643. synchronize_net
  644. synchronize_sched
  645. synchronize_rcu
  646. synchronize_srcu
  647. call_rcu
  648. call_rcu_bh
  649. See the comment headers in the source code (or the docbook generated
  650. from them) for more information.
  651. 8. ANSWERS TO QUICK QUIZZES
  652. Quick Quiz #1: Why is this argument naive? How could a deadlock
  653. occur when using this algorithm in a real-world Linux
  654. kernel? [Referring to the lock-based "toy" RCU
  655. algorithm.]
  656. Answer: Consider the following sequence of events:
  657. 1. CPU 0 acquires some unrelated lock, call it
  658. "problematic_lock", disabling irq via
  659. spin_lock_irqsave().
  660. 2. CPU 1 enters synchronize_rcu(), write-acquiring
  661. rcu_gp_mutex.
  662. 3. CPU 0 enters rcu_read_lock(), but must wait
  663. because CPU 1 holds rcu_gp_mutex.
  664. 4. CPU 1 is interrupted, and the irq handler
  665. attempts to acquire problematic_lock.
  666. The system is now deadlocked.
  667. One way to avoid this deadlock is to use an approach like
  668. that of CONFIG_PREEMPT_RT, where all normal spinlocks
  669. become blocking locks, and all irq handlers execute in
  670. the context of special tasks. In this case, in step 4
  671. above, the irq handler would block, allowing CPU 1 to
  672. release rcu_gp_mutex, avoiding the deadlock.
  673. Even in the absence of deadlock, this RCU implementation
  674. allows latency to "bleed" from readers to other
  675. readers through synchronize_rcu(). To see this,
  676. consider task A in an RCU read-side critical section
  677. (thus read-holding rcu_gp_mutex), task B blocked
  678. attempting to write-acquire rcu_gp_mutex, and
  679. task C blocked in rcu_read_lock() attempting to
  680. read_acquire rcu_gp_mutex. Task A's RCU read-side
  681. latency is holding up task C, albeit indirectly via
  682. task B.
  683. Realtime RCU implementations therefore use a counter-based
  684. approach where tasks in RCU read-side critical sections
  685. cannot be blocked by tasks executing synchronize_rcu().
  686. Quick Quiz #2: Give an example where Classic RCU's read-side
  687. overhead is -negative-.
  688. Answer: Imagine a single-CPU system with a non-CONFIG_PREEMPT
  689. kernel where a routing table is used by process-context
  690. code, but can be updated by irq-context code (for example,
  691. by an "ICMP REDIRECT" packet). The usual way of handling
  692. this would be to have the process-context code disable
  693. interrupts while searching the routing table. Use of
  694. RCU allows such interrupt-disabling to be dispensed with.
  695. Thus, without RCU, you pay the cost of disabling interrupts,
  696. and with RCU you don't.
  697. One can argue that the overhead of RCU in this
  698. case is negative with respect to the single-CPU
  699. interrupt-disabling approach. Others might argue that
  700. the overhead of RCU is merely zero, and that replacing
  701. the positive overhead of the interrupt-disabling scheme
  702. with the zero-overhead RCU scheme does not constitute
  703. negative overhead.
  704. In real life, of course, things are more complex. But
  705. even the theoretical possibility of negative overhead for
  706. a synchronization primitive is a bit unexpected. ;-)
  707. Quick Quiz #3: If it is illegal to block in an RCU read-side
  708. critical section, what the heck do you do in
  709. PREEMPT_RT, where normal spinlocks can block???
  710. Answer: Just as PREEMPT_RT permits preemption of spinlock
  711. critical sections, it permits preemption of RCU
  712. read-side critical sections. It also permits
  713. spinlocks blocking while in RCU read-side critical
  714. sections.
  715. Why the apparent inconsistency? Because it is it
  716. possible to use priority boosting to keep the RCU
  717. grace periods short if need be (for example, if running
  718. short of memory). In contrast, if blocking waiting
  719. for (say) network reception, there is no way to know
  720. what should be boosted. Especially given that the
  721. process we need to boost might well be a human being
  722. who just went out for a pizza or something. And although
  723. a computer-operated cattle prod might arouse serious
  724. interest, it might also provoke serious objections.
  725. Besides, how does the computer know what pizza parlor
  726. the human being went to???
  727. ACKNOWLEDGEMENTS
  728. My thanks to the people who helped make this human-readable, including
  729. Jon Walpole, Josh Triplett, Serge Hallyn, Suzanne Wood, and Alan Stern.
  730. For more information, see http://www.rdrop.com/users/paulmck/RCU.