whatisRCU.txt 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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_TREE_PREEMPT_RCU can preempt RCU
  113. read-side critical sections. Any RCU-protected data structure
  114. accessed during an RCU read-side critical section is guaranteed to
  115. remain 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() rcu_dereference()
  262. b. call_rcu_bh() rcu_read_lock_bh() / rcu_read_unlock_bh()
  263. rcu_dereference_bh()
  264. c. synchronize_sched() rcu_read_lock_sched() / rcu_read_unlock_sched()
  265. preempt_disable() / preempt_enable()
  266. local_irq_save() / local_irq_restore()
  267. hardirq enter / hardirq exit
  268. NMI enter / NMI exit
  269. rcu_dereference_sched()
  270. These three mechanisms are used as follows:
  271. a. RCU applied to normal data structures.
  272. b. RCU applied to networking data structures that may be subjected
  273. to remote denial-of-service attacks.
  274. c. RCU applied to scheduler and interrupt/NMI-handler tasks.
  275. Again, most uses will be of (a). The (b) and (c) cases are important
  276. for specialized uses, but are relatively uncommon.
  277. 3. WHAT ARE SOME EXAMPLE USES OF CORE RCU API?
  278. This section shows a simple use of the core RCU API to protect a
  279. global pointer to a dynamically allocated structure. More-typical
  280. uses of RCU may be found in listRCU.txt, arrayRCU.txt, and NMI-RCU.txt.
  281. struct foo {
  282. int a;
  283. char b;
  284. long c;
  285. };
  286. DEFINE_SPINLOCK(foo_mutex);
  287. struct foo *gbl_foo;
  288. /*
  289. * Create a new struct foo that is the same as the one currently
  290. * pointed to by gbl_foo, except that field "a" is replaced
  291. * with "new_a". Points gbl_foo to the new structure, and
  292. * frees up the old structure after a grace period.
  293. *
  294. * Uses rcu_assign_pointer() to ensure that concurrent readers
  295. * see the initialized version of the new structure.
  296. *
  297. * Uses synchronize_rcu() to ensure that any readers that might
  298. * have references to the old structure complete before freeing
  299. * the old structure.
  300. */
  301. void foo_update_a(int new_a)
  302. {
  303. struct foo *new_fp;
  304. struct foo *old_fp;
  305. new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL);
  306. spin_lock(&foo_mutex);
  307. old_fp = gbl_foo;
  308. *new_fp = *old_fp;
  309. new_fp->a = new_a;
  310. rcu_assign_pointer(gbl_foo, new_fp);
  311. spin_unlock(&foo_mutex);
  312. synchronize_rcu();
  313. kfree(old_fp);
  314. }
  315. /*
  316. * Return the value of field "a" of the current gbl_foo
  317. * structure. Use rcu_read_lock() and rcu_read_unlock()
  318. * to ensure that the structure does not get deleted out
  319. * from under us, and use rcu_dereference() to ensure that
  320. * we see the initialized version of the structure (important
  321. * for DEC Alpha and for people reading the code).
  322. */
  323. int foo_get_a(void)
  324. {
  325. int retval;
  326. rcu_read_lock();
  327. retval = rcu_dereference(gbl_foo)->a;
  328. rcu_read_unlock();
  329. return retval;
  330. }
  331. So, to sum up:
  332. o Use rcu_read_lock() and rcu_read_unlock() to guard RCU
  333. read-side critical sections.
  334. o Within an RCU read-side critical section, use rcu_dereference()
  335. to dereference RCU-protected pointers.
  336. o Use some solid scheme (such as locks or semaphores) to
  337. keep concurrent updates from interfering with each other.
  338. o Use rcu_assign_pointer() to update an RCU-protected pointer.
  339. This primitive protects concurrent readers from the updater,
  340. -not- concurrent updates from each other! You therefore still
  341. need to use locking (or something similar) to keep concurrent
  342. rcu_assign_pointer() primitives from interfering with each other.
  343. o Use synchronize_rcu() -after- removing a data element from an
  344. RCU-protected data structure, but -before- reclaiming/freeing
  345. the data element, in order to wait for the completion of all
  346. RCU read-side critical sections that might be referencing that
  347. data item.
  348. See checklist.txt for additional rules to follow when using RCU.
  349. And again, more-typical uses of RCU may be found in listRCU.txt,
  350. arrayRCU.txt, and NMI-RCU.txt.
  351. 4. WHAT IF MY UPDATING THREAD CANNOT BLOCK?
  352. In the example above, foo_update_a() blocks until a grace period elapses.
  353. This is quite simple, but in some cases one cannot afford to wait so
  354. long -- there might be other high-priority work to be done.
  355. In such cases, one uses call_rcu() rather than synchronize_rcu().
  356. The call_rcu() API is as follows:
  357. void call_rcu(struct rcu_head * head,
  358. void (*func)(struct rcu_head *head));
  359. This function invokes func(head) after a grace period has elapsed.
  360. This invocation might happen from either softirq or process context,
  361. so the function is not permitted to block. The foo struct needs to
  362. have an rcu_head structure added, perhaps as follows:
  363. struct foo {
  364. int a;
  365. char b;
  366. long c;
  367. struct rcu_head rcu;
  368. };
  369. The foo_update_a() function might then be written as follows:
  370. /*
  371. * Create a new struct foo that is the same as the one currently
  372. * pointed to by gbl_foo, except that field "a" is replaced
  373. * with "new_a". Points gbl_foo to the new structure, and
  374. * frees up the old structure after a grace period.
  375. *
  376. * Uses rcu_assign_pointer() to ensure that concurrent readers
  377. * see the initialized version of the new structure.
  378. *
  379. * Uses call_rcu() to ensure that any readers that might have
  380. * references to the old structure complete before freeing the
  381. * old structure.
  382. */
  383. void foo_update_a(int new_a)
  384. {
  385. struct foo *new_fp;
  386. struct foo *old_fp;
  387. new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL);
  388. spin_lock(&foo_mutex);
  389. old_fp = gbl_foo;
  390. *new_fp = *old_fp;
  391. new_fp->a = new_a;
  392. rcu_assign_pointer(gbl_foo, new_fp);
  393. spin_unlock(&foo_mutex);
  394. call_rcu(&old_fp->rcu, foo_reclaim);
  395. }
  396. The foo_reclaim() function might appear as follows:
  397. void foo_reclaim(struct rcu_head *rp)
  398. {
  399. struct foo *fp = container_of(rp, struct foo, rcu);
  400. kfree(fp);
  401. }
  402. The container_of() primitive is a macro that, given a pointer into a
  403. struct, the type of the struct, and the pointed-to field within the
  404. struct, returns a pointer to the beginning of the struct.
  405. The use of call_rcu() permits the caller of foo_update_a() to
  406. immediately regain control, without needing to worry further about the
  407. old version of the newly updated element. It also clearly shows the
  408. RCU distinction between updater, namely foo_update_a(), and reclaimer,
  409. namely foo_reclaim().
  410. The summary of advice is the same as for the previous section, except
  411. that we are now using call_rcu() rather than synchronize_rcu():
  412. o Use call_rcu() -after- removing a data element from an
  413. RCU-protected data structure in order to register a callback
  414. function that will be invoked after the completion of all RCU
  415. read-side critical sections that might be referencing that
  416. data item.
  417. Again, see checklist.txt for additional rules governing the use of RCU.
  418. 5. WHAT ARE SOME SIMPLE IMPLEMENTATIONS OF RCU?
  419. One of the nice things about RCU is that it has extremely simple "toy"
  420. implementations that are a good first step towards understanding the
  421. production-quality implementations in the Linux kernel. This section
  422. presents two such "toy" implementations of RCU, one that is implemented
  423. in terms of familiar locking primitives, and another that more closely
  424. resembles "classic" RCU. Both are way too simple for real-world use,
  425. lacking both functionality and performance. However, they are useful
  426. in getting a feel for how RCU works. See kernel/rcupdate.c for a
  427. production-quality implementation, and see:
  428. http://www.rdrop.com/users/paulmck/RCU
  429. for papers describing the Linux kernel RCU implementation. The OLS'01
  430. and OLS'02 papers are a good introduction, and the dissertation provides
  431. more details on the current implementation as of early 2004.
  432. 5A. "TOY" IMPLEMENTATION #1: LOCKING
  433. This section presents a "toy" RCU implementation that is based on
  434. familiar locking primitives. Its overhead makes it a non-starter for
  435. real-life use, as does its lack of scalability. It is also unsuitable
  436. for realtime use, since it allows scheduling latency to "bleed" from
  437. one read-side critical section to another.
  438. However, it is probably the easiest implementation to relate to, so is
  439. a good starting point.
  440. It is extremely simple:
  441. static DEFINE_RWLOCK(rcu_gp_mutex);
  442. void rcu_read_lock(void)
  443. {
  444. read_lock(&rcu_gp_mutex);
  445. }
  446. void rcu_read_unlock(void)
  447. {
  448. read_unlock(&rcu_gp_mutex);
  449. }
  450. void synchronize_rcu(void)
  451. {
  452. write_lock(&rcu_gp_mutex);
  453. write_unlock(&rcu_gp_mutex);
  454. }
  455. [You can ignore rcu_assign_pointer() and rcu_dereference() without
  456. missing much. But here they are anyway. And whatever you do, don't
  457. forget about them when submitting patches making use of RCU!]
  458. #define rcu_assign_pointer(p, v) ({ \
  459. smp_wmb(); \
  460. (p) = (v); \
  461. })
  462. #define rcu_dereference(p) ({ \
  463. typeof(p) _________p1 = p; \
  464. smp_read_barrier_depends(); \
  465. (_________p1); \
  466. })
  467. The rcu_read_lock() and rcu_read_unlock() primitive read-acquire
  468. and release a global reader-writer lock. The synchronize_rcu()
  469. primitive write-acquires this same lock, then immediately releases
  470. it. This means that once synchronize_rcu() exits, all RCU read-side
  471. critical sections that were in progress before synchronize_rcu() was
  472. called are guaranteed to have completed -- there is no way that
  473. synchronize_rcu() would have been able to write-acquire the lock
  474. otherwise.
  475. It is possible to nest rcu_read_lock(), since reader-writer locks may
  476. be recursively acquired. Note also that rcu_read_lock() is immune
  477. from deadlock (an important property of RCU). The reason for this is
  478. that the only thing that can block rcu_read_lock() is a synchronize_rcu().
  479. But synchronize_rcu() does not acquire any locks while holding rcu_gp_mutex,
  480. so there can be no deadlock cycle.
  481. Quick Quiz #1: Why is this argument naive? How could a deadlock
  482. occur when using this algorithm in a real-world Linux
  483. kernel? How could this deadlock be avoided?
  484. 5B. "TOY" EXAMPLE #2: CLASSIC RCU
  485. This section presents a "toy" RCU implementation that is based on
  486. "classic RCU". It is also short on performance (but only for updates) and
  487. on features such as hotplug CPU and the ability to run in CONFIG_PREEMPT
  488. kernels. The definitions of rcu_dereference() and rcu_assign_pointer()
  489. are the same as those shown in the preceding section, so they are omitted.
  490. void rcu_read_lock(void) { }
  491. void rcu_read_unlock(void) { }
  492. void synchronize_rcu(void)
  493. {
  494. int cpu;
  495. for_each_possible_cpu(cpu)
  496. run_on(cpu);
  497. }
  498. Note that rcu_read_lock() and rcu_read_unlock() do absolutely nothing.
  499. This is the great strength of classic RCU in a non-preemptive kernel:
  500. read-side overhead is precisely zero, at least on non-Alpha CPUs.
  501. And there is absolutely no way that rcu_read_lock() can possibly
  502. participate in a deadlock cycle!
  503. The implementation of synchronize_rcu() simply schedules itself on each
  504. CPU in turn. The run_on() primitive can be implemented straightforwardly
  505. in terms of the sched_setaffinity() primitive. Of course, a somewhat less
  506. "toy" implementation would restore the affinity upon completion rather
  507. than just leaving all tasks running on the last CPU, but when I said
  508. "toy", I meant -toy-!
  509. So how the heck is this supposed to work???
  510. Remember that it is illegal to block while in an RCU read-side critical
  511. section. Therefore, if a given CPU executes a context switch, we know
  512. that it must have completed all preceding RCU read-side critical sections.
  513. Once -all- CPUs have executed a context switch, then -all- preceding
  514. RCU read-side critical sections will have completed.
  515. So, suppose that we remove a data item from its structure and then invoke
  516. synchronize_rcu(). Once synchronize_rcu() returns, we are guaranteed
  517. that there are no RCU read-side critical sections holding a reference
  518. to that data item, so we can safely reclaim it.
  519. Quick Quiz #2: Give an example where Classic RCU's read-side
  520. overhead is -negative-.
  521. Quick Quiz #3: If it is illegal to block in an RCU read-side
  522. critical section, what the heck do you do in
  523. PREEMPT_RT, where normal spinlocks can block???
  524. 6. ANALOGY WITH READER-WRITER LOCKING
  525. Although RCU can be used in many different ways, a very common use of
  526. RCU is analogous to reader-writer locking. The following unified
  527. diff shows how closely related RCU and reader-writer locking can be.
  528. @@ -13,15 +14,15 @@
  529. struct list_head *lp;
  530. struct el *p;
  531. - read_lock();
  532. - list_for_each_entry(p, head, lp) {
  533. + rcu_read_lock();
  534. + list_for_each_entry_rcu(p, head, lp) {
  535. if (p->key == key) {
  536. *result = p->data;
  537. - read_unlock();
  538. + rcu_read_unlock();
  539. return 1;
  540. }
  541. }
  542. - read_unlock();
  543. + rcu_read_unlock();
  544. return 0;
  545. }
  546. @@ -29,15 +30,16 @@
  547. {
  548. struct el *p;
  549. - write_lock(&listmutex);
  550. + spin_lock(&listmutex);
  551. list_for_each_entry(p, head, lp) {
  552. if (p->key == key) {
  553. - list_del(&p->list);
  554. - write_unlock(&listmutex);
  555. + list_del_rcu(&p->list);
  556. + spin_unlock(&listmutex);
  557. + synchronize_rcu();
  558. kfree(p);
  559. return 1;
  560. }
  561. }
  562. - write_unlock(&listmutex);
  563. + spin_unlock(&listmutex);
  564. return 0;
  565. }
  566. Or, for those who prefer a side-by-side listing:
  567. 1 struct el { 1 struct el {
  568. 2 struct list_head list; 2 struct list_head list;
  569. 3 long key; 3 long key;
  570. 4 spinlock_t mutex; 4 spinlock_t mutex;
  571. 5 int data; 5 int data;
  572. 6 /* Other data fields */ 6 /* Other data fields */
  573. 7 }; 7 };
  574. 8 spinlock_t listmutex; 8 spinlock_t listmutex;
  575. 9 struct el head; 9 struct el head;
  576. 1 int search(long key, int *result) 1 int search(long key, int *result)
  577. 2 { 2 {
  578. 3 struct list_head *lp; 3 struct list_head *lp;
  579. 4 struct el *p; 4 struct el *p;
  580. 5 5
  581. 6 read_lock(); 6 rcu_read_lock();
  582. 7 list_for_each_entry(p, head, lp) { 7 list_for_each_entry_rcu(p, head, lp) {
  583. 8 if (p->key == key) { 8 if (p->key == key) {
  584. 9 *result = p->data; 9 *result = p->data;
  585. 10 read_unlock(); 10 rcu_read_unlock();
  586. 11 return 1; 11 return 1;
  587. 12 } 12 }
  588. 13 } 13 }
  589. 14 read_unlock(); 14 rcu_read_unlock();
  590. 15 return 0; 15 return 0;
  591. 16 } 16 }
  592. 1 int delete(long key) 1 int delete(long key)
  593. 2 { 2 {
  594. 3 struct el *p; 3 struct el *p;
  595. 4 4
  596. 5 write_lock(&listmutex); 5 spin_lock(&listmutex);
  597. 6 list_for_each_entry(p, head, lp) { 6 list_for_each_entry(p, head, lp) {
  598. 7 if (p->key == key) { 7 if (p->key == key) {
  599. 8 list_del(&p->list); 8 list_del_rcu(&p->list);
  600. 9 write_unlock(&listmutex); 9 spin_unlock(&listmutex);
  601. 10 synchronize_rcu();
  602. 10 kfree(p); 11 kfree(p);
  603. 11 return 1; 12 return 1;
  604. 12 } 13 }
  605. 13 } 14 }
  606. 14 write_unlock(&listmutex); 15 spin_unlock(&listmutex);
  607. 15 return 0; 16 return 0;
  608. 16 } 17 }
  609. Either way, the differences are quite small. Read-side locking moves
  610. to rcu_read_lock() and rcu_read_unlock, update-side locking moves from
  611. a reader-writer lock to a simple spinlock, and a synchronize_rcu()
  612. precedes the kfree().
  613. However, there is one potential catch: the read-side and update-side
  614. critical sections can now run concurrently. In many cases, this will
  615. not be a problem, but it is necessary to check carefully regardless.
  616. For example, if multiple independent list updates must be seen as
  617. a single atomic update, converting to RCU will require special care.
  618. Also, the presence of synchronize_rcu() means that the RCU version of
  619. delete() can now block. If this is a problem, there is a callback-based
  620. mechanism that never blocks, namely call_rcu(), that can be used in
  621. place of synchronize_rcu().
  622. 7. FULL LIST OF RCU APIs
  623. The RCU APIs are documented in docbook-format header comments in the
  624. Linux-kernel source code, but it helps to have a full list of the
  625. APIs, since there does not appear to be a way to categorize them
  626. in docbook. Here is the list, by category.
  627. RCU list traversal:
  628. list_for_each_entry_rcu
  629. hlist_for_each_entry_rcu
  630. hlist_nulls_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. RCU pointer/list update:
  634. rcu_assign_pointer
  635. list_add_rcu
  636. list_add_tail_rcu
  637. list_del_rcu
  638. list_replace_rcu
  639. hlist_del_rcu
  640. hlist_add_after_rcu
  641. hlist_add_before_rcu
  642. hlist_add_head_rcu
  643. hlist_replace_rcu
  644. list_splice_init_rcu()
  645. RCU: Critical sections Grace period Barrier
  646. rcu_read_lock synchronize_net rcu_barrier
  647. rcu_read_unlock synchronize_rcu
  648. rcu_dereference synchronize_rcu_expedited
  649. call_rcu
  650. bh: Critical sections Grace period Barrier
  651. rcu_read_lock_bh call_rcu_bh rcu_barrier_bh
  652. rcu_read_unlock_bh synchronize_rcu_bh
  653. rcu_dereference_bh synchronize_rcu_bh_expedited
  654. sched: Critical sections Grace period Barrier
  655. rcu_read_lock_sched synchronize_sched rcu_barrier_sched
  656. rcu_read_unlock_sched call_rcu_sched
  657. [preempt_disable] synchronize_sched_expedited
  658. [and friends]
  659. rcu_dereference_sched
  660. SRCU: Critical sections Grace period Barrier
  661. srcu_read_lock synchronize_srcu N/A
  662. srcu_read_unlock synchronize_srcu_expedited
  663. srcu_dereference
  664. SRCU: Initialization/cleanup
  665. init_srcu_struct
  666. cleanup_srcu_struct
  667. All: lockdep-checked RCU-protected pointer access
  668. rcu_dereference_check
  669. rcu_dereference_protected
  670. rcu_access_pointer
  671. See the comment headers in the source code (or the docbook generated
  672. from them) for more information.
  673. However, given that there are no fewer than four families of RCU APIs
  674. in the Linux kernel, how do you choose which one to use? The following
  675. list can be helpful:
  676. a. Will readers need to block? If so, you need SRCU.
  677. b. What about the -rt patchset? If readers would need to block
  678. in an non-rt kernel, you need SRCU. If readers would block
  679. in a -rt kernel, but not in a non-rt kernel, SRCU is not
  680. necessary.
  681. c. Do you need to treat NMI handlers, hardirq handlers,
  682. and code segments with preemption disabled (whether
  683. via preempt_disable(), local_irq_save(), local_bh_disable(),
  684. or some other mechanism) as if they were explicit RCU readers?
  685. If so, you need RCU-sched.
  686. d. Do you need RCU grace periods to complete even in the face
  687. of softirq monopolization of one or more of the CPUs? For
  688. example, is your code subject to network-based denial-of-service
  689. attacks? If so, you need RCU-bh.
  690. e. Is your workload too update-intensive for normal use of
  691. RCU, but inappropriate for other synchronization mechanisms?
  692. If so, consider SLAB_DESTROY_BY_RCU. But please be careful!
  693. f. Otherwise, use RCU.
  694. Of course, this all assumes that you have determined that RCU is in fact
  695. the right tool for your job.
  696. 8. ANSWERS TO QUICK QUIZZES
  697. Quick Quiz #1: Why is this argument naive? How could a deadlock
  698. occur when using this algorithm in a real-world Linux
  699. kernel? [Referring to the lock-based "toy" RCU
  700. algorithm.]
  701. Answer: Consider the following sequence of events:
  702. 1. CPU 0 acquires some unrelated lock, call it
  703. "problematic_lock", disabling irq via
  704. spin_lock_irqsave().
  705. 2. CPU 1 enters synchronize_rcu(), write-acquiring
  706. rcu_gp_mutex.
  707. 3. CPU 0 enters rcu_read_lock(), but must wait
  708. because CPU 1 holds rcu_gp_mutex.
  709. 4. CPU 1 is interrupted, and the irq handler
  710. attempts to acquire problematic_lock.
  711. The system is now deadlocked.
  712. One way to avoid this deadlock is to use an approach like
  713. that of CONFIG_PREEMPT_RT, where all normal spinlocks
  714. become blocking locks, and all irq handlers execute in
  715. the context of special tasks. In this case, in step 4
  716. above, the irq handler would block, allowing CPU 1 to
  717. release rcu_gp_mutex, avoiding the deadlock.
  718. Even in the absence of deadlock, this RCU implementation
  719. allows latency to "bleed" from readers to other
  720. readers through synchronize_rcu(). To see this,
  721. consider task A in an RCU read-side critical section
  722. (thus read-holding rcu_gp_mutex), task B blocked
  723. attempting to write-acquire rcu_gp_mutex, and
  724. task C blocked in rcu_read_lock() attempting to
  725. read_acquire rcu_gp_mutex. Task A's RCU read-side
  726. latency is holding up task C, albeit indirectly via
  727. task B.
  728. Realtime RCU implementations therefore use a counter-based
  729. approach where tasks in RCU read-side critical sections
  730. cannot be blocked by tasks executing synchronize_rcu().
  731. Quick Quiz #2: Give an example where Classic RCU's read-side
  732. overhead is -negative-.
  733. Answer: Imagine a single-CPU system with a non-CONFIG_PREEMPT
  734. kernel where a routing table is used by process-context
  735. code, but can be updated by irq-context code (for example,
  736. by an "ICMP REDIRECT" packet). The usual way of handling
  737. this would be to have the process-context code disable
  738. interrupts while searching the routing table. Use of
  739. RCU allows such interrupt-disabling to be dispensed with.
  740. Thus, without RCU, you pay the cost of disabling interrupts,
  741. and with RCU you don't.
  742. One can argue that the overhead of RCU in this
  743. case is negative with respect to the single-CPU
  744. interrupt-disabling approach. Others might argue that
  745. the overhead of RCU is merely zero, and that replacing
  746. the positive overhead of the interrupt-disabling scheme
  747. with the zero-overhead RCU scheme does not constitute
  748. negative overhead.
  749. In real life, of course, things are more complex. But
  750. even the theoretical possibility of negative overhead for
  751. a synchronization primitive is a bit unexpected. ;-)
  752. Quick Quiz #3: If it is illegal to block in an RCU read-side
  753. critical section, what the heck do you do in
  754. PREEMPT_RT, where normal spinlocks can block???
  755. Answer: Just as PREEMPT_RT permits preemption of spinlock
  756. critical sections, it permits preemption of RCU
  757. read-side critical sections. It also permits
  758. spinlocks blocking while in RCU read-side critical
  759. sections.
  760. Why the apparent inconsistency? Because it is it
  761. possible to use priority boosting to keep the RCU
  762. grace periods short if need be (for example, if running
  763. short of memory). In contrast, if blocking waiting
  764. for (say) network reception, there is no way to know
  765. what should be boosted. Especially given that the
  766. process we need to boost might well be a human being
  767. who just went out for a pizza or something. And although
  768. a computer-operated cattle prod might arouse serious
  769. interest, it might also provoke serious objections.
  770. Besides, how does the computer know what pizza parlor
  771. the human being went to???
  772. ACKNOWLEDGEMENTS
  773. My thanks to the people who helped make this human-readable, including
  774. Jon Walpole, Josh Triplett, Serge Hallyn, Suzanne Wood, and Alan Stern.
  775. For more information, see http://www.rdrop.com/users/paulmck/RCU.