whatisRCU.txt 34 KB

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