whatisRCU.txt 35 KB

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