whatisRCU.txt 33 KB

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