documentation: Get rid of duplicate .htmlx file
[deliverable/linux.git] / Documentation / RCU / Design / Requirements / Requirements.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
2 "http://www.w3.org/TR/html4/loose.dtd">
3 <html>
4 <head><title>A Tour Through RCU's Requirements [LWN.net]</title>
5 <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
6
7 <h1>A Tour Through RCU's Requirements</h1>
8
9 <p>Copyright IBM Corporation, 2015</p>
10 <p>Author: Paul E.&nbsp;McKenney</p>
11 <p><i>The initial version of this document appeared in the
12 <a href="https://lwn.net/">LWN</a> articles
13 <a href="https://lwn.net/Articles/652156/">here</a>,
14 <a href="https://lwn.net/Articles/652677/">here</a>, and
15 <a href="https://lwn.net/Articles/653326/">here</a>.</i></p>
16
17 <h2>Introduction</h2>
18
19 <p>
20 Read-copy update (RCU) is a synchronization mechanism that is often
21 used as a replacement for reader-writer locking.
22 RCU is unusual in that updaters do not block readers,
23 which means that RCU's read-side primitives can be exceedingly fast
24 and scalable.
25 In addition, updaters can make useful forward progress concurrently
26 with readers.
27 However, all this concurrency between RCU readers and updaters does raise
28 the question of exactly what RCU readers are doing, which in turn
29 raises the question of exactly what RCU's requirements are.
30
31 <p>
32 This document therefore summarizes RCU's requirements, and can be thought
33 of as an informal, high-level specification for RCU.
34 It is important to understand that RCU's specification is primarily
35 empirical in nature;
36 in fact, I learned about many of these requirements the hard way.
37 This situation might cause some consternation, however, not only
38 has this learning process been a lot of fun, but it has also been
39 a great privilege to work with so many people willing to apply
40 technologies in interesting new ways.
41
42 <p>
43 All that aside, here are the categories of currently known RCU requirements:
44 </p>
45
46 <ol>
47 <li> <a href="#Fundamental Requirements">
48 Fundamental Requirements</a>
49 <li> <a href="#Fundamental Non-Requirements">Fundamental Non-Requirements</a>
50 <li> <a href="#Parallelism Facts of Life">
51 Parallelism Facts of Life</a>
52 <li> <a href="#Quality-of-Implementation Requirements">
53 Quality-of-Implementation Requirements</a>
54 <li> <a href="#Linux Kernel Complications">
55 Linux Kernel Complications</a>
56 <li> <a href="#Software-Engineering Requirements">
57 Software-Engineering Requirements</a>
58 <li> <a href="#Other RCU Flavors">
59 Other RCU Flavors</a>
60 <li> <a href="#Possible Future Changes">
61 Possible Future Changes</a>
62 </ol>
63
64 <p>
65 This is followed by a <a href="#Summary">summary</a>,
66 however, the answers to each quick quiz immediately follows the quiz.
67 Select the big white space with your mouse to see the answer.
68
69 <h2><a name="Fundamental Requirements">Fundamental Requirements</a></h2>
70
71 <p>
72 RCU's fundamental requirements are the closest thing RCU has to hard
73 mathematical requirements.
74 These are:
75
76 <ol>
77 <li> <a href="#Grace-Period Guarantee">
78 Grace-Period Guarantee</a>
79 <li> <a href="#Publish-Subscribe Guarantee">
80 Publish-Subscribe Guarantee</a>
81 <li> <a href="#Memory-Barrier Guarantees">
82 Memory-Barrier Guarantees</a>
83 <li> <a href="#RCU Primitives Guaranteed to Execute Unconditionally">
84 RCU Primitives Guaranteed to Execute Unconditionally</a>
85 <li> <a href="#Guaranteed Read-to-Write Upgrade">
86 Guaranteed Read-to-Write Upgrade</a>
87 </ol>
88
89 <h3><a name="Grace-Period Guarantee">Grace-Period Guarantee</a></h3>
90
91 <p>
92 RCU's grace-period guarantee is unusual in being premeditated:
93 Jack Slingwine and I had this guarantee firmly in mind when we started
94 work on RCU (then called &ldquo;rclock&rdquo;) in the early 1990s.
95 That said, the past two decades of experience with RCU have produced
96 a much more detailed understanding of this guarantee.
97
98 <p>
99 RCU's grace-period guarantee allows updaters to wait for the completion
100 of all pre-existing RCU read-side critical sections.
101 An RCU read-side critical section
102 begins with the marker <tt>rcu_read_lock()</tt> and ends with
103 the marker <tt>rcu_read_unlock()</tt>.
104 These markers may be nested, and RCU treats a nested set as one
105 big RCU read-side critical section.
106 Production-quality implementations of <tt>rcu_read_lock()</tt> and
107 <tt>rcu_read_unlock()</tt> are extremely lightweight, and in
108 fact have exactly zero overhead in Linux kernels built for production
109 use with <tt>CONFIG_PREEMPT=n</tt>.
110
111 <p>
112 This guarantee allows ordering to be enforced with extremely low
113 overhead to readers, for example:
114
115 <blockquote>
116 <pre>
117 1 int x, y;
118 2
119 3 void thread0(void)
120 4 {
121 5 rcu_read_lock();
122 6 r1 = READ_ONCE(x);
123 7 r2 = READ_ONCE(y);
124 8 rcu_read_unlock();
125 9 }
126 10
127 11 void thread1(void)
128 12 {
129 13 WRITE_ONCE(x, 1);
130 14 synchronize_rcu();
131 15 WRITE_ONCE(y, 1);
132 16 }
133 </pre>
134 </blockquote>
135
136 <p>
137 Because the <tt>synchronize_rcu()</tt> on line&nbsp;14 waits for
138 all pre-existing readers, any instance of <tt>thread0()</tt> that
139 loads a value of zero from <tt>x</tt> must complete before
140 <tt>thread1()</tt> stores to <tt>y</tt>, so that instance must
141 also load a value of zero from <tt>y</tt>.
142 Similarly, any instance of <tt>thread0()</tt> that loads a value of
143 one from <tt>y</tt> must have started after the
144 <tt>synchronize_rcu()</tt> started, and must therefore also load
145 a value of one from <tt>x</tt>.
146 Therefore, the outcome:
147 <blockquote>
148 <pre>
149 (r1 == 0 &amp;&amp; r2 == 1)
150 </pre>
151 </blockquote>
152 cannot happen.
153
154 <table>
155 <tr><th>&nbsp;</th></tr>
156 <tr><th align="left">Quick Quiz:</th></tr>
157 <tr><td>
158 Wait a minute!
159 You said that updaters can make useful forward progress concurrently
160 with readers, but pre-existing readers will block
161 <tt>synchronize_rcu()</tt>!!!
162 Just who are you trying to fool???
163 </td></tr>
164 <tr><th align="left">Answer:</th></tr>
165 <tr><td bgcolor="#ffffff"><font color="ffffff">
166 First, if updaters do not wish to be blocked by readers, they can use
167 <tt>call_rcu()</tt> or <tt>kfree_rcu()</tt>, which will
168 be discussed later.
169 Second, even when using <tt>synchronize_rcu()</tt>, the other
170 update-side code does run concurrently with readers, whether
171 pre-existing or not.
172 </font></td></tr>
173 <tr><td>&nbsp;</td></tr>
174 </table>
175
176 <p>
177 This scenario resembles one of the first uses of RCU in
178 <a href="https://en.wikipedia.org/wiki/DYNIX">DYNIX/ptx</a>,
179 which managed a distributed lock manager's transition into
180 a state suitable for handling recovery from node failure,
181 more or less as follows:
182
183 <blockquote>
184 <pre>
185 1 #define STATE_NORMAL 0
186 2 #define STATE_WANT_RECOVERY 1
187 3 #define STATE_RECOVERING 2
188 4 #define STATE_WANT_NORMAL 3
189 5
190 6 int state = STATE_NORMAL;
191 7
192 8 void do_something_dlm(void)
193 9 {
194 10 int state_snap;
195 11
196 12 rcu_read_lock();
197 13 state_snap = READ_ONCE(state);
198 14 if (state_snap == STATE_NORMAL)
199 15 do_something();
200 16 else
201 17 do_something_carefully();
202 18 rcu_read_unlock();
203 19 }
204 20
205 21 void start_recovery(void)
206 22 {
207 23 WRITE_ONCE(state, STATE_WANT_RECOVERY);
208 24 synchronize_rcu();
209 25 WRITE_ONCE(state, STATE_RECOVERING);
210 26 recovery();
211 27 WRITE_ONCE(state, STATE_WANT_NORMAL);
212 28 synchronize_rcu();
213 29 WRITE_ONCE(state, STATE_NORMAL);
214 30 }
215 </pre>
216 </blockquote>
217
218 <p>
219 The RCU read-side critical section in <tt>do_something_dlm()</tt>
220 works with the <tt>synchronize_rcu()</tt> in <tt>start_recovery()</tt>
221 to guarantee that <tt>do_something()</tt> never runs concurrently
222 with <tt>recovery()</tt>, but with little or no synchronization
223 overhead in <tt>do_something_dlm()</tt>.
224
225 <table>
226 <tr><th>&nbsp;</th></tr>
227 <tr><th align="left">Quick Quiz:</th></tr>
228 <tr><td>
229 Why is the <tt>synchronize_rcu()</tt> on line&nbsp;28 needed?
230 </td></tr>
231 <tr><th align="left">Answer:</th></tr>
232 <tr><td bgcolor="#ffffff"><font color="ffffff">
233 Without that extra grace period, memory reordering could result in
234 <tt>do_something_dlm()</tt> executing <tt>do_something()</tt>
235 concurrently with the last bits of <tt>recovery()</tt>.
236 </font></td></tr>
237 <tr><td>&nbsp;</td></tr>
238 </table>
239
240 <p>
241 In order to avoid fatal problems such as deadlocks,
242 an RCU read-side critical section must not contain calls to
243 <tt>synchronize_rcu()</tt>.
244 Similarly, an RCU read-side critical section must not
245 contain anything that waits, directly or indirectly, on completion of
246 an invocation of <tt>synchronize_rcu()</tt>.
247
248 <p>
249 Although RCU's grace-period guarantee is useful in and of itself, with
250 <a href="https://lwn.net/Articles/573497/">quite a few use cases</a>,
251 it would be good to be able to use RCU to coordinate read-side
252 access to linked data structures.
253 For this, the grace-period guarantee is not sufficient, as can
254 be seen in function <tt>add_gp_buggy()</tt> below.
255 We will look at the reader's code later, but in the meantime, just think of
256 the reader as locklessly picking up the <tt>gp</tt> pointer,
257 and, if the value loaded is non-<tt>NULL</tt>, locklessly accessing the
258 <tt>-&gt;a</tt> and <tt>-&gt;b</tt> fields.
259
260 <blockquote>
261 <pre>
262 1 bool add_gp_buggy(int a, int b)
263 2 {
264 3 p = kmalloc(sizeof(*p), GFP_KERNEL);
265 4 if (!p)
266 5 return -ENOMEM;
267 6 spin_lock(&amp;gp_lock);
268 7 if (rcu_access_pointer(gp)) {
269 8 spin_unlock(&amp;gp_lock);
270 9 return false;
271 10 }
272 11 p-&gt;a = a;
273 12 p-&gt;b = a;
274 13 gp = p; /* ORDERING BUG */
275 14 spin_unlock(&amp;gp_lock);
276 15 return true;
277 16 }
278 </pre>
279 </blockquote>
280
281 <p>
282 The problem is that both the compiler and weakly ordered CPUs are within
283 their rights to reorder this code as follows:
284
285 <blockquote>
286 <pre>
287 1 bool add_gp_buggy_optimized(int a, int b)
288 2 {
289 3 p = kmalloc(sizeof(*p), GFP_KERNEL);
290 4 if (!p)
291 5 return -ENOMEM;
292 6 spin_lock(&amp;gp_lock);
293 7 if (rcu_access_pointer(gp)) {
294 8 spin_unlock(&amp;gp_lock);
295 9 return false;
296 10 }
297 <b>11 gp = p; /* ORDERING BUG */
298 12 p-&gt;a = a;
299 13 p-&gt;b = a;</b>
300 14 spin_unlock(&amp;gp_lock);
301 15 return true;
302 16 }
303 </pre>
304 </blockquote>
305
306 <p>
307 If an RCU reader fetches <tt>gp</tt> just after
308 <tt>add_gp_buggy_optimized</tt> executes line&nbsp;11,
309 it will see garbage in the <tt>-&gt;a</tt> and <tt>-&gt;b</tt>
310 fields.
311 And this is but one of many ways in which compiler and hardware optimizations
312 could cause trouble.
313 Therefore, we clearly need some way to prevent the compiler and the CPU from
314 reordering in this manner, which brings us to the publish-subscribe
315 guarantee discussed in the next section.
316
317 <h3><a name="Publish-Subscribe Guarantee">Publish/Subscribe Guarantee</a></h3>
318
319 <p>
320 RCU's publish-subscribe guarantee allows data to be inserted
321 into a linked data structure without disrupting RCU readers.
322 The updater uses <tt>rcu_assign_pointer()</tt> to insert the
323 new data, and readers use <tt>rcu_dereference()</tt> to
324 access data, whether new or old.
325 The following shows an example of insertion:
326
327 <blockquote>
328 <pre>
329 1 bool add_gp(int a, int b)
330 2 {
331 3 p = kmalloc(sizeof(*p), GFP_KERNEL);
332 4 if (!p)
333 5 return -ENOMEM;
334 6 spin_lock(&amp;gp_lock);
335 7 if (rcu_access_pointer(gp)) {
336 8 spin_unlock(&amp;gp_lock);
337 9 return false;
338 10 }
339 11 p-&gt;a = a;
340 12 p-&gt;b = a;
341 13 rcu_assign_pointer(gp, p);
342 14 spin_unlock(&amp;gp_lock);
343 15 return true;
344 16 }
345 </pre>
346 </blockquote>
347
348 <p>
349 The <tt>rcu_assign_pointer()</tt> on line&nbsp;13 is conceptually
350 equivalent to a simple assignment statement, but also guarantees
351 that its assignment will
352 happen after the two assignments in lines&nbsp;11 and&nbsp;12,
353 similar to the C11 <tt>memory_order_release</tt> store operation.
354 It also prevents any number of &ldquo;interesting&rdquo; compiler
355 optimizations, for example, the use of <tt>gp</tt> as a scratch
356 location immediately preceding the assignment.
357
358 <table>
359 <tr><th>&nbsp;</th></tr>
360 <tr><th align="left">Quick Quiz:</th></tr>
361 <tr><td>
362 But <tt>rcu_assign_pointer()</tt> does nothing to prevent the
363 two assignments to <tt>p-&gt;a</tt> and <tt>p-&gt;b</tt>
364 from being reordered.
365 Can't that also cause problems?
366 </td></tr>
367 <tr><th align="left">Answer:</th></tr>
368 <tr><td bgcolor="#ffffff"><font color="ffffff">
369 No, it cannot.
370 The readers cannot see either of these two fields until
371 the assignment to <tt>gp</tt>, by which time both fields are
372 fully initialized.
373 So reordering the assignments
374 to <tt>p-&gt;a</tt> and <tt>p-&gt;b</tt> cannot possibly
375 cause any problems.
376 </font></td></tr>
377 <tr><td>&nbsp;</td></tr>
378 </table>
379
380 <p>
381 It is tempting to assume that the reader need not do anything special
382 to control its accesses to the RCU-protected data,
383 as shown in <tt>do_something_gp_buggy()</tt> below:
384
385 <blockquote>
386 <pre>
387 1 bool do_something_gp_buggy(void)
388 2 {
389 3 rcu_read_lock();
390 4 p = gp; /* OPTIMIZATIONS GALORE!!! */
391 5 if (p) {
392 6 do_something(p-&gt;a, p-&gt;b);
393 7 rcu_read_unlock();
394 8 return true;
395 9 }
396 10 rcu_read_unlock();
397 11 return false;
398 12 }
399 </pre>
400 </blockquote>
401
402 <p>
403 However, this temptation must be resisted because there are a
404 surprisingly large number of ways that the compiler
405 (to say nothing of
406 <a href="https://h71000.www7.hp.com/wizard/wiz_2637.html">DEC Alpha CPUs</a>)
407 can trip this code up.
408 For but one example, if the compiler were short of registers, it
409 might choose to refetch from <tt>gp</tt> rather than keeping
410 a separate copy in <tt>p</tt> as follows:
411
412 <blockquote>
413 <pre>
414 1 bool do_something_gp_buggy_optimized(void)
415 2 {
416 3 rcu_read_lock();
417 4 if (gp) { /* OPTIMIZATIONS GALORE!!! */
418 <b> 5 do_something(gp-&gt;a, gp-&gt;b);</b>
419 6 rcu_read_unlock();
420 7 return true;
421 8 }
422 9 rcu_read_unlock();
423 10 return false;
424 11 }
425 </pre>
426 </blockquote>
427
428 <p>
429 If this function ran concurrently with a series of updates that
430 replaced the current structure with a new one,
431 the fetches of <tt>gp-&gt;a</tt>
432 and <tt>gp-&gt;b</tt> might well come from two different structures,
433 which could cause serious confusion.
434 To prevent this (and much else besides), <tt>do_something_gp()</tt> uses
435 <tt>rcu_dereference()</tt> to fetch from <tt>gp</tt>:
436
437 <blockquote>
438 <pre>
439 1 bool do_something_gp(void)
440 2 {
441 3 rcu_read_lock();
442 4 p = rcu_dereference(gp);
443 5 if (p) {
444 6 do_something(p-&gt;a, p-&gt;b);
445 7 rcu_read_unlock();
446 8 return true;
447 9 }
448 10 rcu_read_unlock();
449 11 return false;
450 12 }
451 </pre>
452 </blockquote>
453
454 <p>
455 The <tt>rcu_dereference()</tt> uses volatile casts and (for DEC Alpha)
456 memory barriers in the Linux kernel.
457 Should a
458 <a href="http://www.rdrop.com/users/paulmck/RCU/consume.2015.07.13a.pdf">high-quality implementation of C11 <tt>memory_order_consume</tt> [PDF]</a>
459 ever appear, then <tt>rcu_dereference()</tt> could be implemented
460 as a <tt>memory_order_consume</tt> load.
461 Regardless of the exact implementation, a pointer fetched by
462 <tt>rcu_dereference()</tt> may not be used outside of the
463 outermost RCU read-side critical section containing that
464 <tt>rcu_dereference()</tt>, unless protection of
465 the corresponding data element has been passed from RCU to some
466 other synchronization mechanism, most commonly locking or
467 <a href="https://www.kernel.org/doc/Documentation/RCU/rcuref.txt">reference counting</a>.
468
469 <p>
470 In short, updaters use <tt>rcu_assign_pointer()</tt> and readers
471 use <tt>rcu_dereference()</tt>, and these two RCU API elements
472 work together to ensure that readers have a consistent view of
473 newly added data elements.
474
475 <p>
476 Of course, it is also necessary to remove elements from RCU-protected
477 data structures, for example, using the following process:
478
479 <ol>
480 <li> Remove the data element from the enclosing structure.
481 <li> Wait for all pre-existing RCU read-side critical sections
482 to complete (because only pre-existing readers can possibly have
483 a reference to the newly removed data element).
484 <li> At this point, only the updater has a reference to the
485 newly removed data element, so it can safely reclaim
486 the data element, for example, by passing it to <tt>kfree()</tt>.
487 </ol>
488
489 This process is implemented by <tt>remove_gp_synchronous()</tt>:
490
491 <blockquote>
492 <pre>
493 1 bool remove_gp_synchronous(void)
494 2 {
495 3 struct foo *p;
496 4
497 5 spin_lock(&amp;gp_lock);
498 6 p = rcu_access_pointer(gp);
499 7 if (!p) {
500 8 spin_unlock(&amp;gp_lock);
501 9 return false;
502 10 }
503 11 rcu_assign_pointer(gp, NULL);
504 12 spin_unlock(&amp;gp_lock);
505 13 synchronize_rcu();
506 14 kfree(p);
507 15 return true;
508 16 }
509 </pre>
510 </blockquote>
511
512 <p>
513 This function is straightforward, with line&nbsp;13 waiting for a grace
514 period before line&nbsp;14 frees the old data element.
515 This waiting ensures that readers will reach line&nbsp;7 of
516 <tt>do_something_gp()</tt> before the data element referenced by
517 <tt>p</tt> is freed.
518 The <tt>rcu_access_pointer()</tt> on line&nbsp;6 is similar to
519 <tt>rcu_dereference()</tt>, except that:
520
521 <ol>
522 <li> The value returned by <tt>rcu_access_pointer()</tt>
523 cannot be dereferenced.
524 If you want to access the value pointed to as well as
525 the pointer itself, use <tt>rcu_dereference()</tt>
526 instead of <tt>rcu_access_pointer()</tt>.
527 <li> The call to <tt>rcu_access_pointer()</tt> need not be
528 protected.
529 In contrast, <tt>rcu_dereference()</tt> must either be
530 within an RCU read-side critical section or in a code
531 segment where the pointer cannot change, for example, in
532 code protected by the corresponding update-side lock.
533 </ol>
534
535 <table>
536 <tr><th>&nbsp;</th></tr>
537 <tr><th align="left">Quick Quiz:</th></tr>
538 <tr><td>
539 Without the <tt>rcu_dereference()</tt> or the
540 <tt>rcu_access_pointer()</tt>, what destructive optimizations
541 might the compiler make use of?
542 </td></tr>
543 <tr><th align="left">Answer:</th></tr>
544 <tr><td bgcolor="#ffffff"><font color="ffffff">
545 Let's start with what happens to <tt>do_something_gp()</tt>
546 if it fails to use <tt>rcu_dereference()</tt>.
547 It could reuse a value formerly fetched from this same pointer.
548 It could also fetch the pointer from <tt>gp</tt> in a byte-at-a-time
549 manner, resulting in <i>load tearing</i>, in turn resulting a bytewise
550 mash-up of two distince pointer values.
551 It might even use value-speculation optimizations, where it makes
552 a wrong guess, but by the time it gets around to checking the
553 value, an update has changed the pointer to match the wrong guess.
554 Too bad about any dereferences that returned pre-initialization garbage
555 in the meantime!
556 </font>
557
558 <p><font color="ffffff">
559 For <tt>remove_gp_synchronous()</tt>, as long as all modifications
560 to <tt>gp</tt> are carried out while holding <tt>gp_lock</tt>,
561 the above optimizations are harmless.
562 However,
563 with <tt>CONFIG_SPARSE_RCU_POINTER=y</tt>,
564 <tt>sparse</tt> will complain if you
565 define <tt>gp</tt> with <tt>__rcu</tt> and then
566 access it without using
567 either <tt>rcu_access_pointer()</tt> or <tt>rcu_dereference()</tt>.
568 </font></td></tr>
569 <tr><td>&nbsp;</td></tr>
570 </table>
571
572 <p>
573 In short, RCU's publish-subscribe guarantee is provided by the combination
574 of <tt>rcu_assign_pointer()</tt> and <tt>rcu_dereference()</tt>.
575 This guarantee allows data elements to be safely added to RCU-protected
576 linked data structures without disrupting RCU readers.
577 This guarantee can be used in combination with the grace-period
578 guarantee to also allow data elements to be removed from RCU-protected
579 linked data structures, again without disrupting RCU readers.
580
581 <p>
582 This guarantee was only partially premeditated.
583 DYNIX/ptx used an explicit memory barrier for publication, but had nothing
584 resembling <tt>rcu_dereference()</tt> for subscription, nor did it
585 have anything resembling the <tt>smp_read_barrier_depends()</tt>
586 that was later subsumed into <tt>rcu_dereference()</tt>.
587 The need for these operations made itself known quite suddenly at a
588 late-1990s meeting with the DEC Alpha architects, back in the days when
589 DEC was still a free-standing company.
590 It took the Alpha architects a good hour to convince me that any sort
591 of barrier would ever be needed, and it then took me a good <i>two</i> hours
592 to convince them that their documentation did not make this point clear.
593 More recent work with the C and C++ standards committees have provided
594 much education on tricks and traps from the compiler.
595 In short, compilers were much less tricky in the early 1990s, but in
596 2015, don't even think about omitting <tt>rcu_dereference()</tt>!
597
598 <h3><a name="Memory-Barrier Guarantees">Memory-Barrier Guarantees</a></h3>
599
600 <p>
601 The previous section's simple linked-data-structure scenario clearly
602 demonstrates the need for RCU's stringent memory-ordering guarantees on
603 systems with more than one CPU:
604
605 <ol>
606 <li> Each CPU that has an RCU read-side critical section that
607 begins before <tt>synchronize_rcu()</tt> starts is
608 guaranteed to execute a full memory barrier between the time
609 that the RCU read-side critical section ends and the time that
610 <tt>synchronize_rcu()</tt> returns.
611 Without this guarantee, a pre-existing RCU read-side critical section
612 might hold a reference to the newly removed <tt>struct foo</tt>
613 after the <tt>kfree()</tt> on line&nbsp;14 of
614 <tt>remove_gp_synchronous()</tt>.
615 <li> Each CPU that has an RCU read-side critical section that ends
616 after <tt>synchronize_rcu()</tt> returns is guaranteed
617 to execute a full memory barrier between the time that
618 <tt>synchronize_rcu()</tt> begins and the time that the RCU
619 read-side critical section begins.
620 Without this guarantee, a later RCU read-side critical section
621 running after the <tt>kfree()</tt> on line&nbsp;14 of
622 <tt>remove_gp_synchronous()</tt> might
623 later run <tt>do_something_gp()</tt> and find the
624 newly deleted <tt>struct foo</tt>.
625 <li> If the task invoking <tt>synchronize_rcu()</tt> remains
626 on a given CPU, then that CPU is guaranteed to execute a full
627 memory barrier sometime during the execution of
628 <tt>synchronize_rcu()</tt>.
629 This guarantee ensures that the <tt>kfree()</tt> on
630 line&nbsp;14 of <tt>remove_gp_synchronous()</tt> really does
631 execute after the removal on line&nbsp;11.
632 <li> If the task invoking <tt>synchronize_rcu()</tt> migrates
633 among a group of CPUs during that invocation, then each of the
634 CPUs in that group is guaranteed to execute a full memory barrier
635 sometime during the execution of <tt>synchronize_rcu()</tt>.
636 This guarantee also ensures that the <tt>kfree()</tt> on
637 line&nbsp;14 of <tt>remove_gp_synchronous()</tt> really does
638 execute after the removal on
639 line&nbsp;11, but also in the case where the thread executing the
640 <tt>synchronize_rcu()</tt> migrates in the meantime.
641 </ol>
642
643 <table>
644 <tr><th>&nbsp;</th></tr>
645 <tr><th align="left">Quick Quiz:</th></tr>
646 <tr><td>
647 Given that multiple CPUs can start RCU read-side critical sections
648 at any time without any ordering whatsoever, how can RCU possibly
649 tell whether or not a given RCU read-side critical section starts
650 before a given instance of <tt>synchronize_rcu()</tt>?
651 </td></tr>
652 <tr><th align="left">Answer:</th></tr>
653 <tr><td bgcolor="#ffffff"><font color="ffffff">
654 If RCU cannot tell whether or not a given
655 RCU read-side critical section starts before a
656 given instance of <tt>synchronize_rcu()</tt>,
657 then it must assume that the RCU read-side critical section
658 started first.
659 In other words, a given instance of <tt>synchronize_rcu()</tt>
660 can avoid waiting on a given RCU read-side critical section only
661 if it can prove that <tt>synchronize_rcu()</tt> started first.
662 </font></td></tr>
663 <tr><td>&nbsp;</td></tr>
664 </table>
665
666 <table>
667 <tr><th>&nbsp;</th></tr>
668 <tr><th align="left">Quick Quiz:</th></tr>
669 <tr><td>
670 The first and second guarantees require unbelievably strict ordering!
671 Are all these memory barriers <i> really</i> required?
672 </td></tr>
673 <tr><th align="left">Answer:</th></tr>
674 <tr><td bgcolor="#ffffff"><font color="ffffff">
675 Yes, they really are required.
676 To see why the first guarantee is required, consider the following
677 sequence of events:
678 </font>
679
680 <ol>
681 <li> <font color="ffffff">
682 CPU 1: <tt>rcu_read_lock()</tt>
683 </font>
684 <li> <font color="ffffff">
685 CPU 1: <tt>q = rcu_dereference(gp);
686 /* Very likely to return p. */</tt>
687 </font>
688 <li> <font color="ffffff">
689 CPU 0: <tt>list_del_rcu(p);</tt>
690 </font>
691 <li> <font color="ffffff">
692 CPU 0: <tt>synchronize_rcu()</tt> starts.
693 </font>
694 <li> <font color="ffffff">
695 CPU 1: <tt>do_something_with(q-&gt;a);
696 /* No smp_mb(), so might happen after kfree(). */</tt>
697 </font>
698 <li> <font color="ffffff">
699 CPU 1: <tt>rcu_read_unlock()</tt>
700 </font>
701 <li> <font color="ffffff">
702 CPU 0: <tt>synchronize_rcu()</tt> returns.
703 </font>
704 <li> <font color="ffffff">
705 CPU 0: <tt>kfree(p);</tt>
706 </font>
707 </ol>
708
709 <p><font color="ffffff">
710 Therefore, there absolutely must be a full memory barrier between the
711 end of the RCU read-side critical section and the end of the
712 grace period.
713 </font>
714
715 <p><font color="ffffff">
716 The sequence of events demonstrating the necessity of the second rule
717 is roughly similar:
718 </font>
719
720 <ol>
721 <li> <font color="ffffff">CPU 0: <tt>list_del_rcu(p);</tt>
722 </font>
723 <li> <font color="ffffff">CPU 0: <tt>synchronize_rcu()</tt> starts.
724 </font>
725 <li> <font color="ffffff">CPU 1: <tt>rcu_read_lock()</tt>
726 </font>
727 <li> <font color="ffffff">CPU 1: <tt>q = rcu_dereference(gp);
728 /* Might return p if no memory barrier. */</tt>
729 </font>
730 <li> <font color="ffffff">CPU 0: <tt>synchronize_rcu()</tt> returns.
731 </font>
732 <li> <font color="ffffff">CPU 0: <tt>kfree(p);</tt>
733 </font>
734 <li> <font color="ffffff">
735 CPU 1: <tt>do_something_with(q-&gt;a); /* Boom!!! */</tt>
736 </font>
737 <li> <font color="ffffff">CPU 1: <tt>rcu_read_unlock()</tt>
738 </font>
739 </ol>
740
741 <p><font color="ffffff">
742 And similarly, without a memory barrier between the beginning of the
743 grace period and the beginning of the RCU read-side critical section,
744 CPU&nbsp;1 might end up accessing the freelist.
745 </font>
746
747 <p><font color="ffffff">
748 The &ldquo;as if&rdquo; rule of course applies, so that any
749 implementation that acts as if the appropriate memory barriers
750 were in place is a correct implementation.
751 That said, it is much easier to fool yourself into believing
752 that you have adhered to the as-if rule than it is to actually
753 adhere to it!
754 </font></td></tr>
755 <tr><td>&nbsp;</td></tr>
756 </table>
757
758 <table>
759 <tr><th>&nbsp;</th></tr>
760 <tr><th align="left">Quick Quiz:</th></tr>
761 <tr><td>
762 You claim that <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>
763 generate absolutely no code in some kernel builds.
764 This means that the compiler might arbitrarily rearrange consecutive
765 RCU read-side critical sections.
766 Given such rearrangement, if a given RCU read-side critical section
767 is done, how can you be sure that all prior RCU read-side critical
768 sections are done?
769 Won't the compiler rearrangements make that impossible to determine?
770 </td></tr>
771 <tr><th align="left">Answer:</th></tr>
772 <tr><td bgcolor="#ffffff"><font color="ffffff">
773 In cases where <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>
774 generate absolutely no code, RCU infers quiescent states only at
775 special locations, for example, within the scheduler.
776 Because calls to <tt>schedule()</tt> had better prevent calling-code
777 accesses to shared variables from being rearranged across the call to
778 <tt>schedule()</tt>, if RCU detects the end of a given RCU read-side
779 critical section, it will necessarily detect the end of all prior
780 RCU read-side critical sections, no matter how aggressively the
781 compiler scrambles the code.
782 </font>
783
784 <p><font color="ffffff">
785 Again, this all assumes that the compiler cannot scramble code across
786 calls to the scheduler, out of interrupt handlers, into the idle loop,
787 into user-mode code, and so on.
788 But if your kernel build allows that sort of scrambling, you have broken
789 far more than just RCU!
790 </font></td></tr>
791 <tr><td>&nbsp;</td></tr>
792 </table>
793
794 <p>
795 Note that these memory-barrier requirements do not replace the fundamental
796 RCU requirement that a grace period wait for all pre-existing readers.
797 On the contrary, the memory barriers called out in this section must operate in
798 such a way as to <i>enforce</i> this fundamental requirement.
799 Of course, different implementations enforce this requirement in different
800 ways, but enforce it they must.
801
802 <h3><a name="RCU Primitives Guaranteed to Execute Unconditionally">RCU Primitives Guaranteed to Execute Unconditionally</a></h3>
803
804 <p>
805 The common-case RCU primitives are unconditional.
806 They are invoked, they do their job, and they return, with no possibility
807 of error, and no need to retry.
808 This is a key RCU design philosophy.
809
810 <p>
811 However, this philosophy is pragmatic rather than pigheaded.
812 If someone comes up with a good justification for a particular conditional
813 RCU primitive, it might well be implemented and added.
814 After all, this guarantee was reverse-engineered, not premeditated.
815 The unconditional nature of the RCU primitives was initially an
816 accident of implementation, and later experience with synchronization
817 primitives with conditional primitives caused me to elevate this
818 accident to a guarantee.
819 Therefore, the justification for adding a conditional primitive to
820 RCU would need to be based on detailed and compelling use cases.
821
822 <h3><a name="Guaranteed Read-to-Write Upgrade">Guaranteed Read-to-Write Upgrade</a></h3>
823
824 <p>
825 As far as RCU is concerned, it is always possible to carry out an
826 update within an RCU read-side critical section.
827 For example, that RCU read-side critical section might search for
828 a given data element, and then might acquire the update-side
829 spinlock in order to update that element, all while remaining
830 in that RCU read-side critical section.
831 Of course, it is necessary to exit the RCU read-side critical section
832 before invoking <tt>synchronize_rcu()</tt>, however, this
833 inconvenience can be avoided through use of the
834 <tt>call_rcu()</tt> and <tt>kfree_rcu()</tt> API members
835 described later in this document.
836
837 <table>
838 <tr><th>&nbsp;</th></tr>
839 <tr><th align="left">Quick Quiz:</th></tr>
840 <tr><td>
841 But how does the upgrade-to-write operation exclude other readers?
842 </td></tr>
843 <tr><th align="left">Answer:</th></tr>
844 <tr><td bgcolor="#ffffff"><font color="ffffff">
845 It doesn't, just like normal RCU updates, which also do not exclude
846 RCU readers.
847 </font></td></tr>
848 <tr><td>&nbsp;</td></tr>
849 </table>
850
851 <p>
852 This guarantee allows lookup code to be shared between read-side
853 and update-side code, and was premeditated, appearing in the earliest
854 DYNIX/ptx RCU documentation.
855
856 <h2><a name="Fundamental Non-Requirements">Fundamental Non-Requirements</a></h2>
857
858 <p>
859 RCU provides extremely lightweight readers, and its read-side guarantees,
860 though quite useful, are correspondingly lightweight.
861 It is therefore all too easy to assume that RCU is guaranteeing more
862 than it really is.
863 Of course, the list of things that RCU does not guarantee is infinitely
864 long, however, the following sections list a few non-guarantees that
865 have caused confusion.
866 Except where otherwise noted, these non-guarantees were premeditated.
867
868 <ol>
869 <li> <a href="#Readers Impose Minimal Ordering">
870 Readers Impose Minimal Ordering</a>
871 <li> <a href="#Readers Do Not Exclude Updaters">
872 Readers Do Not Exclude Updaters</a>
873 <li> <a href="#Updaters Only Wait For Old Readers">
874 Updaters Only Wait For Old Readers</a>
875 <li> <a href="#Grace Periods Don't Partition Read-Side Critical Sections">
876 Grace Periods Don't Partition Read-Side Critical Sections</a>
877 <li> <a href="#Read-Side Critical Sections Don't Partition Grace Periods">
878 Read-Side Critical Sections Don't Partition Grace Periods</a>
879 <li> <a href="#Disabling Preemption Does Not Block Grace Periods">
880 Disabling Preemption Does Not Block Grace Periods</a>
881 </ol>
882
883 <h3><a name="Readers Impose Minimal Ordering">Readers Impose Minimal Ordering</a></h3>
884
885 <p>
886 Reader-side markers such as <tt>rcu_read_lock()</tt> and
887 <tt>rcu_read_unlock()</tt> provide absolutely no ordering guarantees
888 except through their interaction with the grace-period APIs such as
889 <tt>synchronize_rcu()</tt>.
890 To see this, consider the following pair of threads:
891
892 <blockquote>
893 <pre>
894 1 void thread0(void)
895 2 {
896 3 rcu_read_lock();
897 4 WRITE_ONCE(x, 1);
898 5 rcu_read_unlock();
899 6 rcu_read_lock();
900 7 WRITE_ONCE(y, 1);
901 8 rcu_read_unlock();
902 9 }
903 10
904 11 void thread1(void)
905 12 {
906 13 rcu_read_lock();
907 14 r1 = READ_ONCE(y);
908 15 rcu_read_unlock();
909 16 rcu_read_lock();
910 17 r2 = READ_ONCE(x);
911 18 rcu_read_unlock();
912 19 }
913 </pre>
914 </blockquote>
915
916 <p>
917 After <tt>thread0()</tt> and <tt>thread1()</tt> execute
918 concurrently, it is quite possible to have
919
920 <blockquote>
921 <pre>
922 (r1 == 1 &amp;&amp; r2 == 0)
923 </pre>
924 </blockquote>
925
926 (that is, <tt>y</tt> appears to have been assigned before <tt>x</tt>),
927 which would not be possible if <tt>rcu_read_lock()</tt> and
928 <tt>rcu_read_unlock()</tt> had much in the way of ordering
929 properties.
930 But they do not, so the CPU is within its rights
931 to do significant reordering.
932 This is by design: Any significant ordering constraints would slow down
933 these fast-path APIs.
934
935 <table>
936 <tr><th>&nbsp;</th></tr>
937 <tr><th align="left">Quick Quiz:</th></tr>
938 <tr><td>
939 Can't the compiler also reorder this code?
940 </td></tr>
941 <tr><th align="left">Answer:</th></tr>
942 <tr><td bgcolor="#ffffff"><font color="ffffff">
943 No, the volatile casts in <tt>READ_ONCE()</tt> and
944 <tt>WRITE_ONCE()</tt> prevent the compiler from reordering in
945 this particular case.
946 </font></td></tr>
947 <tr><td>&nbsp;</td></tr>
948 </table>
949
950 <h3><a name="Readers Do Not Exclude Updaters">Readers Do Not Exclude Updaters</a></h3>
951
952 <p>
953 Neither <tt>rcu_read_lock()</tt> nor <tt>rcu_read_unlock()</tt>
954 exclude updates.
955 All they do is to prevent grace periods from ending.
956 The following example illustrates this:
957
958 <blockquote>
959 <pre>
960 1 void thread0(void)
961 2 {
962 3 rcu_read_lock();
963 4 r1 = READ_ONCE(y);
964 5 if (r1) {
965 6 do_something_with_nonzero_x();
966 7 r2 = READ_ONCE(x);
967 8 WARN_ON(!r2); /* BUG!!! */
968 9 }
969 10 rcu_read_unlock();
970 11 }
971 12
972 13 void thread1(void)
973 14 {
974 15 spin_lock(&amp;my_lock);
975 16 WRITE_ONCE(x, 1);
976 17 WRITE_ONCE(y, 1);
977 18 spin_unlock(&amp;my_lock);
978 19 }
979 </pre>
980 </blockquote>
981
982 <p>
983 If the <tt>thread0()</tt> function's <tt>rcu_read_lock()</tt>
984 excluded the <tt>thread1()</tt> function's update,
985 the <tt>WARN_ON()</tt> could never fire.
986 But the fact is that <tt>rcu_read_lock()</tt> does not exclude
987 much of anything aside from subsequent grace periods, of which
988 <tt>thread1()</tt> has none, so the
989 <tt>WARN_ON()</tt> can and does fire.
990
991 <h3><a name="Updaters Only Wait For Old Readers">Updaters Only Wait For Old Readers</a></h3>
992
993 <p>
994 It might be tempting to assume that after <tt>synchronize_rcu()</tt>
995 completes, there are no readers executing.
996 This temptation must be avoided because
997 new readers can start immediately after <tt>synchronize_rcu()</tt>
998 starts, and <tt>synchronize_rcu()</tt> is under no
999 obligation to wait for these new readers.
1000
1001 <table>
1002 <tr><th>&nbsp;</th></tr>
1003 <tr><th align="left">Quick Quiz:</th></tr>
1004 <tr><td>
1005 Suppose that synchronize_rcu() did wait until all readers had completed.
1006 Would the updater be able to rely on this?
1007 </td></tr>
1008 <tr><th align="left">Answer:</th></tr>
1009 <tr><td bgcolor="#ffffff"><font color="ffffff">
1010 No.
1011 Even if <tt>synchronize_rcu()</tt> were to wait until
1012 all readers had completed, a new reader might start immediately after
1013 <tt>synchronize_rcu()</tt> completed.
1014 Therefore, the code following
1015 <tt>synchronize_rcu()</tt> cannot rely on there being no readers
1016 in any case.
1017 </font></td></tr>
1018 <tr><td>&nbsp;</td></tr>
1019 </table>
1020
1021 <h3><a name="Grace Periods Don't Partition Read-Side Critical Sections">
1022 Grace Periods Don't Partition Read-Side Critical Sections</a></h3>
1023
1024 <p>
1025 It is tempting to assume that if any part of one RCU read-side critical
1026 section precedes a given grace period, and if any part of another RCU
1027 read-side critical section follows that same grace period, then all of
1028 the first RCU read-side critical section must precede all of the second.
1029 However, this just isn't the case: A single grace period does not
1030 partition the set of RCU read-side critical sections.
1031 An example of this situation can be illustrated as follows, where
1032 <tt>x</tt>, <tt>y</tt>, and <tt>z</tt> are initially all zero:
1033
1034 <blockquote>
1035 <pre>
1036 1 void thread0(void)
1037 2 {
1038 3 rcu_read_lock();
1039 4 WRITE_ONCE(a, 1);
1040 5 WRITE_ONCE(b, 1);
1041 6 rcu_read_unlock();
1042 7 }
1043 8
1044 9 void thread1(void)
1045 10 {
1046 11 r1 = READ_ONCE(a);
1047 12 synchronize_rcu();
1048 13 WRITE_ONCE(c, 1);
1049 14 }
1050 15
1051 16 void thread2(void)
1052 17 {
1053 18 rcu_read_lock();
1054 19 r2 = READ_ONCE(b);
1055 20 r3 = READ_ONCE(c);
1056 21 rcu_read_unlock();
1057 22 }
1058 </pre>
1059 </blockquote>
1060
1061 <p>
1062 It turns out that the outcome:
1063
1064 <blockquote>
1065 <pre>
1066 (r1 == 1 &amp;&amp; r2 == 0 &amp;&amp; r3 == 1)
1067 </pre>
1068 </blockquote>
1069
1070 is entirely possible.
1071 The following figure show how this can happen, with each circled
1072 <tt>QS</tt> indicating the point at which RCU recorded a
1073 <i>quiescent state</i> for each thread, that is, a state in which
1074 RCU knows that the thread cannot be in the midst of an RCU read-side
1075 critical section that started before the current grace period:
1076
1077 <p><img src="GPpartitionReaders1.svg" alt="GPpartitionReaders1.svg" width="60%"></p>
1078
1079 <p>
1080 If it is necessary to partition RCU read-side critical sections in this
1081 manner, it is necessary to use two grace periods, where the first
1082 grace period is known to end before the second grace period starts:
1083
1084 <blockquote>
1085 <pre>
1086 1 void thread0(void)
1087 2 {
1088 3 rcu_read_lock();
1089 4 WRITE_ONCE(a, 1);
1090 5 WRITE_ONCE(b, 1);
1091 6 rcu_read_unlock();
1092 7 }
1093 8
1094 9 void thread1(void)
1095 10 {
1096 11 r1 = READ_ONCE(a);
1097 12 synchronize_rcu();
1098 13 WRITE_ONCE(c, 1);
1099 14 }
1100 15
1101 16 void thread2(void)
1102 17 {
1103 18 r2 = READ_ONCE(c);
1104 19 synchronize_rcu();
1105 20 WRITE_ONCE(d, 1);
1106 21 }
1107 22
1108 23 void thread3(void)
1109 24 {
1110 25 rcu_read_lock();
1111 26 r3 = READ_ONCE(b);
1112 27 r4 = READ_ONCE(d);
1113 28 rcu_read_unlock();
1114 29 }
1115 </pre>
1116 </blockquote>
1117
1118 <p>
1119 Here, if <tt>(r1 == 1)</tt>, then
1120 <tt>thread0()</tt>'s write to <tt>b</tt> must happen
1121 before the end of <tt>thread1()</tt>'s grace period.
1122 If in addition <tt>(r4 == 1)</tt>, then
1123 <tt>thread3()</tt>'s read from <tt>b</tt> must happen
1124 after the beginning of <tt>thread2()</tt>'s grace period.
1125 If it is also the case that <tt>(r2 == 1)</tt>, then the
1126 end of <tt>thread1()</tt>'s grace period must precede the
1127 beginning of <tt>thread2()</tt>'s grace period.
1128 This mean that the two RCU read-side critical sections cannot overlap,
1129 guaranteeing that <tt>(r3 == 1)</tt>.
1130 As a result, the outcome:
1131
1132 <blockquote>
1133 <pre>
1134 (r1 == 1 &amp;&amp; r2 == 1 &amp;&amp; r3 == 0 &amp;&amp; r4 == 1)
1135 </pre>
1136 </blockquote>
1137
1138 cannot happen.
1139
1140 <p>
1141 This non-requirement was also non-premeditated, but became apparent
1142 when studying RCU's interaction with memory ordering.
1143
1144 <h3><a name="Read-Side Critical Sections Don't Partition Grace Periods">
1145 Read-Side Critical Sections Don't Partition Grace Periods</a></h3>
1146
1147 <p>
1148 It is also tempting to assume that if an RCU read-side critical section
1149 happens between a pair of grace periods, then those grace periods cannot
1150 overlap.
1151 However, this temptation leads nowhere good, as can be illustrated by
1152 the following, with all variables initially zero:
1153
1154 <blockquote>
1155 <pre>
1156 1 void thread0(void)
1157 2 {
1158 3 rcu_read_lock();
1159 4 WRITE_ONCE(a, 1);
1160 5 WRITE_ONCE(b, 1);
1161 6 rcu_read_unlock();
1162 7 }
1163 8
1164 9 void thread1(void)
1165 10 {
1166 11 r1 = READ_ONCE(a);
1167 12 synchronize_rcu();
1168 13 WRITE_ONCE(c, 1);
1169 14 }
1170 15
1171 16 void thread2(void)
1172 17 {
1173 18 rcu_read_lock();
1174 19 WRITE_ONCE(d, 1);
1175 20 r2 = READ_ONCE(c);
1176 21 rcu_read_unlock();
1177 22 }
1178 23
1179 24 void thread3(void)
1180 25 {
1181 26 r3 = READ_ONCE(d);
1182 27 synchronize_rcu();
1183 28 WRITE_ONCE(e, 1);
1184 29 }
1185 30
1186 31 void thread4(void)
1187 32 {
1188 33 rcu_read_lock();
1189 34 r4 = READ_ONCE(b);
1190 35 r5 = READ_ONCE(e);
1191 36 rcu_read_unlock();
1192 37 }
1193 </pre>
1194 </blockquote>
1195
1196 <p>
1197 In this case, the outcome:
1198
1199 <blockquote>
1200 <pre>
1201 (r1 == 1 &amp;&amp; r2 == 1 &amp;&amp; r3 == 1 &amp;&amp; r4 == 0 &amp&amp; r5 == 1)
1202 </pre>
1203 </blockquote>
1204
1205 is entirely possible, as illustrated below:
1206
1207 <p><img src="ReadersPartitionGP1.svg" alt="ReadersPartitionGP1.svg" width="100%"></p>
1208
1209 <p>
1210 Again, an RCU read-side critical section can overlap almost all of a
1211 given grace period, just so long as it does not overlap the entire
1212 grace period.
1213 As a result, an RCU read-side critical section cannot partition a pair
1214 of RCU grace periods.
1215
1216 <table>
1217 <tr><th>&nbsp;</th></tr>
1218 <tr><th align="left">Quick Quiz:</th></tr>
1219 <tr><td>
1220 How long a sequence of grace periods, each separated by an RCU
1221 read-side critical section, would be required to partition the RCU
1222 read-side critical sections at the beginning and end of the chain?
1223 </td></tr>
1224 <tr><th align="left">Answer:</th></tr>
1225 <tr><td bgcolor="#ffffff"><font color="ffffff">
1226 In theory, an infinite number.
1227 In practice, an unknown number that is sensitive to both implementation
1228 details and timing considerations.
1229 Therefore, even in practice, RCU users must abide by the
1230 theoretical rather than the practical answer.
1231 </font></td></tr>
1232 <tr><td>&nbsp;</td></tr>
1233 </table>
1234
1235 <h3><a name="Disabling Preemption Does Not Block Grace Periods">
1236 Disabling Preemption Does Not Block Grace Periods</a></h3>
1237
1238 <p>
1239 There was a time when disabling preemption on any given CPU would block
1240 subsequent grace periods.
1241 However, this was an accident of implementation and is not a requirement.
1242 And in the current Linux-kernel implementation, disabling preemption
1243 on a given CPU in fact does not block grace periods, as Oleg Nesterov
1244 <a href="https://lkml.kernel.org/g/20150614193825.GA19582@redhat.com">demonstrated</a>.
1245
1246 <p>
1247 If you need a preempt-disable region to block grace periods, you need to add
1248 <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>, for example
1249 as follows:
1250
1251 <blockquote>
1252 <pre>
1253 1 preempt_disable();
1254 2 rcu_read_lock();
1255 3 do_something();
1256 4 rcu_read_unlock();
1257 5 preempt_enable();
1258 6
1259 7 /* Spinlocks implicitly disable preemption. */
1260 8 spin_lock(&amp;mylock);
1261 9 rcu_read_lock();
1262 10 do_something();
1263 11 rcu_read_unlock();
1264 12 spin_unlock(&amp;mylock);
1265 </pre>
1266 </blockquote>
1267
1268 <p>
1269 In theory, you could enter the RCU read-side critical section first,
1270 but it is more efficient to keep the entire RCU read-side critical
1271 section contained in the preempt-disable region as shown above.
1272 Of course, RCU read-side critical sections that extend outside of
1273 preempt-disable regions will work correctly, but such critical sections
1274 can be preempted, which forces <tt>rcu_read_unlock()</tt> to do
1275 more work.
1276 And no, this is <i>not</i> an invitation to enclose all of your RCU
1277 read-side critical sections within preempt-disable regions, because
1278 doing so would degrade real-time response.
1279
1280 <p>
1281 This non-requirement appeared with preemptible RCU.
1282 If you need a grace period that waits on non-preemptible code regions, use
1283 <a href="#Sched Flavor">RCU-sched</a>.
1284
1285 <h2><a name="Parallelism Facts of Life">Parallelism Facts of Life</a></h2>
1286
1287 <p>
1288 These parallelism facts of life are by no means specific to RCU, but
1289 the RCU implementation must abide by them.
1290 They therefore bear repeating:
1291
1292 <ol>
1293 <li> Any CPU or task may be delayed at any time,
1294 and any attempts to avoid these delays by disabling
1295 preemption, interrupts, or whatever are completely futile.
1296 This is most obvious in preemptible user-level
1297 environments and in virtualized environments (where
1298 a given guest OS's VCPUs can be preempted at any time by
1299 the underlying hypervisor), but can also happen in bare-metal
1300 environments due to ECC errors, NMIs, and other hardware
1301 events.
1302 Although a delay of more than about 20 seconds can result
1303 in splats, the RCU implementation is obligated to use
1304 algorithms that can tolerate extremely long delays, but where
1305 &ldquo;extremely long&rdquo; is not long enough to allow
1306 wrap-around when incrementing a 64-bit counter.
1307 <li> Both the compiler and the CPU can reorder memory accesses.
1308 Where it matters, RCU must use compiler directives and
1309 memory-barrier instructions to preserve ordering.
1310 <li> Conflicting writes to memory locations in any given cache line
1311 will result in expensive cache misses.
1312 Greater numbers of concurrent writes and more-frequent
1313 concurrent writes will result in more dramatic slowdowns.
1314 RCU is therefore obligated to use algorithms that have
1315 sufficient locality to avoid significant performance and
1316 scalability problems.
1317 <li> As a rough rule of thumb, only one CPU's worth of processing
1318 may be carried out under the protection of any given exclusive
1319 lock.
1320 RCU must therefore use scalable locking designs.
1321 <li> Counters are finite, especially on 32-bit systems.
1322 RCU's use of counters must therefore tolerate counter wrap,
1323 or be designed such that counter wrap would take way more
1324 time than a single system is likely to run.
1325 An uptime of ten years is quite possible, a runtime
1326 of a century much less so.
1327 As an example of the latter, RCU's dyntick-idle nesting counter
1328 allows 54 bits for interrupt nesting level (this counter
1329 is 64 bits even on a 32-bit system).
1330 Overflowing this counter requires 2<sup>54</sup>
1331 half-interrupts on a given CPU without that CPU ever going idle.
1332 If a half-interrupt happened every microsecond, it would take
1333 570 years of runtime to overflow this counter, which is currently
1334 believed to be an acceptably long time.
1335 <li> Linux systems can have thousands of CPUs running a single
1336 Linux kernel in a single shared-memory environment.
1337 RCU must therefore pay close attention to high-end scalability.
1338 </ol>
1339
1340 <p>
1341 This last parallelism fact of life means that RCU must pay special
1342 attention to the preceding facts of life.
1343 The idea that Linux might scale to systems with thousands of CPUs would
1344 have been met with some skepticism in the 1990s, but these requirements
1345 would have otherwise have been unsurprising, even in the early 1990s.
1346
1347 <h2><a name="Quality-of-Implementation Requirements">Quality-of-Implementation Requirements</a></h2>
1348
1349 <p>
1350 These sections list quality-of-implementation requirements.
1351 Although an RCU implementation that ignores these requirements could
1352 still be used, it would likely be subject to limitations that would
1353 make it inappropriate for industrial-strength production use.
1354 Classes of quality-of-implementation requirements are as follows:
1355
1356 <ol>
1357 <li> <a href="#Specialization">Specialization</a>
1358 <li> <a href="#Performance and Scalability">Performance and Scalability</a>
1359 <li> <a href="#Composability">Composability</a>
1360 <li> <a href="#Corner Cases">Corner Cases</a>
1361 </ol>
1362
1363 <p>
1364 These classes is covered in the following sections.
1365
1366 <h3><a name="Specialization">Specialization</a></h3>
1367
1368 <p>
1369 RCU is and always has been intended primarily for read-mostly situations,
1370 which means that RCU's read-side primitives are optimized, often at the
1371 expense of its update-side primitives.
1372 Experience thus far is captured by the following list of situations:
1373
1374 <ol>
1375 <li> Read-mostly data, where stale and inconsistent data is not
1376 a problem: RCU works great!
1377 <li> Read-mostly data, where data must be consistent:
1378 RCU works well.
1379 <li> Read-write data, where data must be consistent:
1380 RCU <i>might</i> work OK.
1381 Or not.
1382 <li> Write-mostly data, where data must be consistent:
1383 RCU is very unlikely to be the right tool for the job,
1384 with the following exceptions, where RCU can provide:
1385 <ol type=a>
1386 <li> Existence guarantees for update-friendly mechanisms.
1387 <li> Wait-free read-side primitives for real-time use.
1388 </ol>
1389 </ol>
1390
1391 <p>
1392 This focus on read-mostly situations means that RCU must interoperate
1393 with other synchronization primitives.
1394 For example, the <tt>add_gp()</tt> and <tt>remove_gp_synchronous()</tt>
1395 examples discussed earlier use RCU to protect readers and locking to
1396 coordinate updaters.
1397 However, the need extends much farther, requiring that a variety of
1398 synchronization primitives be legal within RCU read-side critical sections,
1399 including spinlocks, sequence locks, atomic operations, reference
1400 counters, and memory barriers.
1401
1402 <table>
1403 <tr><th>&nbsp;</th></tr>
1404 <tr><th align="left">Quick Quiz:</th></tr>
1405 <tr><td>
1406 What about sleeping locks?
1407 </td></tr>
1408 <tr><th align="left">Answer:</th></tr>
1409 <tr><td bgcolor="#ffffff"><font color="ffffff">
1410 These are forbidden within Linux-kernel RCU read-side critical
1411 sections because it is not legal to place a quiescent state
1412 (in this case, voluntary context switch) within an RCU read-side
1413 critical section.
1414 However, sleeping locks may be used within userspace RCU read-side
1415 critical sections, and also within Linux-kernel sleepable RCU
1416 <a href="#Sleepable RCU"><font color="ffffff">(SRCU)</font></a>
1417 read-side critical sections.
1418 In addition, the -rt patchset turns spinlocks into a
1419 sleeping locks so that the corresponding critical sections
1420 can be preempted, which also means that these sleeplockified
1421 spinlocks (but not other sleeping locks!) may be acquire within
1422 -rt-Linux-kernel RCU read-side critical sections.
1423 </font>
1424
1425 <p><font color="ffffff">
1426 Note that it <i>is</i> legal for a normal RCU read-side
1427 critical section to conditionally acquire a sleeping locks
1428 (as in <tt>mutex_trylock()</tt>), but only as long as it does
1429 not loop indefinitely attempting to conditionally acquire that
1430 sleeping locks.
1431 The key point is that things like <tt>mutex_trylock()</tt>
1432 either return with the mutex held, or return an error indication if
1433 the mutex was not immediately available.
1434 Either way, <tt>mutex_trylock()</tt> returns immediately without
1435 sleeping.
1436 </font></td></tr>
1437 <tr><td>&nbsp;</td></tr>
1438 </table>
1439
1440 <p>
1441 It often comes as a surprise that many algorithms do not require a
1442 consistent view of data, but many can function in that mode,
1443 with network routing being the poster child.
1444 Internet routing algorithms take significant time to propagate
1445 updates, so that by the time an update arrives at a given system,
1446 that system has been sending network traffic the wrong way for
1447 a considerable length of time.
1448 Having a few threads continue to send traffic the wrong way for a
1449 few more milliseconds is clearly not a problem: In the worst case,
1450 TCP retransmissions will eventually get the data where it needs to go.
1451 In general, when tracking the state of the universe outside of the
1452 computer, some level of inconsistency must be tolerated due to
1453 speed-of-light delays if nothing else.
1454
1455 <p>
1456 Furthermore, uncertainty about external state is inherent in many cases.
1457 For example, a pair of veternarians might use heartbeat to determine
1458 whether or not a given cat was alive.
1459 But how long should they wait after the last heartbeat to decide that
1460 the cat is in fact dead?
1461 Waiting less than 400 milliseconds makes no sense because this would
1462 mean that a relaxed cat would be considered to cycle between death
1463 and life more than 100 times per minute.
1464 Moreover, just as with human beings, a cat's heart might stop for
1465 some period of time, so the exact wait period is a judgment call.
1466 One of our pair of veternarians might wait 30 seconds before pronouncing
1467 the cat dead, while the other might insist on waiting a full minute.
1468 The two veternarians would then disagree on the state of the cat during
1469 the final 30 seconds of the minute following the last heartbeat.
1470
1471 <p>
1472 Interestingly enough, this same situation applies to hardware.
1473 When push comes to shove, how do we tell whether or not some
1474 external server has failed?
1475 We send messages to it periodically, and declare it failed if we
1476 don't receive a response within a given period of time.
1477 Policy decisions can usually tolerate short
1478 periods of inconsistency.
1479 The policy was decided some time ago, and is only now being put into
1480 effect, so a few milliseconds of delay is normally inconsequential.
1481
1482 <p>
1483 However, there are algorithms that absolutely must see consistent data.
1484 For example, the translation between a user-level SystemV semaphore
1485 ID to the corresponding in-kernel data structure is protected by RCU,
1486 but it is absolutely forbidden to update a semaphore that has just been
1487 removed.
1488 In the Linux kernel, this need for consistency is accommodated by acquiring
1489 spinlocks located in the in-kernel data structure from within
1490 the RCU read-side critical section, and this is indicated by the
1491 green box in the figure above.
1492 Many other techniques may be used, and are in fact used within the
1493 Linux kernel.
1494
1495 <p>
1496 In short, RCU is not required to maintain consistency, and other
1497 mechanisms may be used in concert with RCU when consistency is required.
1498 RCU's specialization allows it to do its job extremely well, and its
1499 ability to interoperate with other synchronization mechanisms allows
1500 the right mix of synchronization tools to be used for a given job.
1501
1502 <h3><a name="Performance and Scalability">Performance and Scalability</a></h3>
1503
1504 <p>
1505 Energy efficiency is a critical component of performance today,
1506 and Linux-kernel RCU implementations must therefore avoid unnecessarily
1507 awakening idle CPUs.
1508 I cannot claim that this requirement was premeditated.
1509 In fact, I learned of it during a telephone conversation in which I
1510 was given &ldquo;frank and open&rdquo; feedback on the importance
1511 of energy efficiency in battery-powered systems and on specific
1512 energy-efficiency shortcomings of the Linux-kernel RCU implementation.
1513 In my experience, the battery-powered embedded community will consider
1514 any unnecessary wakeups to be extremely unfriendly acts.
1515 So much so that mere Linux-kernel-mailing-list posts are
1516 insufficient to vent their ire.
1517
1518 <p>
1519 Memory consumption is not particularly important for in most
1520 situations, and has become decreasingly
1521 so as memory sizes have expanded and memory
1522 costs have plummeted.
1523 However, as I learned from Matt Mackall's
1524 <a href="http://elinux.org/Linux_Tiny-FAQ">bloatwatch</a>
1525 efforts, memory footprint is critically important on single-CPU systems with
1526 non-preemptible (<tt>CONFIG_PREEMPT=n</tt>) kernels, and thus
1527 <a href="https://lkml.kernel.org/g/20090113221724.GA15307@linux.vnet.ibm.com">tiny RCU</a>
1528 was born.
1529 Josh Triplett has since taken over the small-memory banner with his
1530 <a href="https://tiny.wiki.kernel.org/">Linux kernel tinification</a>
1531 project, which resulted in
1532 <a href="#Sleepable RCU">SRCU</a>
1533 becoming optional for those kernels not needing it.
1534
1535 <p>
1536 The remaining performance requirements are, for the most part,
1537 unsurprising.
1538 For example, in keeping with RCU's read-side specialization,
1539 <tt>rcu_dereference()</tt> should have negligible overhead (for
1540 example, suppression of a few minor compiler optimizations).
1541 Similarly, in non-preemptible environments, <tt>rcu_read_lock()</tt> and
1542 <tt>rcu_read_unlock()</tt> should have exactly zero overhead.
1543
1544 <p>
1545 In preemptible environments, in the case where the RCU read-side
1546 critical section was not preempted (as will be the case for the
1547 highest-priority real-time process), <tt>rcu_read_lock()</tt> and
1548 <tt>rcu_read_unlock()</tt> should have minimal overhead.
1549 In particular, they should not contain atomic read-modify-write
1550 operations, memory-barrier instructions, preemption disabling,
1551 interrupt disabling, or backwards branches.
1552 However, in the case where the RCU read-side critical section was preempted,
1553 <tt>rcu_read_unlock()</tt> may acquire spinlocks and disable interrupts.
1554 This is why it is better to nest an RCU read-side critical section
1555 within a preempt-disable region than vice versa, at least in cases
1556 where that critical section is short enough to avoid unduly degrading
1557 real-time latencies.
1558
1559 <p>
1560 The <tt>synchronize_rcu()</tt> grace-period-wait primitive is
1561 optimized for throughput.
1562 It may therefore incur several milliseconds of latency in addition to
1563 the duration of the longest RCU read-side critical section.
1564 On the other hand, multiple concurrent invocations of
1565 <tt>synchronize_rcu()</tt> are required to use batching optimizations
1566 so that they can be satisfied by a single underlying grace-period-wait
1567 operation.
1568 For example, in the Linux kernel, it is not unusual for a single
1569 grace-period-wait operation to serve more than
1570 <a href="https://www.usenix.org/conference/2004-usenix-annual-technical-conference/making-rcu-safe-deep-sub-millisecond-response">1,000 separate invocations</a>
1571 of <tt>synchronize_rcu()</tt>, thus amortizing the per-invocation
1572 overhead down to nearly zero.
1573 However, the grace-period optimization is also required to avoid
1574 measurable degradation of real-time scheduling and interrupt latencies.
1575
1576 <p>
1577 In some cases, the multi-millisecond <tt>synchronize_rcu()</tt>
1578 latencies are unacceptable.
1579 In these cases, <tt>synchronize_rcu_expedited()</tt> may be used
1580 instead, reducing the grace-period latency down to a few tens of
1581 microseconds on small systems, at least in cases where the RCU read-side
1582 critical sections are short.
1583 There are currently no special latency requirements for
1584 <tt>synchronize_rcu_expedited()</tt> on large systems, but,
1585 consistent with the empirical nature of the RCU specification,
1586 that is subject to change.
1587 However, there most definitely are scalability requirements:
1588 A storm of <tt>synchronize_rcu_expedited()</tt> invocations on 4096
1589 CPUs should at least make reasonable forward progress.
1590 In return for its shorter latencies, <tt>synchronize_rcu_expedited()</tt>
1591 is permitted to impose modest degradation of real-time latency
1592 on non-idle online CPUs.
1593 That said, it will likely be necessary to take further steps to reduce this
1594 degradation, hopefully to roughly that of a scheduling-clock interrupt.
1595
1596 <p>
1597 There are a number of situations where even
1598 <tt>synchronize_rcu_expedited()</tt>'s reduced grace-period
1599 latency is unacceptable.
1600 In these situations, the asynchronous <tt>call_rcu()</tt> can be
1601 used in place of <tt>synchronize_rcu()</tt> as follows:
1602
1603 <blockquote>
1604 <pre>
1605 1 struct foo {
1606 2 int a;
1607 3 int b;
1608 4 struct rcu_head rh;
1609 5 };
1610 6
1611 7 static void remove_gp_cb(struct rcu_head *rhp)
1612 8 {
1613 9 struct foo *p = container_of(rhp, struct foo, rh);
1614 10
1615 11 kfree(p);
1616 12 }
1617 13
1618 14 bool remove_gp_asynchronous(void)
1619 15 {
1620 16 struct foo *p;
1621 17
1622 18 spin_lock(&amp;gp_lock);
1623 19 p = rcu_dereference(gp);
1624 20 if (!p) {
1625 21 spin_unlock(&amp;gp_lock);
1626 22 return false;
1627 23 }
1628 24 rcu_assign_pointer(gp, NULL);
1629 25 call_rcu(&amp;p-&gt;rh, remove_gp_cb);
1630 26 spin_unlock(&amp;gp_lock);
1631 27 return true;
1632 28 }
1633 </pre>
1634 </blockquote>
1635
1636 <p>
1637 A definition of <tt>struct foo</tt> is finally needed, and appears
1638 on lines&nbsp;1-5.
1639 The function <tt>remove_gp_cb()</tt> is passed to <tt>call_rcu()</tt>
1640 on line&nbsp;25, and will be invoked after the end of a subsequent
1641 grace period.
1642 This gets the same effect as <tt>remove_gp_synchronous()</tt>,
1643 but without forcing the updater to wait for a grace period to elapse.
1644 The <tt>call_rcu()</tt> function may be used in a number of
1645 situations where neither <tt>synchronize_rcu()</tt> nor
1646 <tt>synchronize_rcu_expedited()</tt> would be legal,
1647 including within preempt-disable code, <tt>local_bh_disable()</tt> code,
1648 interrupt-disable code, and interrupt handlers.
1649 However, even <tt>call_rcu()</tt> is illegal within NMI handlers
1650 and from offline CPUs.
1651 The callback function (<tt>remove_gp_cb()</tt> in this case) will be
1652 executed within softirq (software interrupt) environment within the
1653 Linux kernel,
1654 either within a real softirq handler or under the protection
1655 of <tt>local_bh_disable()</tt>.
1656 In both the Linux kernel and in userspace, it is bad practice to
1657 write an RCU callback function that takes too long.
1658 Long-running operations should be relegated to separate threads or
1659 (in the Linux kernel) workqueues.
1660
1661 <table>
1662 <tr><th>&nbsp;</th></tr>
1663 <tr><th align="left">Quick Quiz:</th></tr>
1664 <tr><td>
1665 Why does line&nbsp;19 use <tt>rcu_access_pointer()</tt>?
1666 After all, <tt>call_rcu()</tt> on line&nbsp;25 stores into the
1667 structure, which would interact badly with concurrent insertions.
1668 Doesn't this mean that <tt>rcu_dereference()</tt> is required?
1669 </td></tr>
1670 <tr><th align="left">Answer:</th></tr>
1671 <tr><td bgcolor="#ffffff"><font color="ffffff">
1672 Presumably the <tt>-&gt;gp_lock</tt> acquired on line&nbsp;18 excludes
1673 any changes, including any insertions that <tt>rcu_dereference()</tt>
1674 would protect against.
1675 Therefore, any insertions will be delayed until after
1676 <tt>-&gt;gp_lock</tt>
1677 is released on line&nbsp;25, which in turn means that
1678 <tt>rcu_access_pointer()</tt> suffices.
1679 </font></td></tr>
1680 <tr><td>&nbsp;</td></tr>
1681 </table>
1682
1683 <p>
1684 However, all that <tt>remove_gp_cb()</tt> is doing is
1685 invoking <tt>kfree()</tt> on the data element.
1686 This is a common idiom, and is supported by <tt>kfree_rcu()</tt>,
1687 which allows &ldquo;fire and forget&rdquo; operation as shown below:
1688
1689 <blockquote>
1690 <pre>
1691 1 struct foo {
1692 2 int a;
1693 3 int b;
1694 4 struct rcu_head rh;
1695 5 };
1696 6
1697 7 bool remove_gp_faf(void)
1698 8 {
1699 9 struct foo *p;
1700 10
1701 11 spin_lock(&amp;gp_lock);
1702 12 p = rcu_dereference(gp);
1703 13 if (!p) {
1704 14 spin_unlock(&amp;gp_lock);
1705 15 return false;
1706 16 }
1707 17 rcu_assign_pointer(gp, NULL);
1708 18 kfree_rcu(p, rh);
1709 19 spin_unlock(&amp;gp_lock);
1710 20 return true;
1711 21 }
1712 </pre>
1713 </blockquote>
1714
1715 <p>
1716 Note that <tt>remove_gp_faf()</tt> simply invokes
1717 <tt>kfree_rcu()</tt> and proceeds, without any need to pay any
1718 further attention to the subsequent grace period and <tt>kfree()</tt>.
1719 It is permissible to invoke <tt>kfree_rcu()</tt> from the same
1720 environments as for <tt>call_rcu()</tt>.
1721 Interestingly enough, DYNIX/ptx had the equivalents of
1722 <tt>call_rcu()</tt> and <tt>kfree_rcu()</tt>, but not
1723 <tt>synchronize_rcu()</tt>.
1724 This was due to the fact that RCU was not heavily used within DYNIX/ptx,
1725 so the very few places that needed something like
1726 <tt>synchronize_rcu()</tt> simply open-coded it.
1727
1728 <table>
1729 <tr><th>&nbsp;</th></tr>
1730 <tr><th align="left">Quick Quiz:</th></tr>
1731 <tr><td>
1732 Earlier it was claimed that <tt>call_rcu()</tt> and
1733 <tt>kfree_rcu()</tt> allowed updaters to avoid being blocked
1734 by readers.
1735 But how can that be correct, given that the invocation of the callback
1736 and the freeing of the memory (respectively) must still wait for
1737 a grace period to elapse?
1738 </td></tr>
1739 <tr><th align="left">Answer:</th></tr>
1740 <tr><td bgcolor="#ffffff"><font color="ffffff">
1741 We could define things this way, but keep in mind that this sort of
1742 definition would say that updates in garbage-collected languages
1743 cannot complete until the next time the garbage collector runs,
1744 which does not seem at all reasonable.
1745 The key point is that in most cases, an updater using either
1746 <tt>call_rcu()</tt> or <tt>kfree_rcu()</tt> can proceed to the
1747 next update as soon as it has invoked <tt>call_rcu()</tt> or
1748 <tt>kfree_rcu()</tt>, without having to wait for a subsequent
1749 grace period.
1750 </font></td></tr>
1751 <tr><td>&nbsp;</td></tr>
1752 </table>
1753
1754 <p>
1755 But what if the updater must wait for the completion of code to be
1756 executed after the end of the grace period, but has other tasks
1757 that can be carried out in the meantime?
1758 The polling-style <tt>get_state_synchronize_rcu()</tt> and
1759 <tt>cond_synchronize_rcu()</tt> functions may be used for this
1760 purpose, as shown below:
1761
1762 <blockquote>
1763 <pre>
1764 1 bool remove_gp_poll(void)
1765 2 {
1766 3 struct foo *p;
1767 4 unsigned long s;
1768 5
1769 6 spin_lock(&amp;gp_lock);
1770 7 p = rcu_access_pointer(gp);
1771 8 if (!p) {
1772 9 spin_unlock(&amp;gp_lock);
1773 10 return false;
1774 11 }
1775 12 rcu_assign_pointer(gp, NULL);
1776 13 spin_unlock(&amp;gp_lock);
1777 14 s = get_state_synchronize_rcu();
1778 15 do_something_while_waiting();
1779 16 cond_synchronize_rcu(s);
1780 17 kfree(p);
1781 18 return true;
1782 19 }
1783 </pre>
1784 </blockquote>
1785
1786 <p>
1787 On line&nbsp;14, <tt>get_state_synchronize_rcu()</tt> obtains a
1788 &ldquo;cookie&rdquo; from RCU,
1789 then line&nbsp;15 carries out other tasks,
1790 and finally, line&nbsp;16 returns immediately if a grace period has
1791 elapsed in the meantime, but otherwise waits as required.
1792 The need for <tt>get_state_synchronize_rcu</tt> and
1793 <tt>cond_synchronize_rcu()</tt> has appeared quite recently,
1794 so it is too early to tell whether they will stand the test of time.
1795
1796 <p>
1797 RCU thus provides a range of tools to allow updaters to strike the
1798 required tradeoff between latency, flexibility and CPU overhead.
1799
1800 <h3><a name="Composability">Composability</a></h3>
1801
1802 <p>
1803 Composability has received much attention in recent years, perhaps in part
1804 due to the collision of multicore hardware with object-oriented techniques
1805 designed in single-threaded environments for single-threaded use.
1806 And in theory, RCU read-side critical sections may be composed, and in
1807 fact may be nested arbitrarily deeply.
1808 In practice, as with all real-world implementations of composable
1809 constructs, there are limitations.
1810
1811 <p>
1812 Implementations of RCU for which <tt>rcu_read_lock()</tt>
1813 and <tt>rcu_read_unlock()</tt> generate no code, such as
1814 Linux-kernel RCU when <tt>CONFIG_PREEMPT=n</tt>, can be
1815 nested arbitrarily deeply.
1816 After all, there is no overhead.
1817 Except that if all these instances of <tt>rcu_read_lock()</tt>
1818 and <tt>rcu_read_unlock()</tt> are visible to the compiler,
1819 compilation will eventually fail due to exhausting memory,
1820 mass storage, or user patience, whichever comes first.
1821 If the nesting is not visible to the compiler, as is the case with
1822 mutually recursive functions each in its own translation unit,
1823 stack overflow will result.
1824 If the nesting takes the form of loops, either the control variable
1825 will overflow or (in the Linux kernel) you will get an RCU CPU stall warning.
1826 Nevertheless, this class of RCU implementations is one
1827 of the most composable constructs in existence.
1828
1829 <p>
1830 RCU implementations that explicitly track nesting depth
1831 are limited by the nesting-depth counter.
1832 For example, the Linux kernel's preemptible RCU limits nesting to
1833 <tt>INT_MAX</tt>.
1834 This should suffice for almost all practical purposes.
1835 That said, a consecutive pair of RCU read-side critical sections
1836 between which there is an operation that waits for a grace period
1837 cannot be enclosed in another RCU read-side critical section.
1838 This is because it is not legal to wait for a grace period within
1839 an RCU read-side critical section: To do so would result either
1840 in deadlock or
1841 in RCU implicitly splitting the enclosing RCU read-side critical
1842 section, neither of which is conducive to a long-lived and prosperous
1843 kernel.
1844
1845 <p>
1846 It is worth noting that RCU is not alone in limiting composability.
1847 For example, many transactional-memory implementations prohibit
1848 composing a pair of transactions separated by an irrevocable
1849 operation (for example, a network receive operation).
1850 For another example, lock-based critical sections can be composed
1851 surprisingly freely, but only if deadlock is avoided.
1852
1853 <p>
1854 In short, although RCU read-side critical sections are highly composable,
1855 care is required in some situations, just as is the case for any other
1856 composable synchronization mechanism.
1857
1858 <h3><a name="Corner Cases">Corner Cases</a></h3>
1859
1860 <p>
1861 A given RCU workload might have an endless and intense stream of
1862 RCU read-side critical sections, perhaps even so intense that there
1863 was never a point in time during which there was not at least one
1864 RCU read-side critical section in flight.
1865 RCU cannot allow this situation to block grace periods: As long as
1866 all the RCU read-side critical sections are finite, grace periods
1867 must also be finite.
1868
1869 <p>
1870 That said, preemptible RCU implementations could potentially result
1871 in RCU read-side critical sections being preempted for long durations,
1872 which has the effect of creating a long-duration RCU read-side
1873 critical section.
1874 This situation can arise only in heavily loaded systems, but systems using
1875 real-time priorities are of course more vulnerable.
1876 Therefore, RCU priority boosting is provided to help deal with this
1877 case.
1878 That said, the exact requirements on RCU priority boosting will likely
1879 evolve as more experience accumulates.
1880
1881 <p>
1882 Other workloads might have very high update rates.
1883 Although one can argue that such workloads should instead use
1884 something other than RCU, the fact remains that RCU must
1885 handle such workloads gracefully.
1886 This requirement is another factor driving batching of grace periods,
1887 but it is also the driving force behind the checks for large numbers
1888 of queued RCU callbacks in the <tt>call_rcu()</tt> code path.
1889 Finally, high update rates should not delay RCU read-side critical
1890 sections, although some read-side delays can occur when using
1891 <tt>synchronize_rcu_expedited()</tt>, courtesy of this function's use
1892 of <tt>try_stop_cpus()</tt>.
1893 (In the future, <tt>synchronize_rcu_expedited()</tt> will be
1894 converted to use lighter-weight inter-processor interrupts (IPIs),
1895 but this will still disturb readers, though to a much smaller degree.)
1896
1897 <p>
1898 Although all three of these corner cases were understood in the early
1899 1990s, a simple user-level test consisting of <tt>close(open(path))</tt>
1900 in a tight loop
1901 in the early 2000s suddenly provided a much deeper appreciation of the
1902 high-update-rate corner case.
1903 This test also motivated addition of some RCU code to react to high update
1904 rates, for example, if a given CPU finds itself with more than 10,000
1905 RCU callbacks queued, it will cause RCU to take evasive action by
1906 more aggressively starting grace periods and more aggressively forcing
1907 completion of grace-period processing.
1908 This evasive action causes the grace period to complete more quickly,
1909 but at the cost of restricting RCU's batching optimizations, thus
1910 increasing the CPU overhead incurred by that grace period.
1911
1912 <h2><a name="Software-Engineering Requirements">
1913 Software-Engineering Requirements</a></h2>
1914
1915 <p>
1916 Between Murphy's Law and &ldquo;To err is human&rdquo;, it is necessary to
1917 guard against mishaps and misuse:
1918
1919 <ol>
1920 <li> It is all too easy to forget to use <tt>rcu_read_lock()</tt>
1921 everywhere that it is needed, so kernels built with
1922 <tt>CONFIG_PROVE_RCU=y</tt> will spat if
1923 <tt>rcu_dereference()</tt> is used outside of an
1924 RCU read-side critical section.
1925 Update-side code can use <tt>rcu_dereference_protected()</tt>,
1926 which takes a
1927 <a href="https://lwn.net/Articles/371986/">lockdep expression</a>
1928 to indicate what is providing the protection.
1929 If the indicated protection is not provided, a lockdep splat
1930 is emitted.
1931
1932 <p>
1933 Code shared between readers and updaters can use
1934 <tt>rcu_dereference_check()</tt>, which also takes a
1935 lockdep expression, and emits a lockdep splat if neither
1936 <tt>rcu_read_lock()</tt> nor the indicated protection
1937 is in place.
1938 In addition, <tt>rcu_dereference_raw()</tt> is used in those
1939 (hopefully rare) cases where the required protection cannot
1940 be easily described.
1941 Finally, <tt>rcu_read_lock_held()</tt> is provided to
1942 allow a function to verify that it has been invoked within
1943 an RCU read-side critical section.
1944 I was made aware of this set of requirements shortly after Thomas
1945 Gleixner audited a number of RCU uses.
1946 <li> A given function might wish to check for RCU-related preconditions
1947 upon entry, before using any other RCU API.
1948 The <tt>rcu_lockdep_assert()</tt> does this job,
1949 asserting the expression in kernels having lockdep enabled
1950 and doing nothing otherwise.
1951 <li> It is also easy to forget to use <tt>rcu_assign_pointer()</tt>
1952 and <tt>rcu_dereference()</tt>, perhaps (incorrectly)
1953 substituting a simple assignment.
1954 To catch this sort of error, a given RCU-protected pointer may be
1955 tagged with <tt>__rcu</tt>, after which running sparse
1956 with <tt>CONFIG_SPARSE_RCU_POINTER=y</tt> will complain
1957 about simple-assignment accesses to that pointer.
1958 Arnd Bergmann made me aware of this requirement, and also
1959 supplied the needed
1960 <a href="https://lwn.net/Articles/376011/">patch series</a>.
1961 <li> Kernels built with <tt>CONFIG_DEBUG_OBJECTS_RCU_HEAD=y</tt>
1962 will splat if a data element is passed to <tt>call_rcu()</tt>
1963 twice in a row, without a grace period in between.
1964 (This error is similar to a double free.)
1965 The corresponding <tt>rcu_head</tt> structures that are
1966 dynamically allocated are automatically tracked, but
1967 <tt>rcu_head</tt> structures allocated on the stack
1968 must be initialized with <tt>init_rcu_head_on_stack()</tt>
1969 and cleaned up with <tt>destroy_rcu_head_on_stack()</tt>.
1970 Similarly, statically allocated non-stack <tt>rcu_head</tt>
1971 structures must be initialized with <tt>init_rcu_head()</tt>
1972 and cleaned up with <tt>destroy_rcu_head()</tt>.
1973 Mathieu Desnoyers made me aware of this requirement, and also
1974 supplied the needed
1975 <a href="https://lkml.kernel.org/g/20100319013024.GA28456@Krystal">patch</a>.
1976 <li> An infinite loop in an RCU read-side critical section will
1977 eventually trigger an RCU CPU stall warning splat, with
1978 the duration of &ldquo;eventually&rdquo; being controlled by the
1979 <tt>RCU_CPU_STALL_TIMEOUT</tt> <tt>Kconfig</tt> option, or,
1980 alternatively, by the
1981 <tt>rcupdate.rcu_cpu_stall_timeout</tt> boot/sysfs
1982 parameter.
1983 However, RCU is not obligated to produce this splat
1984 unless there is a grace period waiting on that particular
1985 RCU read-side critical section.
1986 <p>
1987 Some extreme workloads might intentionally delay
1988 RCU grace periods, and systems running those workloads can
1989 be booted with <tt>rcupdate.rcu_cpu_stall_suppress</tt>
1990 to suppress the splats.
1991 This kernel parameter may also be set via <tt>sysfs</tt>.
1992 Furthermore, RCU CPU stall warnings are counter-productive
1993 during sysrq dumps and during panics.
1994 RCU therefore supplies the <tt>rcu_sysrq_start()</tt> and
1995 <tt>rcu_sysrq_end()</tt> API members to be called before
1996 and after long sysrq dumps.
1997 RCU also supplies the <tt>rcu_panic()</tt> notifier that is
1998 automatically invoked at the beginning of a panic to suppress
1999 further RCU CPU stall warnings.
2000
2001 <p>
2002 This requirement made itself known in the early 1990s, pretty
2003 much the first time that it was necessary to debug a CPU stall.
2004 That said, the initial implementation in DYNIX/ptx was quite
2005 generic in comparison with that of Linux.
2006 <li> Although it would be very good to detect pointers leaking out
2007 of RCU read-side critical sections, there is currently no
2008 good way of doing this.
2009 One complication is the need to distinguish between pointers
2010 leaking and pointers that have been handed off from RCU to
2011 some other synchronization mechanism, for example, reference
2012 counting.
2013 <li> In kernels built with <tt>CONFIG_RCU_TRACE=y</tt>, RCU-related
2014 information is provided via both debugfs and event tracing.
2015 <li> Open-coded use of <tt>rcu_assign_pointer()</tt> and
2016 <tt>rcu_dereference()</tt> to create typical linked
2017 data structures can be surprisingly error-prone.
2018 Therefore, RCU-protected
2019 <a href="https://lwn.net/Articles/609973/#RCU List APIs">linked lists</a>
2020 and, more recently, RCU-protected
2021 <a href="https://lwn.net/Articles/612100/">hash tables</a>
2022 are available.
2023 Many other special-purpose RCU-protected data structures are
2024 available in the Linux kernel and the userspace RCU library.
2025 <li> Some linked structures are created at compile time, but still
2026 require <tt>__rcu</tt> checking.
2027 The <tt>RCU_POINTER_INITIALIZER()</tt> macro serves this
2028 purpose.
2029 <li> It is not necessary to use <tt>rcu_assign_pointer()</tt>
2030 when creating linked structures that are to be published via
2031 a single external pointer.
2032 The <tt>RCU_INIT_POINTER()</tt> macro is provided for
2033 this task and also for assigning <tt>NULL</tt> pointers
2034 at runtime.
2035 </ol>
2036
2037 <p>
2038 This not a hard-and-fast list: RCU's diagnostic capabilities will
2039 continue to be guided by the number and type of usage bugs found
2040 in real-world RCU usage.
2041
2042 <h2><a name="Linux Kernel Complications">Linux Kernel Complications</a></h2>
2043
2044 <p>
2045 The Linux kernel provides an interesting environment for all kinds of
2046 software, including RCU.
2047 Some of the relevant points of interest are as follows:
2048
2049 <ol>
2050 <li> <a href="#Configuration">Configuration</a>.
2051 <li> <a href="#Firmware Interface">Firmware Interface</a>.
2052 <li> <a href="#Early Boot">Early Boot</a>.
2053 <li> <a href="#Interrupts and NMIs">
2054 Interrupts and non-maskable interrupts (NMIs)</a>.
2055 <li> <a href="#Loadable Modules">Loadable Modules</a>.
2056 <li> <a href="#Hotplug CPU">Hotplug CPU</a>.
2057 <li> <a href="#Scheduler and RCU">Scheduler and RCU</a>.
2058 <li> <a href="#Tracing and RCU">Tracing and RCU</a>.
2059 <li> <a href="#Energy Efficiency">Energy Efficiency</a>.
2060 <li> <a href="#Memory Efficiency">Memory Efficiency</a>.
2061 <li> <a href="#Performance, Scalability, Response Time, and Reliability">
2062 Performance, Scalability, Response Time, and Reliability</a>.
2063 </ol>
2064
2065 <p>
2066 This list is probably incomplete, but it does give a feel for the
2067 most notable Linux-kernel complications.
2068 Each of the following sections covers one of the above topics.
2069
2070 <h3><a name="Configuration">Configuration</a></h3>
2071
2072 <p>
2073 RCU's goal is automatic configuration, so that almost nobody
2074 needs to worry about RCU's <tt>Kconfig</tt> options.
2075 And for almost all users, RCU does in fact work well
2076 &ldquo;out of the box.&rdquo;
2077
2078 <p>
2079 However, there are specialized use cases that are handled by
2080 kernel boot parameters and <tt>Kconfig</tt> options.
2081 Unfortunately, the <tt>Kconfig</tt> system will explicitly ask users
2082 about new <tt>Kconfig</tt> options, which requires almost all of them
2083 be hidden behind a <tt>CONFIG_RCU_EXPERT</tt> <tt>Kconfig</tt> option.
2084
2085 <p>
2086 This all should be quite obvious, but the fact remains that
2087 Linus Torvalds recently had to
2088 <a href="https://lkml.kernel.org/g/CA+55aFy4wcCwaL4okTs8wXhGZ5h-ibecy_Meg9C4MNQrUnwMcg@mail.gmail.com">remind</a>
2089 me of this requirement.
2090
2091 <h3><a name="Firmware Interface">Firmware Interface</a></h3>
2092
2093 <p>
2094 In many cases, kernel obtains information about the system from the
2095 firmware, and sometimes things are lost in translation.
2096 Or the translation is accurate, but the original message is bogus.
2097
2098 <p>
2099 For example, some systems' firmware overreports the number of CPUs,
2100 sometimes by a large factor.
2101 If RCU naively believed the firmware, as it used to do,
2102 it would create too many per-CPU kthreads.
2103 Although the resulting system will still run correctly, the extra
2104 kthreads needlessly consume memory and can cause confusion
2105 when they show up in <tt>ps</tt> listings.
2106
2107 <p>
2108 RCU must therefore wait for a given CPU to actually come online before
2109 it can allow itself to believe that the CPU actually exists.
2110 The resulting &ldquo;ghost CPUs&rdquo; (which are never going to
2111 come online) cause a number of
2112 <a href="https://paulmck.livejournal.com/37494.html">interesting complications</a>.
2113
2114 <h3><a name="Early Boot">Early Boot</a></h3>
2115
2116 <p>
2117 The Linux kernel's boot sequence is an interesting process,
2118 and RCU is used early, even before <tt>rcu_init()</tt>
2119 is invoked.
2120 In fact, a number of RCU's primitives can be used as soon as the
2121 initial task's <tt>task_struct</tt> is available and the
2122 boot CPU's per-CPU variables are set up.
2123 The read-side primitives (<tt>rcu_read_lock()</tt>,
2124 <tt>rcu_read_unlock()</tt>, <tt>rcu_dereference()</tt>,
2125 and <tt>rcu_access_pointer()</tt>) will operate normally very early on,
2126 as will <tt>rcu_assign_pointer()</tt>.
2127
2128 <p>
2129 Although <tt>call_rcu()</tt> may be invoked at any
2130 time during boot, callbacks are not guaranteed to be invoked until after
2131 the scheduler is fully up and running.
2132 This delay in callback invocation is due to the fact that RCU does not
2133 invoke callbacks until it is fully initialized, and this full initialization
2134 cannot occur until after the scheduler has initialized itself to the
2135 point where RCU can spawn and run its kthreads.
2136 In theory, it would be possible to invoke callbacks earlier,
2137 however, this is not a panacea because there would be severe restrictions
2138 on what operations those callbacks could invoke.
2139
2140 <p>
2141 Perhaps surprisingly, <tt>synchronize_rcu()</tt>,
2142 <a href="#Bottom-Half Flavor"><tt>synchronize_rcu_bh()</tt></a>
2143 (<a href="#Bottom-Half Flavor">discussed below</a>),
2144 and
2145 <a href="#Sched Flavor"><tt>synchronize_sched()</tt></a>
2146 will all operate normally
2147 during very early boot, the reason being that there is only one CPU
2148 and preemption is disabled.
2149 This means that the call <tt>synchronize_rcu()</tt> (or friends)
2150 itself is a quiescent
2151 state and thus a grace period, so the early-boot implementation can
2152 be a no-op.
2153
2154 <p>
2155 Both <tt>synchronize_rcu_bh()</tt> and <tt>synchronize_sched()</tt>
2156 continue to operate normally through the remainder of boot, courtesy
2157 of the fact that preemption is disabled across their RCU read-side
2158 critical sections and also courtesy of the fact that there is still
2159 only one CPU.
2160 However, once the scheduler starts initializing, preemption is enabled.
2161 There is still only a single CPU, but the fact that preemption is enabled
2162 means that the no-op implementation of <tt>synchronize_rcu()</tt> no
2163 longer works in <tt>CONFIG_PREEMPT=y</tt> kernels.
2164 Therefore, as soon as the scheduler starts initializing, the early-boot
2165 fastpath is disabled.
2166 This means that <tt>synchronize_rcu()</tt> switches to its runtime
2167 mode of operation where it posts callbacks, which in turn means that
2168 any call to <tt>synchronize_rcu()</tt> will block until the corresponding
2169 callback is invoked.
2170 Unfortunately, the callback cannot be invoked until RCU's runtime
2171 grace-period machinery is up and running, which cannot happen until
2172 the scheduler has initialized itself sufficiently to allow RCU's
2173 kthreads to be spawned.
2174 Therefore, invoking <tt>synchronize_rcu()</tt> during scheduler
2175 initialization can result in deadlock.
2176
2177 <table>
2178 <tr><th>&nbsp;</th></tr>
2179 <tr><th align="left">Quick Quiz:</th></tr>
2180 <tr><td>
2181 So what happens with <tt>synchronize_rcu()</tt> during
2182 scheduler initialization for <tt>CONFIG_PREEMPT=n</tt>
2183 kernels?
2184 </td></tr>
2185 <tr><th align="left">Answer:</th></tr>
2186 <tr><td bgcolor="#ffffff"><font color="ffffff">
2187 In <tt>CONFIG_PREEMPT=n</tt> kernel, <tt>synchronize_rcu()</tt>
2188 maps directly to <tt>synchronize_sched()</tt>.
2189 Therefore, <tt>synchronize_rcu()</tt> works normally throughout
2190 boot in <tt>CONFIG_PREEMPT=n</tt> kernels.
2191 However, your code must also work in <tt>CONFIG_PREEMPT=y</tt> kernels,
2192 so it is still necessary to avoid invoking <tt>synchronize_rcu()</tt>
2193 during scheduler initialization.
2194 </font></td></tr>
2195 <tr><td>&nbsp;</td></tr>
2196 </table>
2197
2198 <p>
2199 I learned of these boot-time requirements as a result of a series of
2200 system hangs.
2201
2202 <h3><a name="Interrupts and NMIs">Interrupts and NMIs</a></h3>
2203
2204 <p>
2205 The Linux kernel has interrupts, and RCU read-side critical sections are
2206 legal within interrupt handlers and within interrupt-disabled regions
2207 of code, as are invocations of <tt>call_rcu()</tt>.
2208
2209 <p>
2210 Some Linux-kernel architectures can enter an interrupt handler from
2211 non-idle process context, and then just never leave it, instead stealthily
2212 transitioning back to process context.
2213 This trick is sometimes used to invoke system calls from inside the kernel.
2214 These &ldquo;half-interrupts&rdquo; mean that RCU has to be very careful
2215 about how it counts interrupt nesting levels.
2216 I learned of this requirement the hard way during a rewrite
2217 of RCU's dyntick-idle code.
2218
2219 <p>
2220 The Linux kernel has non-maskable interrupts (NMIs), and
2221 RCU read-side critical sections are legal within NMI handlers.
2222 Thankfully, RCU update-side primitives, including
2223 <tt>call_rcu()</tt>, are prohibited within NMI handlers.
2224
2225 <p>
2226 The name notwithstanding, some Linux-kernel architectures
2227 can have nested NMIs, which RCU must handle correctly.
2228 Andy Lutomirski
2229 <a href="https://lkml.kernel.org/g/CALCETrXLq1y7e_dKFPgou-FKHB6Pu-r8+t-6Ds+8=va7anBWDA@mail.gmail.com">surprised me</a>
2230 with this requirement;
2231 he also kindly surprised me with
2232 <a href="https://lkml.kernel.org/g/CALCETrXSY9JpW3uE6H8WYk81sg56qasA2aqmjMPsq5dOtzso=g@mail.gmail.com">an algorithm</a>
2233 that meets this requirement.
2234
2235 <h3><a name="Loadable Modules">Loadable Modules</a></h3>
2236
2237 <p>
2238 The Linux kernel has loadable modules, and these modules can
2239 also be unloaded.
2240 After a given module has been unloaded, any attempt to call
2241 one of its functions results in a segmentation fault.
2242 The module-unload functions must therefore cancel any
2243 delayed calls to loadable-module functions, for example,
2244 any outstanding <tt>mod_timer()</tt> must be dealt with
2245 via <tt>del_timer_sync()</tt> or similar.
2246
2247 <p>
2248 Unfortunately, there is no way to cancel an RCU callback;
2249 once you invoke <tt>call_rcu()</tt>, the callback function is
2250 going to eventually be invoked, unless the system goes down first.
2251 Because it is normally considered socially irresponsible to crash the system
2252 in response to a module unload request, we need some other way
2253 to deal with in-flight RCU callbacks.
2254
2255 <p>
2256 RCU therefore provides
2257 <tt><a href="https://lwn.net/Articles/217484/">rcu_barrier()</a></tt>,
2258 which waits until all in-flight RCU callbacks have been invoked.
2259 If a module uses <tt>call_rcu()</tt>, its exit function should therefore
2260 prevent any future invocation of <tt>call_rcu()</tt>, then invoke
2261 <tt>rcu_barrier()</tt>.
2262 In theory, the underlying module-unload code could invoke
2263 <tt>rcu_barrier()</tt> unconditionally, but in practice this would
2264 incur unacceptable latencies.
2265
2266 <p>
2267 Nikita Danilov noted this requirement for an analogous filesystem-unmount
2268 situation, and Dipankar Sarma incorporated <tt>rcu_barrier()</tt> into RCU.
2269 The need for <tt>rcu_barrier()</tt> for module unloading became
2270 apparent later.
2271
2272 <h3><a name="Hotplug CPU">Hotplug CPU</a></h3>
2273
2274 <p>
2275 The Linux kernel supports CPU hotplug, which means that CPUs
2276 can come and go.
2277 It is of course illegal to use any RCU API member from an offline CPU.
2278 This requirement was present from day one in DYNIX/ptx, but
2279 on the other hand, the Linux kernel's CPU-hotplug implementation
2280 is &ldquo;interesting.&rdquo;
2281
2282 <p>
2283 The Linux-kernel CPU-hotplug implementation has notifiers that
2284 are used to allow the various kernel subsystems (including RCU)
2285 to respond appropriately to a given CPU-hotplug operation.
2286 Most RCU operations may be invoked from CPU-hotplug notifiers,
2287 including even normal synchronous grace-period operations
2288 such as <tt>synchronize_rcu()</tt>.
2289 However, expedited grace-period operations such as
2290 <tt>synchronize_rcu_expedited()</tt> are not supported,
2291 due to the fact that current implementations block CPU-hotplug
2292 operations, which could result in deadlock.
2293
2294 <p>
2295 In addition, all-callback-wait operations such as
2296 <tt>rcu_barrier()</tt> are also not supported, due to the
2297 fact that there are phases of CPU-hotplug operations where
2298 the outgoing CPU's callbacks will not be invoked until after
2299 the CPU-hotplug operation ends, which could also result in deadlock.
2300
2301 <h3><a name="Scheduler and RCU">Scheduler and RCU</a></h3>
2302
2303 <p>
2304 RCU depends on the scheduler, and the scheduler uses RCU to
2305 protect some of its data structures.
2306 This means the scheduler is forbidden from acquiring
2307 the runqueue locks and the priority-inheritance locks
2308 in the middle of an outermost RCU read-side critical section unless either
2309 (1)&nbsp;it releases them before exiting that same
2310 RCU read-side critical section, or
2311 (2)&nbsp;interrupts are disabled across
2312 that entire RCU read-side critical section.
2313 This same prohibition also applies (recursively!) to any lock that is acquired
2314 while holding any lock to which this prohibition applies.
2315 Adhering to this rule prevents preemptible RCU from invoking
2316 <tt>rcu_read_unlock_special()</tt> while either runqueue or
2317 priority-inheritance locks are held, thus avoiding deadlock.
2318
2319 <p>
2320 Prior to v4.4, it was only necessary to disable preemption across
2321 RCU read-side critical sections that acquired scheduler locks.
2322 In v4.4, expedited grace periods started using IPIs, and these
2323 IPIs could force a <tt>rcu_read_unlock()</tt> to take the slowpath.
2324 Therefore, this expedited-grace-period change required disabling of
2325 interrupts, not just preemption.
2326
2327 <p>
2328 For RCU's part, the preemptible-RCU <tt>rcu_read_unlock()</tt>
2329 implementation must be written carefully to avoid similar deadlocks.
2330 In particular, <tt>rcu_read_unlock()</tt> must tolerate an
2331 interrupt where the interrupt handler invokes both
2332 <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>.
2333 This possibility requires <tt>rcu_read_unlock()</tt> to use
2334 negative nesting levels to avoid destructive recursion via
2335 interrupt handler's use of RCU.
2336
2337 <p>
2338 This pair of mutual scheduler-RCU requirements came as a
2339 <a href="https://lwn.net/Articles/453002/">complete surprise</a>.
2340
2341 <p>
2342 As noted above, RCU makes use of kthreads, and it is necessary to
2343 avoid excessive CPU-time accumulation by these kthreads.
2344 This requirement was no surprise, but RCU's violation of it
2345 when running context-switch-heavy workloads when built with
2346 <tt>CONFIG_NO_HZ_FULL=y</tt>
2347 <a href="http://www.rdrop.com/users/paulmck/scalability/paper/BareMetal.2015.01.15b.pdf">did come as a surprise [PDF]</a>.
2348 RCU has made good progress towards meeting this requirement, even
2349 for context-switch-have <tt>CONFIG_NO_HZ_FULL=y</tt> workloads,
2350 but there is room for further improvement.
2351
2352 <h3><a name="Tracing and RCU">Tracing and RCU</a></h3>
2353
2354 <p>
2355 It is possible to use tracing on RCU code, but tracing itself
2356 uses RCU.
2357 For this reason, <tt>rcu_dereference_raw_notrace()</tt>
2358 is provided for use by tracing, which avoids the destructive
2359 recursion that could otherwise ensue.
2360 This API is also used by virtualization in some architectures,
2361 where RCU readers execute in environments in which tracing
2362 cannot be used.
2363 The tracing folks both located the requirement and provided the
2364 needed fix, so this surprise requirement was relatively painless.
2365
2366 <h3><a name="Energy Efficiency">Energy Efficiency</a></h3>
2367
2368 <p>
2369 Interrupting idle CPUs is considered socially unacceptable,
2370 especially by people with battery-powered embedded systems.
2371 RCU therefore conserves energy by detecting which CPUs are
2372 idle, including tracking CPUs that have been interrupted from idle.
2373 This is a large part of the energy-efficiency requirement,
2374 so I learned of this via an irate phone call.
2375
2376 <p>
2377 Because RCU avoids interrupting idle CPUs, it is illegal to
2378 execute an RCU read-side critical section on an idle CPU.
2379 (Kernels built with <tt>CONFIG_PROVE_RCU=y</tt> will splat
2380 if you try it.)
2381 The <tt>RCU_NONIDLE()</tt> macro and <tt>_rcuidle</tt>
2382 event tracing is provided to work around this restriction.
2383 In addition, <tt>rcu_is_watching()</tt> may be used to
2384 test whether or not it is currently legal to run RCU read-side
2385 critical sections on this CPU.
2386 I learned of the need for diagnostics on the one hand
2387 and <tt>RCU_NONIDLE()</tt> on the other while inspecting
2388 idle-loop code.
2389 Steven Rostedt supplied <tt>_rcuidle</tt> event tracing,
2390 which is used quite heavily in the idle loop.
2391
2392 <p>
2393 It is similarly socially unacceptable to interrupt an
2394 <tt>nohz_full</tt> CPU running in userspace.
2395 RCU must therefore track <tt>nohz_full</tt> userspace
2396 execution.
2397 And in
2398 <a href="https://lwn.net/Articles/558284/"><tt>CONFIG_NO_HZ_FULL_SYSIDLE=y</tt></a>
2399 kernels, RCU must separately track idle CPUs on the one hand and
2400 CPUs that are either idle or executing in userspace on the other.
2401 In both cases, RCU must be able to sample state at two points in
2402 time, and be able to determine whether or not some other CPU spent
2403 any time idle and/or executing in userspace.
2404
2405 <p>
2406 These energy-efficiency requirements have proven quite difficult to
2407 understand and to meet, for example, there have been more than five
2408 clean-sheet rewrites of RCU's energy-efficiency code, the last of
2409 which was finally able to demonstrate
2410 <a href="http://www.rdrop.com/users/paulmck/realtime/paper/AMPenergy.2013.04.19a.pdf">real energy savings running on real hardware [PDF]</a>.
2411 As noted earlier,
2412 I learned of many of these requirements via angry phone calls:
2413 Flaming me on the Linux-kernel mailing list was apparently not
2414 sufficient to fully vent their ire at RCU's energy-efficiency bugs!
2415
2416 <h3><a name="Memory Efficiency">Memory Efficiency</a></h3>
2417
2418 <p>
2419 Although small-memory non-realtime systems can simply use Tiny RCU,
2420 code size is only one aspect of memory efficiency.
2421 Another aspect is the size of the <tt>rcu_head</tt> structure
2422 used by <tt>call_rcu()</tt> and <tt>kfree_rcu()</tt>.
2423 Although this structure contains nothing more than a pair of pointers,
2424 it does appear in many RCU-protected data structures, including
2425 some that are size critical.
2426 The <tt>page</tt> structure is a case in point, as evidenced by
2427 the many occurrences of the <tt>union</tt> keyword within that structure.
2428
2429 <p>
2430 This need for memory efficiency is one reason that RCU uses hand-crafted
2431 singly linked lists to track the <tt>rcu_head</tt> structures that
2432 are waiting for a grace period to elapse.
2433 It is also the reason why <tt>rcu_head</tt> structures do not contain
2434 debug information, such as fields tracking the file and line of the
2435 <tt>call_rcu()</tt> or <tt>kfree_rcu()</tt> that posted them.
2436 Although this information might appear in debug-only kernel builds at some
2437 point, in the meantime, the <tt>-&gt;func</tt> field will often provide
2438 the needed debug information.
2439
2440 <p>
2441 However, in some cases, the need for memory efficiency leads to even
2442 more extreme measures.
2443 Returning to the <tt>page</tt> structure, the <tt>rcu_head</tt> field
2444 shares storage with a great many other structures that are used at
2445 various points in the corresponding page's lifetime.
2446 In order to correctly resolve certain
2447 <a href="https://lkml.kernel.org/g/1439976106-137226-1-git-send-email-kirill.shutemov@linux.intel.com">race conditions</a>,
2448 the Linux kernel's memory-management subsystem needs a particular bit
2449 to remain zero during all phases of grace-period processing,
2450 and that bit happens to map to the bottom bit of the
2451 <tt>rcu_head</tt> structure's <tt>-&gt;next</tt> field.
2452 RCU makes this guarantee as long as <tt>call_rcu()</tt>
2453 is used to post the callback, as opposed to <tt>kfree_rcu()</tt>
2454 or some future &ldquo;lazy&rdquo;
2455 variant of <tt>call_rcu()</tt> that might one day be created for
2456 energy-efficiency purposes.
2457
2458 <h3><a name="Performance, Scalability, Response Time, and Reliability">
2459 Performance, Scalability, Response Time, and Reliability</a></h3>
2460
2461 <p>
2462 Expanding on the
2463 <a href="#Performance and Scalability">earlier discussion</a>,
2464 RCU is used heavily by hot code paths in performance-critical
2465 portions of the Linux kernel's networking, security, virtualization,
2466 and scheduling code paths.
2467 RCU must therefore use efficient implementations, especially in its
2468 read-side primitives.
2469 To that end, it would be good if preemptible RCU's implementation
2470 of <tt>rcu_read_lock()</tt> could be inlined, however, doing
2471 this requires resolving <tt>#include</tt> issues with the
2472 <tt>task_struct</tt> structure.
2473
2474 <p>
2475 The Linux kernel supports hardware configurations with up to
2476 4096 CPUs, which means that RCU must be extremely scalable.
2477 Algorithms that involve frequent acquisitions of global locks or
2478 frequent atomic operations on global variables simply cannot be
2479 tolerated within the RCU implementation.
2480 RCU therefore makes heavy use of a combining tree based on the
2481 <tt>rcu_node</tt> structure.
2482 RCU is required to tolerate all CPUs continuously invoking any
2483 combination of RCU's runtime primitives with minimal per-operation
2484 overhead.
2485 In fact, in many cases, increasing load must <i>decrease</i> the
2486 per-operation overhead, witness the batching optimizations for
2487 <tt>synchronize_rcu()</tt>, <tt>call_rcu()</tt>,
2488 <tt>synchronize_rcu_expedited()</tt>, and <tt>rcu_barrier()</tt>.
2489 As a general rule, RCU must cheerfully accept whatever the
2490 rest of the Linux kernel decides to throw at it.
2491
2492 <p>
2493 The Linux kernel is used for real-time workloads, especially
2494 in conjunction with the
2495 <a href="https://rt.wiki.kernel.org/index.php/Main_Page">-rt patchset</a>.
2496 The real-time-latency response requirements are such that the
2497 traditional approach of disabling preemption across RCU
2498 read-side critical sections is inappropriate.
2499 Kernels built with <tt>CONFIG_PREEMPT=y</tt> therefore
2500 use an RCU implementation that allows RCU read-side critical
2501 sections to be preempted.
2502 This requirement made its presence known after users made it
2503 clear that an earlier
2504 <a href="https://lwn.net/Articles/107930/">real-time patch</a>
2505 did not meet their needs, in conjunction with some
2506 <a href="https://lkml.kernel.org/g/20050318002026.GA2693@us.ibm.com">RCU issues</a>
2507 encountered by a very early version of the -rt patchset.
2508
2509 <p>
2510 In addition, RCU must make do with a sub-100-microsecond real-time latency
2511 budget.
2512 In fact, on smaller systems with the -rt patchset, the Linux kernel
2513 provides sub-20-microsecond real-time latencies for the whole kernel,
2514 including RCU.
2515 RCU's scalability and latency must therefore be sufficient for
2516 these sorts of configurations.
2517 To my surprise, the sub-100-microsecond real-time latency budget
2518 <a href="http://www.rdrop.com/users/paulmck/realtime/paper/bigrt.2013.01.31a.LCA.pdf">
2519 applies to even the largest systems [PDF]</a>,
2520 up to and including systems with 4096 CPUs.
2521 This real-time requirement motivated the grace-period kthread, which
2522 also simplified handling of a number of race conditions.
2523
2524 <p>
2525 RCU must avoid degrading real-time response for CPU-bound threads, whether
2526 executing in usermode (which is one use case for
2527 <tt>CONFIG_NO_HZ_FULL=y</tt>) or in the kernel.
2528 That said, CPU-bound loops in the kernel must execute
2529 <tt>cond_resched_rcu_qs()</tt> at least once per few tens of milliseconds
2530 in order to avoid receiving an IPI from RCU.
2531
2532 <p>
2533 Finally, RCU's status as a synchronization primitive means that
2534 any RCU failure can result in arbitrary memory corruption that can be
2535 extremely difficult to debug.
2536 This means that RCU must be extremely reliable, which in
2537 practice also means that RCU must have an aggressive stress-test
2538 suite.
2539 This stress-test suite is called <tt>rcutorture</tt>.
2540
2541 <p>
2542 Although the need for <tt>rcutorture</tt> was no surprise,
2543 the current immense popularity of the Linux kernel is posing
2544 interesting&mdash;and perhaps unprecedented&mdash;validation
2545 challenges.
2546 To see this, keep in mind that there are well over one billion
2547 instances of the Linux kernel running today, given Android
2548 smartphones, Linux-powered televisions, and servers.
2549 This number can be expected to increase sharply with the advent of
2550 the celebrated Internet of Things.
2551
2552 <p>
2553 Suppose that RCU contains a race condition that manifests on average
2554 once per million years of runtime.
2555 This bug will be occurring about three times per <i>day</i> across
2556 the installed base.
2557 RCU could simply hide behind hardware error rates, given that no one
2558 should really expect their smartphone to last for a million years.
2559 However, anyone taking too much comfort from this thought should
2560 consider the fact that in most jurisdictions, a successful multi-year
2561 test of a given mechanism, which might include a Linux kernel,
2562 suffices for a number of types of safety-critical certifications.
2563 In fact, rumor has it that the Linux kernel is already being used
2564 in production for safety-critical applications.
2565 I don't know about you, but I would feel quite bad if a bug in RCU
2566 killed someone.
2567 Which might explain my recent focus on validation and verification.
2568
2569 <h2><a name="Other RCU Flavors">Other RCU Flavors</a></h2>
2570
2571 <p>
2572 One of the more surprising things about RCU is that there are now
2573 no fewer than five <i>flavors</i>, or API families.
2574 In addition, the primary flavor that has been the sole focus up to
2575 this point has two different implementations, non-preemptible and
2576 preemptible.
2577 The other four flavors are listed below, with requirements for each
2578 described in a separate section.
2579
2580 <ol>
2581 <li> <a href="#Bottom-Half Flavor">Bottom-Half Flavor</a>
2582 <li> <a href="#Sched Flavor">Sched Flavor</a>
2583 <li> <a href="#Sleepable RCU">Sleepable RCU</a>
2584 <li> <a href="#Tasks RCU">Tasks RCU</a>
2585 <li> <a href="#Waiting for Multiple Grace Periods">
2586 Waiting for Multiple Grace Periods</a>
2587 </ol>
2588
2589 <h3><a name="Bottom-Half Flavor">Bottom-Half Flavor</a></h3>
2590
2591 <p>
2592 The softirq-disable (AKA &ldquo;bottom-half&rdquo;,
2593 hence the &ldquo;_bh&rdquo; abbreviations)
2594 flavor of RCU, or <i>RCU-bh</i>, was developed by
2595 Dipankar Sarma to provide a flavor of RCU that could withstand the
2596 network-based denial-of-service attacks researched by Robert
2597 Olsson.
2598 These attacks placed so much networking load on the system
2599 that some of the CPUs never exited softirq execution,
2600 which in turn prevented those CPUs from ever executing a context switch,
2601 which, in the RCU implementation of that time, prevented grace periods
2602 from ever ending.
2603 The result was an out-of-memory condition and a system hang.
2604
2605 <p>
2606 The solution was the creation of RCU-bh, which does
2607 <tt>local_bh_disable()</tt>
2608 across its read-side critical sections, and which uses the transition
2609 from one type of softirq processing to another as a quiescent state
2610 in addition to context switch, idle, user mode, and offline.
2611 This means that RCU-bh grace periods can complete even when some of
2612 the CPUs execute in softirq indefinitely, thus allowing algorithms
2613 based on RCU-bh to withstand network-based denial-of-service attacks.
2614
2615 <p>
2616 Because
2617 <tt>rcu_read_lock_bh()</tt> and <tt>rcu_read_unlock_bh()</tt>
2618 disable and re-enable softirq handlers, any attempt to start a softirq
2619 handlers during the
2620 RCU-bh read-side critical section will be deferred.
2621 In this case, <tt>rcu_read_unlock_bh()</tt>
2622 will invoke softirq processing, which can take considerable time.
2623 One can of course argue that this softirq overhead should be associated
2624 with the code following the RCU-bh read-side critical section rather
2625 than <tt>rcu_read_unlock_bh()</tt>, but the fact
2626 is that most profiling tools cannot be expected to make this sort
2627 of fine distinction.
2628 For example, suppose that a three-millisecond-long RCU-bh read-side
2629 critical section executes during a time of heavy networking load.
2630 There will very likely be an attempt to invoke at least one softirq
2631 handler during that three milliseconds, but any such invocation will
2632 be delayed until the time of the <tt>rcu_read_unlock_bh()</tt>.
2633 This can of course make it appear at first glance as if
2634 <tt>rcu_read_unlock_bh()</tt> was executing very slowly.
2635
2636 <p>
2637 The
2638 <a href="https://lwn.net/Articles/609973/#RCU Per-Flavor API Table">RCU-bh API</a>
2639 includes
2640 <tt>rcu_read_lock_bh()</tt>,
2641 <tt>rcu_read_unlock_bh()</tt>,
2642 <tt>rcu_dereference_bh()</tt>,
2643 <tt>rcu_dereference_bh_check()</tt>,
2644 <tt>synchronize_rcu_bh()</tt>,
2645 <tt>synchronize_rcu_bh_expedited()</tt>,
2646 <tt>call_rcu_bh()</tt>,
2647 <tt>rcu_barrier_bh()</tt>, and
2648 <tt>rcu_read_lock_bh_held()</tt>.
2649
2650 <h3><a name="Sched Flavor">Sched Flavor</a></h3>
2651
2652 <p>
2653 Before preemptible RCU, waiting for an RCU grace period had the
2654 side effect of also waiting for all pre-existing interrupt
2655 and NMI handlers.
2656 However, there are legitimate preemptible-RCU implementations that
2657 do not have this property, given that any point in the code outside
2658 of an RCU read-side critical section can be a quiescent state.
2659 Therefore, <i>RCU-sched</i> was created, which follows &ldquo;classic&rdquo;
2660 RCU in that an RCU-sched grace period waits for for pre-existing
2661 interrupt and NMI handlers.
2662 In kernels built with <tt>CONFIG_PREEMPT=n</tt>, the RCU and RCU-sched
2663 APIs have identical implementations, while kernels built with
2664 <tt>CONFIG_PREEMPT=y</tt> provide a separate implementation for each.
2665
2666 <p>
2667 Note well that in <tt>CONFIG_PREEMPT=y</tt> kernels,
2668 <tt>rcu_read_lock_sched()</tt> and <tt>rcu_read_unlock_sched()</tt>
2669 disable and re-enable preemption, respectively.
2670 This means that if there was a preemption attempt during the
2671 RCU-sched read-side critical section, <tt>rcu_read_unlock_sched()</tt>
2672 will enter the scheduler, with all the latency and overhead entailed.
2673 Just as with <tt>rcu_read_unlock_bh()</tt>, this can make it look
2674 as if <tt>rcu_read_unlock_sched()</tt> was executing very slowly.
2675 However, the highest-priority task won't be preempted, so that task
2676 will enjoy low-overhead <tt>rcu_read_unlock_sched()</tt> invocations.
2677
2678 <p>
2679 The
2680 <a href="https://lwn.net/Articles/609973/#RCU Per-Flavor API Table">RCU-sched API</a>
2681 includes
2682 <tt>rcu_read_lock_sched()</tt>,
2683 <tt>rcu_read_unlock_sched()</tt>,
2684 <tt>rcu_read_lock_sched_notrace()</tt>,
2685 <tt>rcu_read_unlock_sched_notrace()</tt>,
2686 <tt>rcu_dereference_sched()</tt>,
2687 <tt>rcu_dereference_sched_check()</tt>,
2688 <tt>synchronize_sched()</tt>,
2689 <tt>synchronize_rcu_sched_expedited()</tt>,
2690 <tt>call_rcu_sched()</tt>,
2691 <tt>rcu_barrier_sched()</tt>, and
2692 <tt>rcu_read_lock_sched_held()</tt>.
2693 However, anything that disables preemption also marks an RCU-sched
2694 read-side critical section, including
2695 <tt>preempt_disable()</tt> and <tt>preempt_enable()</tt>,
2696 <tt>local_irq_save()</tt> and <tt>local_irq_restore()</tt>,
2697 and so on.
2698
2699 <h3><a name="Sleepable RCU">Sleepable RCU</a></h3>
2700
2701 <p>
2702 For well over a decade, someone saying &ldquo;I need to block within
2703 an RCU read-side critical section&rdquo; was a reliable indication
2704 that this someone did not understand RCU.
2705 After all, if you are always blocking in an RCU read-side critical
2706 section, you can probably afford to use a higher-overhead synchronization
2707 mechanism.
2708 However, that changed with the advent of the Linux kernel's notifiers,
2709 whose RCU read-side critical
2710 sections almost never sleep, but sometimes need to.
2711 This resulted in the introduction of
2712 <a href="https://lwn.net/Articles/202847/">sleepable RCU</a>,
2713 or <i>SRCU</i>.
2714
2715 <p>
2716 SRCU allows different domains to be defined, with each such domain
2717 defined by an instance of an <tt>srcu_struct</tt> structure.
2718 A pointer to this structure must be passed in to each SRCU function,
2719 for example, <tt>synchronize_srcu(&amp;ss)</tt>, where
2720 <tt>ss</tt> is the <tt>srcu_struct</tt> structure.
2721 The key benefit of these domains is that a slow SRCU reader in one
2722 domain does not delay an SRCU grace period in some other domain.
2723 That said, one consequence of these domains is that read-side code
2724 must pass a &ldquo;cookie&rdquo; from <tt>srcu_read_lock()</tt>
2725 to <tt>srcu_read_unlock()</tt>, for example, as follows:
2726
2727 <blockquote>
2728 <pre>
2729 1 int idx;
2730 2
2731 3 idx = srcu_read_lock(&amp;ss);
2732 4 do_something();
2733 5 srcu_read_unlock(&amp;ss, idx);
2734 </pre>
2735 </blockquote>
2736
2737 <p>
2738 As noted above, it is legal to block within SRCU read-side critical sections,
2739 however, with great power comes great responsibility.
2740 If you block forever in one of a given domain's SRCU read-side critical
2741 sections, then that domain's grace periods will also be blocked forever.
2742 Of course, one good way to block forever is to deadlock, which can
2743 happen if any operation in a given domain's SRCU read-side critical
2744 section can block waiting, either directly or indirectly, for that domain's
2745 grace period to elapse.
2746 For example, this results in a self-deadlock:
2747
2748 <blockquote>
2749 <pre>
2750 1 int idx;
2751 2
2752 3 idx = srcu_read_lock(&amp;ss);
2753 4 do_something();
2754 5 synchronize_srcu(&amp;ss);
2755 6 srcu_read_unlock(&amp;ss, idx);
2756 </pre>
2757 </blockquote>
2758
2759 <p>
2760 However, if line&nbsp;5 acquired a mutex that was held across
2761 a <tt>synchronize_srcu()</tt> for domain <tt>ss</tt>,
2762 deadlock would still be possible.
2763 Furthermore, if line&nbsp;5 acquired a mutex that was held across
2764 a <tt>synchronize_srcu()</tt> for some other domain <tt>ss1</tt>,
2765 and if an <tt>ss1</tt>-domain SRCU read-side critical section
2766 acquired another mutex that was held across as <tt>ss</tt>-domain
2767 <tt>synchronize_srcu()</tt>,
2768 deadlock would again be possible.
2769 Such a deadlock cycle could extend across an arbitrarily large number
2770 of different SRCU domains.
2771 Again, with great power comes great responsibility.
2772
2773 <p>
2774 Unlike the other RCU flavors, SRCU read-side critical sections can
2775 run on idle and even offline CPUs.
2776 This ability requires that <tt>srcu_read_lock()</tt> and
2777 <tt>srcu_read_unlock()</tt> contain memory barriers, which means
2778 that SRCU readers will run a bit slower than would RCU readers.
2779 It also motivates the <tt>smp_mb__after_srcu_read_unlock()</tt>
2780 API, which, in combination with <tt>srcu_read_unlock()</tt>,
2781 guarantees a full memory barrier.
2782
2783 <p>
2784 The
2785 <a href="https://lwn.net/Articles/609973/#RCU Per-Flavor API Table">SRCU API</a>
2786 includes
2787 <tt>srcu_read_lock()</tt>,
2788 <tt>srcu_read_unlock()</tt>,
2789 <tt>srcu_dereference()</tt>,
2790 <tt>srcu_dereference_check()</tt>,
2791 <tt>synchronize_srcu()</tt>,
2792 <tt>synchronize_srcu_expedited()</tt>,
2793 <tt>call_srcu()</tt>,
2794 <tt>srcu_barrier()</tt>, and
2795 <tt>srcu_read_lock_held()</tt>.
2796 It also includes
2797 <tt>DEFINE_SRCU()</tt>,
2798 <tt>DEFINE_STATIC_SRCU()</tt>, and
2799 <tt>init_srcu_struct()</tt>
2800 APIs for defining and initializing <tt>srcu_struct</tt> structures.
2801
2802 <h3><a name="Tasks RCU">Tasks RCU</a></h3>
2803
2804 <p>
2805 Some forms of tracing use &ldquo;tramopolines&rdquo; to handle the
2806 binary rewriting required to install different types of probes.
2807 It would be good to be able to free old trampolines, which sounds
2808 like a job for some form of RCU.
2809 However, because it is necessary to be able to install a trace
2810 anywhere in the code, it is not possible to use read-side markers
2811 such as <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>.
2812 In addition, it does not work to have these markers in the trampoline
2813 itself, because there would need to be instructions following
2814 <tt>rcu_read_unlock()</tt>.
2815 Although <tt>synchronize_rcu()</tt> would guarantee that execution
2816 reached the <tt>rcu_read_unlock()</tt>, it would not be able to
2817 guarantee that execution had completely left the trampoline.
2818
2819 <p>
2820 The solution, in the form of
2821 <a href="https://lwn.net/Articles/607117/"><i>Tasks RCU</i></a>,
2822 is to have implicit
2823 read-side critical sections that are delimited by voluntary context
2824 switches, that is, calls to <tt>schedule()</tt>,
2825 <tt>cond_resched_rcu_qs()</tt>, and
2826 <tt>synchronize_rcu_tasks()</tt>.
2827 In addition, transitions to and from userspace execution also delimit
2828 tasks-RCU read-side critical sections.
2829
2830 <p>
2831 The tasks-RCU API is quite compact, consisting only of
2832 <tt>call_rcu_tasks()</tt>,
2833 <tt>synchronize_rcu_tasks()</tt>, and
2834 <tt>rcu_barrier_tasks()</tt>.
2835
2836 <h3><a name="Waiting for Multiple Grace Periods">
2837 Waiting for Multiple Grace Periods</a></h3>
2838
2839 <p>
2840 Perhaps you have an RCU protected data structure that is accessed from
2841 RCU read-side critical sections, from softirq handlers, and from
2842 hardware interrupt handlers.
2843 That is three flavors of RCU, the normal flavor, the bottom-half flavor,
2844 and the sched flavor.
2845 How to wait for a compound grace period?
2846
2847 <p>
2848 The best approach is usually to &ldquo;just say no!&rdquo; and
2849 insert <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>
2850 around each RCU read-side critical section, regardless of what
2851 environment it happens to be in.
2852 But suppose that some of the RCU read-side critical sections are
2853 on extremely hot code paths, and that use of <tt>CONFIG_PREEMPT=n</tt>
2854 is not a viable option, so that <tt>rcu_read_lock()</tt> and
2855 <tt>rcu_read_unlock()</tt> are not free.
2856 What then?
2857
2858 <p>
2859 You <i>could</i> wait on all three grace periods in succession, as follows:
2860
2861 <blockquote>
2862 <pre>
2863 1 synchronize_rcu();
2864 2 synchronize_rcu_bh();
2865 3 synchronize_sched();
2866 </pre>
2867 </blockquote>
2868
2869 <p>
2870 This works, but triples the update-side latency penalty.
2871 In cases where this is not acceptable, <tt>synchronize_rcu_mult()</tt>
2872 may be used to wait on all three flavors of grace period concurrently:
2873
2874 <blockquote>
2875 <pre>
2876 1 synchronize_rcu_mult(call_rcu, call_rcu_bh, call_rcu_sched);
2877 </pre>
2878 </blockquote>
2879
2880 <p>
2881 But what if it is necessary to also wait on SRCU?
2882 This can be done as follows:
2883
2884 <blockquote>
2885 <pre>
2886 1 static void call_my_srcu(struct rcu_head *head,
2887 2 void (*func)(struct rcu_head *head))
2888 3 {
2889 4 call_srcu(&amp;my_srcu, head, func);
2890 5 }
2891 6
2892 7 synchronize_rcu_mult(call_rcu, call_rcu_bh, call_rcu_sched, call_my_srcu);
2893 </pre>
2894 </blockquote>
2895
2896 <p>
2897 If you needed to wait on multiple different flavors of SRCU
2898 (but why???), you would need to create a wrapper function resembling
2899 <tt>call_my_srcu()</tt> for each SRCU flavor.
2900
2901 <table>
2902 <tr><th>&nbsp;</th></tr>
2903 <tr><th align="left">Quick Quiz:</th></tr>
2904 <tr><td>
2905 But what if I need to wait for multiple RCU flavors, but I also need
2906 the grace periods to be expedited?
2907 </td></tr>
2908 <tr><th align="left">Answer:</th></tr>
2909 <tr><td bgcolor="#ffffff"><font color="ffffff">
2910 If you are using expedited grace periods, there should be less penalty
2911 for waiting on them in succession.
2912 But if that is nevertheless a problem, you can use workqueues
2913 or multiple kthreads to wait on the various expedited grace
2914 periods concurrently.
2915 </font></td></tr>
2916 <tr><td>&nbsp;</td></tr>
2917 </table>
2918
2919 <p>
2920 Again, it is usually better to adjust the RCU read-side critical sections
2921 to use a single flavor of RCU, but when this is not feasible, you can use
2922 <tt>synchronize_rcu_mult()</tt>.
2923
2924 <h2><a name="Possible Future Changes">Possible Future Changes</a></h2>
2925
2926 <p>
2927 One of the tricks that RCU uses to attain update-side scalability is
2928 to increase grace-period latency with increasing numbers of CPUs.
2929 If this becomes a serious problem, it will be necessary to rework the
2930 grace-period state machine so as to avoid the need for the additional
2931 latency.
2932
2933 <p>
2934 Expedited grace periods scan the CPUs, so their latency and overhead
2935 increases with increasing numbers of CPUs.
2936 If this becomes a serious problem on large systems, it will be necessary
2937 to do some redesign to avoid this scalability problem.
2938
2939 <p>
2940 RCU disables CPU hotplug in a few places, perhaps most notably in the
2941 expedited grace-period and <tt>rcu_barrier()</tt> operations.
2942 If there is a strong reason to use expedited grace periods in CPU-hotplug
2943 notifiers, it will be necessary to avoid disabling CPU hotplug.
2944 This would introduce some complexity, so there had better be a <i>very</i>
2945 good reason.
2946
2947 <p>
2948 The tradeoff between grace-period latency on the one hand and interruptions
2949 of other CPUs on the other hand may need to be re-examined.
2950 The desire is of course for zero grace-period latency as well as zero
2951 interprocessor interrupts undertaken during an expedited grace period
2952 operation.
2953 While this ideal is unlikely to be achievable, it is quite possible that
2954 further improvements can be made.
2955
2956 <p>
2957 The multiprocessor implementations of RCU use a combining tree that
2958 groups CPUs so as to reduce lock contention and increase cache locality.
2959 However, this combining tree does not spread its memory across NUMA
2960 nodes nor does it align the CPU groups with hardware features such
2961 as sockets or cores.
2962 Such spreading and alignment is currently believed to be unnecessary
2963 because the hotpath read-side primitives do not access the combining
2964 tree, nor does <tt>call_rcu()</tt> in the common case.
2965 If you believe that your architecture needs such spreading and alignment,
2966 then your architecture should also benefit from the
2967 <tt>rcutree.rcu_fanout_leaf</tt> boot parameter, which can be set
2968 to the number of CPUs in a socket, NUMA node, or whatever.
2969 If the number of CPUs is too large, use a fraction of the number of
2970 CPUs.
2971 If the number of CPUs is a large prime number, well, that certainly
2972 is an &ldquo;interesting&rdquo; architectural choice!
2973 More flexible arrangements might be considered, but only if
2974 <tt>rcutree.rcu_fanout_leaf</tt> has proven inadequate, and only
2975 if the inadequacy has been demonstrated by a carefully run and
2976 realistic system-level workload.
2977
2978 <p>
2979 Please note that arrangements that require RCU to remap CPU numbers will
2980 require extremely good demonstration of need and full exploration of
2981 alternatives.
2982
2983 <p>
2984 There is an embarrassingly large number of flavors of RCU, and this
2985 number has been increasing over time.
2986 Perhaps it will be possible to combine some at some future date.
2987
2988 <p>
2989 RCU's various kthreads are reasonably recent additions.
2990 It is quite likely that adjustments will be required to more gracefully
2991 handle extreme loads.
2992 It might also be necessary to be able to relate CPU utilization by
2993 RCU's kthreads and softirq handlers to the code that instigated this
2994 CPU utilization.
2995 For example, RCU callback overhead might be charged back to the
2996 originating <tt>call_rcu()</tt> instance, though probably not
2997 in production kernels.
2998
2999 <h2><a name="Summary">Summary</a></h2>
3000
3001 <p>
3002 This document has presented more than two decade's worth of RCU
3003 requirements.
3004 Given that the requirements keep changing, this will not be the last
3005 word on this subject, but at least it serves to get an important
3006 subset of the requirements set forth.
3007
3008 <h2><a name="Acknowledgments">Acknowledgments</a></h2>
3009
3010 I am grateful to Steven Rostedt, Lai Jiangshan, Ingo Molnar,
3011 Oleg Nesterov, Borislav Petkov, Peter Zijlstra, Boqun Feng, and
3012 Andy Lutomirski for their help in rendering
3013 this article human readable, and to Michelle Rankin for her support
3014 of this effort.
3015 Other contributions are acknowledged in the Linux kernel's git archive.
3016 The cartoon is copyright (c) 2013 by Melissa Broussard,
3017 and is provided
3018 under the terms of the Creative Commons Attribution-Share Alike 3.0
3019 United States license.
3020
3021 </body></html>
This page took 0.103211 seconds and 6 git commands to generate.