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