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