documentation: Expand on scheduler/RCU deadlock requirements
[deliverable/linux.git] / Documentation / RCU / Design / Requirements / Requirements.htmlx
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
2 "http://www.w3.org/TR/html4/loose.dtd">
3 <html>
4 <head><title>A Tour Through RCU's Requirements [LWN.net]</title>
5 <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
6
7 <h1>A Tour Through RCU's Requirements</h1>
8
9 <p>Copyright IBM Corporation, 2015</p>
10 <p>Author: Paul E.&nbsp;McKenney</p>
11 <p><i>The initial version of this document appeared in the
12 <a href="https://lwn.net/">LWN</a> articles
13 <a href="https://lwn.net/Articles/652156/">here</a>,
14 <a href="https://lwn.net/Articles/652677/">here</a>, and
15 <a href="https://lwn.net/Articles/653326/">here</a>.</i></p>
16
17 <h2>Introduction</h2>
18
19 <p>
20 Read-copy update (RCU) is a synchronization mechanism that is often
21 used as a replacement for reader-writer locking.
22 RCU is unusual in that updaters do not block readers,
23 which means that RCU's read-side primitives can be exceedingly fast
24 and scalable.
25 In addition, updaters can make useful forward progress concurrently
26 with readers.
27 However, all this concurrency between RCU readers and updaters does raise
28 the question of exactly what RCU readers are doing, which in turn
29 raises the question of exactly what RCU's requirements are.
30
31 <p>
32 This document therefore summarizes RCU's requirements, and can be thought
33 of as an informal, high-level specification for RCU.
34 It is important to understand that RCU's specification is primarily
35 empirical in nature;
36 in fact, I learned about many of these requirements the hard way.
37 This situation might cause some consternation, however, not only
38 has this learning process been a lot of fun, but it has also been
39 a great privilege to work with so many people willing to apply
40 technologies in interesting new ways.
41
42 <p>
43 All that aside, here are the categories of currently known RCU requirements:
44 </p>
45
46 <ol>
47 <li> <a href="#Fundamental Requirements">
48 Fundamental Requirements</a>
49 <li> <a href="#Fundamental Non-Requirements">Fundamental Non-Requirements</a>
50 <li> <a href="#Parallelism Facts of Life">
51 Parallelism Facts of Life</a>
52 <li> <a href="#Quality-of-Implementation Requirements">
53 Quality-of-Implementation Requirements</a>
54 <li> <a href="#Linux Kernel Complications">
55 Linux Kernel Complications</a>
56 <li> <a href="#Software-Engineering Requirements">
57 Software-Engineering Requirements</a>
58 <li> <a href="#Other RCU Flavors">
59 Other RCU Flavors</a>
60 <li> <a href="#Possible Future Changes">
61 Possible Future Changes</a>
62 </ol>
63
64 <p>
65 This is followed by a <a href="#Summary">summary</a>,
66 which 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>
72 RCU's fundamental requirements are the closest thing RCU has to hard
73 mathematical requirements.
74 These are:
75
76 <ol>
77 <li> <a href="#Grace-Period Guarantee">
78 Grace-Period Guarantee</a>
79 <li> <a href="#Publish-Subscribe Guarantee">
80 Publish-Subscribe Guarantee</a>
81 <li> <a href="#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>
90 RCU's grace-period guarantee is unusual in being premeditated:
91 Jack Slingwine and I had this guarantee firmly in mind when we started
92 work on RCU (then called &ldquo;rclock&rdquo;) in the early 1990s.
93 That said, the past two decades of experience with RCU have produced
94 a much more detailed understanding of this guarantee.
95
96 <p>
97 RCU's grace-period guarantee allows updaters to wait for the completion
98 of all pre-existing RCU read-side critical sections.
99 An RCU read-side critical section
100 begins with the marker <tt>rcu_read_lock()</tt> and ends with
101 the marker <tt>rcu_read_unlock()</tt>.
102 These markers may be nested, and RCU treats a nested set as one
103 big RCU read-side critical section.
104 Production-quality implementations of <tt>rcu_read_lock()</tt> and
105 <tt>rcu_read_unlock()</tt> are extremely lightweight, and in
106 fact have exactly zero overhead in Linux kernels built for production
107 use with <tt>CONFIG_PREEMPT=n</tt>.
108
109 <p>
110 This guarantee allows ordering to be enforced with extremely low
111 overhead 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 }
124 10
125 11 void thread1(void)
126 12 {
127 13 WRITE_ONCE(x, 1);
128 14 synchronize_rcu();
129 15 WRITE_ONCE(y, 1);
130 16 }
131 </pre>
132 </blockquote>
133
134 <p>
135 Because the <tt>synchronize_rcu()</tt> on line&nbsp;14 waits for
136 all pre-existing readers, any instance of <tt>thread0()</tt> that
137 loads a value of zero from <tt>x</tt> must complete before
138 <tt>thread1()</tt> stores to <tt>y</tt>, so that instance must
139 also load a value of zero from <tt>y</tt>.
140 Similarly, any instance of <tt>thread0()</tt> that loads a value of
141 one from <tt>y</tt> must have started after the
142 <tt>synchronize_rcu()</tt> started, and must therefore also load
143 a value of one from <tt>x</tt>.
144 Therefore, the outcome:
145 <blockquote>
146 <pre>
147 (r1 == 0 &amp;&amp; r2 == 1)
148 </pre>
149 </blockquote>
150 cannot happen.
151
152 <p>@@QQ@@
153 Wait a minute!
154 You said that updaters can make useful forward progress concurrently
155 with readers, but pre-existing readers will block
156 <tt>synchronize_rcu()</tt>!!!
157 Just who are you trying to fool???
158 <p>@@QQA@@
159 First, 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
161 be discussed later.
162 Second, even when using <tt>synchronize_rcu()</tt>, the other
163 update-side code does run concurrently with readers, whether pre-existing
164 or not.
165 <p>@@QQE@@
166
167 <p>
168 This scenario resembles one of the first uses of RCU in
169 <a href="https://en.wikipedia.org/wiki/DYNIX">DYNIX/ptx</a>,
170 which managed a distributed lock manager's transition into
171 a state suitable for handling recovery from node failure,
172 more 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 {
185 10 int state_snap;
186 11
187 12 rcu_read_lock();
188 13 state_snap = READ_ONCE(state);
189 14 if (state_snap == STATE_NORMAL)
190 15 do_something();
191 16 else
192 17 do_something_carefully();
193 18 rcu_read_unlock();
194 19 }
195 20
196 21 void start_recovery(void)
197 22 {
198 23 WRITE_ONCE(state, STATE_WANT_RECOVERY);
199 24 synchronize_rcu();
200 25 WRITE_ONCE(state, STATE_RECOVERING);
201 26 recovery();
202 27 WRITE_ONCE(state, STATE_WANT_NORMAL);
203 28 synchronize_rcu();
204 29 WRITE_ONCE(state, STATE_NORMAL);
205 30 }
206 </pre>
207 </blockquote>
208
209 <p>
210 The RCU read-side critical section in <tt>do_something_dlm()</tt>
211 works with the <tt>synchronize_rcu()</tt> in <tt>start_recovery()</tt>
212 to guarantee that <tt>do_something()</tt> never runs concurrently
213 with <tt>recovery()</tt>, but with little or no synchronization
214 overhead in <tt>do_something_dlm()</tt>.
215
216 <p>@@QQ@@
217 Why is the <tt>synchronize_rcu()</tt> on line&nbsp;28 needed?
218 <p>@@QQA@@
219 Without that extra grace period, memory reordering could result in
220 <tt>do_something_dlm()</tt> executing <tt>do_something()</tt>
221 concurrently with the last bits of <tt>recovery()</tt>.
222 <p>@@QQE@@
223
224 <p>
225 In order to avoid fatal problems such as deadlocks,
226 an RCU read-side critical section must not contain calls to
227 <tt>synchronize_rcu()</tt>.
228 Similarly, an RCU read-side critical section must not
229 contain anything that waits, directly or indirectly, on completion of
230 an invocation of <tt>synchronize_rcu()</tt>.
231
232 <p>
233 Although 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>,
235 it would be good to be able to use RCU to coordinate read-side
236 access to linked data structures.
237 For this, the grace-period guarantee is not sufficient, as can
238 be seen in function <tt>add_gp_buggy()</tt> below.
239 We will look at the reader's code later, but in the meantime, just think of
240 the reader as locklessly picking up the <tt>gp</tt> pointer,
241 and, 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;
255 10 }
256 11 p-&gt;a = a;
257 12 p-&gt;b = a;
258 13 gp = p; /* ORDERING BUG */
259 14 spin_unlock(&amp;gp_lock);
260 15 return true;
261 16 }
262 </pre>
263 </blockquote>
264
265 <p>
266 The problem is that both the compiler and weakly ordered CPUs are within
267 their 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;
280 10 }
281 <b>11 gp = p; /* ORDERING BUG */
282 12 p-&gt;a = a;
283 13 p-&gt;b = a;</b>
284 14 spin_unlock(&amp;gp_lock);
285 15 return true;
286 16 }
287 </pre>
288 </blockquote>
289
290 <p>
291 If an RCU reader fetches <tt>gp</tt> just after
292 <tt>add_gp_buggy_optimized</tt> executes line&nbsp;11,
293 it will see garbage in the <tt>-&gt;a</tt> and <tt>-&gt;b</tt>
294 fields.
295 And this is but one of many ways in which compiler and hardware optimizations
296 could cause trouble.
297 Therefore, we clearly need some way to prevent the compiler and the CPU from
298 reordering in this manner, which brings us to the publish-subscribe
299 guarantee discussed in the next section.
300
301 <h3><a name="Publish-Subscribe Guarantee">Publish/Subscribe Guarantee</a></h3>
302
303 <p>
304 RCU's publish-subscribe guarantee allows data to be inserted
305 into a linked data structure without disrupting RCU readers.
306 The updater uses <tt>rcu_assign_pointer()</tt> to insert the
307 new data, and readers use <tt>rcu_dereference()</tt> to
308 access data, whether new or old.
309 The 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;
322 10 }
323 11 p-&gt;a = a;
324 12 p-&gt;b = a;
325 13 rcu_assign_pointer(gp, p);
326 14 spin_unlock(&amp;gp_lock);
327 15 return true;
328 16 }
329 </pre>
330 </blockquote>
331
332 <p>
333 The <tt>rcu_assign_pointer()</tt> on line&nbsp;13 is conceptually
334 equivalent to a simple assignment statement, but also guarantees
335 that its assignment will
336 happen after the two assignments in lines&nbsp;11 and&nbsp;12,
337 similar to the C11 <tt>memory_order_release</tt> store operation.
338 It also prevents any number of &ldquo;interesting&rdquo; compiler
339 optimizations, for example, the use of <tt>gp</tt> as a scratch
340 location immediately preceding the assignment.
341
342 <p>@@QQ@@
343 But <tt>rcu_assign_pointer()</tt> does nothing to prevent the
344 two assignments to <tt>p-&gt;a</tt> and <tt>p-&gt;b</tt>
345 from being reordered.
346 Can't that also cause problems?
347 <p>@@QQA@@
348 No, it cannot.
349 The readers cannot see either of these two fields until
350 the assignment to <tt>gp</tt>, by which time both fields are
351 fully initialized.
352 So reordering the assignments
353 to <tt>p-&gt;a</tt> and <tt>p-&gt;b</tt> cannot possibly
354 cause any problems.
355 <p>@@QQE@@
356
357 <p>
358 It is tempting to assume that the reader need not do anything special
359 to control its accesses to the RCU-protected data,
360 as 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 }
373 10 rcu_read_unlock();
374 11 return false;
375 12 }
376 </pre>
377 </blockquote>
378
379 <p>
380 However, this temptation must be resisted because there are a
381 surprisingly 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>)
384 can trip this code up.
385 For but one example, if the compiler were short of registers, it
386 might choose to refetch from <tt>gp</tt> rather than keeping
387 a 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();
400 10 return false;
401 11 }
402 </pre>
403 </blockquote>
404
405 <p>
406 If this function ran concurrently with a series of updates that
407 replaced the current structure with a new one,
408 the fetches of <tt>gp-&gt;a</tt>
409 and <tt>gp-&gt;b</tt> might well come from two different structures,
410 which could cause serious confusion.
411 To 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 }
425 10 rcu_read_unlock();
426 11 return false;
427 12 }
428 </pre>
429 </blockquote>
430
431 <p>
432 The <tt>rcu_dereference()</tt> uses volatile casts and (for DEC Alpha)
433 memory barriers in the Linux kernel.
434 Should 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>
436 ever appear, then <tt>rcu_dereference()</tt> could be implemented
437 as a <tt>memory_order_consume</tt> load.
438 Regardless of the exact implementation, a pointer fetched by
439 <tt>rcu_dereference()</tt> may not be used outside of the
440 outermost RCU read-side critical section containing that
441 <tt>rcu_dereference()</tt>, unless protection of
442 the corresponding data element has been passed from RCU to some
443 other synchronization mechanism, most commonly locking or
444 <a href="https://www.kernel.org/doc/Documentation/RCU/rcuref.txt">reference counting</a>.
445
446 <p>
447 In short, updaters use <tt>rcu_assign_pointer()</tt> and readers
448 use <tt>rcu_dereference()</tt>, and these two RCU API elements
449 work together to ensure that readers have a consistent view of
450 newly added data elements.
451
452 <p>
453 Of course, it is also necessary to remove elements from RCU-protected
454 data 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
466 This 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;
479 10 }
480 11 rcu_assign_pointer(gp, NULL);
481 12 spin_unlock(&amp;gp_lock);
482 13 synchronize_rcu();
483 14 kfree(p);
484 15 return true;
485 16 }
486 </pre>
487 </blockquote>
488
489 <p>
490 This function is straightforward, with line&nbsp;13 waiting for a grace
491 period before line&nbsp;14 frees the old data element.
492 This 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.
495 The <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@@
513 Without the <tt>rcu_dereference()</tt> or the
514 <tt>rcu_access_pointer()</tt>, what destructive optimizations
515 might the compiler make use of?
516 <p>@@QQA@@
517 Let's start with what happens to <tt>do_something_gp()</tt>
518 if it fails to use <tt>rcu_dereference()</tt>.
519 It could reuse a value formerly fetched from this same pointer.
520 It could also fetch the pointer from <tt>gp</tt> in a byte-at-a-time
521 manner, resulting in <i>load tearing</i>, in turn resulting a bytewise
522 mash-up of two distince pointer values.
523 It might even use value-speculation optimizations, where it makes a wrong
524 guess, but by the time it gets around to checking the value, an update
525 has changed the pointer to match the wrong guess.
526 Too bad about any dereferences that returned pre-initialization garbage
527 in the meantime!
528
529 <p>
530 For <tt>remove_gp_synchronous()</tt>, as long as all modifications
531 to <tt>gp</tt> are carried out while holding <tt>gp_lock</tt>,
532 the above optimizations are harmless.
533 However,
534 with <tt>CONFIG_SPARSE_RCU_POINTER=y</tt>,
535 <tt>sparse</tt> will complain if you
536 define <tt>gp</tt> with <tt>__rcu</tt> and then
537 access it without using
538 either <tt>rcu_access_pointer()</tt> or <tt>rcu_dereference()</tt>.
539 <p>@@QQE@@
540
541 <p>
542 This simple linked-data-structure scenario clearly demonstrates the need
543 for RCU's stringent memory-ordering guarantees on systems with more than
544 one 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@@
585 Given that multiple CPUs can start RCU read-side critical sections
586 at any time without any ordering whatsoever, how can RCU possibly tell whether
587 or not a given RCU read-side critical section starts before a
588 given instance of <tt>synchronize_rcu()</tt>?
589 <p>@@QQA@@
590 If RCU cannot tell whether or not a given
591 RCU read-side critical section starts before a
592 given instance of <tt>synchronize_rcu()</tt>,
593 then it must assume that the RCU read-side critical section
594 started first.
595 In other words, a given instance of <tt>synchronize_rcu()</tt>
596 can avoid waiting on a given RCU read-side critical section only
597 if it can prove that <tt>synchronize_rcu()</tt> started first.
598 <p>@@QQE@@
599
600 <p>@@QQ@@
601 The first and second guarantees require unbelievably strict ordering!
602 Are all these memory barriers <i> really</i> required?
603 <p>@@QQA@@
604 Yes, they really are required.
605 To see why the first guarantee is required, consider the following
606 sequence 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>
622 Therefore, there absolutely must be a full memory barrier between the
623 end of the RCU read-side critical section and the end of the
624 grace period.
625
626 <p>
627 The sequence of events demonstrating the necessity of the second rule
628 is 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>
643 And similarly, without a memory barrier between the beginning of the
644 grace period and the beginning of the RCU read-side critical section,
645 CPU&nbsp;1 might end up accessing the freelist.
646
647 <p>
648 The &ldquo;as if&rdquo; rule of course applies, so that any implementation
649 that acts as if the appropriate memory barriers were in place is a
650 correct implementation.
651 That said, it is much easier to fool yourself into believing that you have
652 adhered to the as-if rule than it is to actually adhere to it!
653 <p>@@QQE@@
654
655 <p>
656 In short, RCU's publish-subscribe guarantee is provided by the combination
657 of <tt>rcu_assign_pointer()</tt> and <tt>rcu_dereference()</tt>.
658 This guarantee allows data elements to be safely added to RCU-protected
659 linked data structures without disrupting RCU readers.
660 This guarantee can be used in combination with the grace-period
661 guarantee to also allow data elements to be removed from RCU-protected
662 linked data structures, again without disrupting RCU readers.
663
664 <p>
665 This guarantee was only partially premeditated.
666 DYNIX/ptx used an explicit memory barrier for publication, but had nothing
667 resembling <tt>rcu_dereference()</tt> for subscription, nor did it
668 have anything resembling the <tt>smp_read_barrier_depends()</tt>
669 that was later subsumed into <tt>rcu_dereference()</tt>.
670 The need for these operations made itself known quite suddenly at a
671 late-1990s meeting with the DEC Alpha architects, back in the days when
672 DEC was still a free-standing company.
673 It took the Alpha architects a good hour to convince me that any sort
674 of barrier would ever be needed, and it then took me a good <i>two</i> hours
675 to convince them that their documentation did not make this point clear.
676 More recent work with the C and C++ standards committees have provided
677 much education on tricks and traps from the compiler.
678 In short, compilers were much less tricky in the early 1990s, but in
679 2015, 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>
684 The common-case RCU primitives are unconditional.
685 They are invoked, they do their job, and they return, with no possibility
686 of error, and no need to retry.
687 This is a key RCU design philosophy.
688
689 <p>
690 However, this philosophy is pragmatic rather than pigheaded.
691 If someone comes up with a good justification for a particular conditional
692 RCU primitive, it might well be implemented and added.
693 After all, this guarantee was reverse-engineered, not premeditated.
694 The unconditional nature of the RCU primitives was initially an
695 accident of implementation, and later experience with synchronization
696 primitives with conditional primitives caused me to elevate this
697 accident to a guarantee.
698 Therefore, the justification for adding a conditional primitive to
699 RCU 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>
704 As far as RCU is concerned, it is always possible to carry out an
705 update within an RCU read-side critical section.
706 For example, that RCU read-side critical section might search for
707 a given data element, and then might acquire the update-side
708 spinlock in order to update that element, all while remaining
709 in that RCU read-side critical section.
710 Of course, it is necessary to exit the RCU read-side critical section
711 before invoking <tt>synchronize_rcu()</tt>, however, this
712 inconvenience can be avoided through use of the
713 <tt>call_rcu()</tt> and <tt>kfree_rcu()</tt> API members
714 described later in this document.
715
716 <p>@@QQ@@
717 But how does the upgrade-to-write operation exclude other readers?
718 <p>@@QQA@@
719 It doesn't, just like normal RCU updates, which also do not exclude
720 RCU readers.
721 <p>@@QQE@@
722
723 <p>
724 This guarantee allows lookup code to be shared between read-side
725 and update-side code, and was premeditated, appearing in the earliest
726 DYNIX/ptx RCU documentation.
727
728 <h2><a name="Fundamental Non-Requirements">Fundamental Non-Requirements</a></h2>
729
730 <p>
731 RCU provides extremely lightweight readers, and its read-side guarantees,
732 though quite useful, are correspondingly lightweight.
733 It is therefore all too easy to assume that RCU is guaranteeing more
734 than it really is.
735 Of course, the list of things that RCU does not guarantee is infinitely
736 long, however, the following sections list a few non-guarantees that
737 have caused confusion.
738 Except 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>
758 Reader-side markers such as <tt>rcu_read_lock()</tt> and
759 <tt>rcu_read_unlock()</tt> provide absolutely no ordering guarantees
760 except through their interaction with the grace-period APIs such as
761 <tt>synchronize_rcu()</tt>.
762 To 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 }
775 10
776 11 void thread1(void)
777 12 {
778 13 rcu_read_lock();
779 14 r1 = READ_ONCE(y);
780 15 rcu_read_unlock();
781 16 rcu_read_lock();
782 17 r2 = READ_ONCE(x);
783 18 rcu_read_unlock();
784 19 }
785 </pre>
786 </blockquote>
787
788 <p>
789 After <tt>thread0()</tt> and <tt>thread1()</tt> execute
790 concurrently, 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>),
799 which would not be possible if <tt>rcu_read_lock()</tt> and
800 <tt>rcu_read_unlock()</tt> had much in the way of ordering
801 properties.
802 But they do not, so the CPU is within its rights
803 to do significant reordering.
804 This is by design: Any significant ordering constraints would slow down
805 these fast-path APIs.
806
807 <p>@@QQ@@
808 Can't the compiler also reorder this code?
809 <p>@@QQA@@
810 No, the volatile casts in <tt>READ_ONCE()</tt> and
811 <tt>WRITE_ONCE()</tt> prevent the compiler from reordering in
812 this 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>
818 Neither <tt>rcu_read_lock()</tt> nor <tt>rcu_read_unlock()</tt>
819 exclude updates.
820 All they do is to prevent grace periods from ending.
821 The 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 }
834 10 rcu_read_unlock();
835 11 }
836 12
837 13 void thread1(void)
838 14 {
839 15 spin_lock(&amp;my_lock);
840 16 WRITE_ONCE(x, 1);
841 17 WRITE_ONCE(y, 1);
842 18 spin_unlock(&amp;my_lock);
843 19 }
844 </pre>
845 </blockquote>
846
847 <p>
848 If the <tt>thread0()</tt> function's <tt>rcu_read_lock()</tt>
849 excluded the <tt>thread1()</tt> function's update,
850 the <tt>WARN_ON()</tt> could never fire.
851 But the fact is that <tt>rcu_read_lock()</tt> does not exclude
852 much 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>
859 It might be tempting to assume that after <tt>synchronize_rcu()</tt>
860 completes, there are no readers executing.
861 This temptation must be avoided because
862 new readers can start immediately after <tt>synchronize_rcu()</tt>
863 starts, and <tt>synchronize_rcu()</tt> is under no
864 obligation to wait for these new readers.
865
866 <p>@@QQ@@
867 Suppose that synchronize_rcu() did wait until all readers had completed.
868 Would the updater be able to rely on this?
869 <p>@@QQA@@
870 No.
871 Even if <tt>synchronize_rcu()</tt> were to wait until
872 all readers had completed, a new reader might start immediately after
873 <tt>synchronize_rcu()</tt> completed.
874 Therefore, the code following
875 <tt>synchronize_rcu()</tt> cannot rely on there being no readers
876 in any case.
877 <p>@@QQE@@
878
879 <h3><a name="Grace Periods Don't Partition Read-Side Critical Sections">
880 Grace Periods Don't Partition Read-Side Critical Sections</a></h3>
881
882 <p>
883 It is tempting to assume that if any part of one RCU read-side critical
884 section precedes a given grace period, and if any part of another RCU
885 read-side critical section follows that same grace period, then all of
886 the first RCU read-side critical section must precede all of the second.
887 However, this just isn't the case: A single grace period does not
888 partition the set of RCU read-side critical sections.
889 An 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)
903 10 {
904 11 r1 = READ_ONCE(a);
905 12 synchronize_rcu();
906 13 WRITE_ONCE(c, 1);
907 14 }
908 15
909 16 void thread2(void)
910 17 {
911 18 rcu_read_lock();
912 19 r2 = READ_ONCE(b);
913 20 r3 = READ_ONCE(c);
914 21 rcu_read_unlock();
915 22 }
916 </pre>
917 </blockquote>
918
919 <p>
920 It 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
928 is entirely possible.
929 The 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
932 RCU knows that the thread cannot be in the midst of an RCU read-side
933 critical section that started before the current grace period:
934
935 <p><img src="GPpartitionReaders1.svg" alt="GPpartitionReaders1.svg" width="60%"></p>
936
937 <p>
938 If it is necessary to partition RCU read-side critical sections in this
939 manner, it is necessary to use two grace periods, where the first
940 grace 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)
953 10 {
954 11 r1 = READ_ONCE(a);
955 12 synchronize_rcu();
956 13 WRITE_ONCE(c, 1);
957 14 }
958 15
959 16 void thread2(void)
960 17 {
961 18 r2 = READ_ONCE(c);
962 19 synchronize_rcu();
963 20 WRITE_ONCE(d, 1);
964 21 }
965 22
966 23 void thread3(void)
967 24 {
968 25 rcu_read_lock();
969 26 r3 = READ_ONCE(b);
970 27 r4 = READ_ONCE(d);
971 28 rcu_read_unlock();
972 29 }
973 </pre>
974 </blockquote>
975
976 <p>
977 Here, if <tt>(r1 == 1)</tt>, then
978 <tt>thread0()</tt>'s write to <tt>b</tt> must happen
979 before the end of <tt>thread1()</tt>'s grace period.
980 If in addition <tt>(r4 == 1)</tt>, then
981 <tt>thread3()</tt>'s read from <tt>b</tt> must happen
982 after the beginning of <tt>thread2()</tt>'s grace period.
983 If it is also the case that <tt>(r2 == 1)</tt>, then the
984 end of <tt>thread1()</tt>'s grace period must precede the
985 beginning of <tt>thread2()</tt>'s grace period.
986 This mean that the two RCU read-side critical sections cannot overlap,
987 guaranteeing that <tt>(r3 == 1)</tt>.
988 As 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
996 cannot happen.
997
998 <p>
999 This non-requirement was also non-premeditated, but became apparent
1000 when studying RCU's interaction with memory ordering.
1001
1002 <h3><a name="Read-Side Critical Sections Don't Partition Grace Periods">
1003 Read-Side Critical Sections Don't Partition Grace Periods</a></h3>
1004
1005 <p>
1006 It is also tempting to assume that if an RCU read-side critical section
1007 happens between a pair of grace periods, then those grace periods cannot
1008 overlap.
1009 However, this temptation leads nowhere good, as can be illustrated by
1010 the 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)
1023 10 {
1024 11 r1 = READ_ONCE(a);
1025 12 synchronize_rcu();
1026 13 WRITE_ONCE(c, 1);
1027 14 }
1028 15
1029 16 void thread2(void)
1030 17 {
1031 18 rcu_read_lock();
1032 19 WRITE_ONCE(d, 1);
1033 20 r2 = READ_ONCE(c);
1034 21 rcu_read_unlock();
1035 22 }
1036 23
1037 24 void thread3(void)
1038 25 {
1039 26 r3 = READ_ONCE(d);
1040 27 synchronize_rcu();
1041 28 WRITE_ONCE(e, 1);
1042 29 }
1043 30
1044 31 void thread4(void)
1045 32 {
1046 33 rcu_read_lock();
1047 34 r4 = READ_ONCE(b);
1048 35 r5 = READ_ONCE(e);
1049 36 rcu_read_unlock();
1050 37 }
1051 </pre>
1052 </blockquote>
1053
1054 <p>
1055 In 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
1063 is entirely possible, as illustrated below:
1064
1065 <p><img src="ReadersPartitionGP1.svg" alt="ReadersPartitionGP1.svg" width="100%"></p>
1066
1067 <p>
1068 Again, an RCU read-side critical section can overlap almost all of a
1069 given grace period, just so long as it does not overlap the entire
1070 grace period.
1071 As a result, an RCU read-side critical section cannot partition a pair
1072 of RCU grace periods.
1073
1074 <p>@@QQ@@
1075 How long a sequence of grace periods, each separated by an RCU read-side
1076 critical section, would be required to partition the RCU read-side
1077 critical sections at the beginning and end of the chain?
1078 <p>@@QQA@@
1079 In theory, an infinite number.
1080 In practice, an unknown number that is sensitive to both implementation
1081 details and timing considerations.
1082 Therefore, even in practice, RCU users must abide by the theoretical rather
1083 than the practical answer.
1084 <p>@@QQE@@
1085
1086 <h3><a name="Disabling Preemption Does Not Block Grace Periods">
1087 Disabling Preemption Does Not Block Grace Periods</a></h3>
1088
1089 <p>
1090 There was a time when disabling preemption on any given CPU would block
1091 subsequent grace periods.
1092 However, this was an accident of implementation and is not a requirement.
1093 And in the current Linux-kernel implementation, disabling preemption
1094 on 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>
1098 If 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
1100 as 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();
1113 10 do_something();
1114 11 rcu_read_unlock();
1115 12 spin_unlock(&amp;mylock);
1116 </pre>
1117 </blockquote>
1118
1119 <p>
1120 In theory, you could enter the RCU read-side critical section first,
1121 but it is more efficient to keep the entire RCU read-side critical
1122 section contained in the preempt-disable region as shown above.
1123 Of course, RCU read-side critical sections that extend outside of
1124 preempt-disable regions will work correctly, but such critical sections
1125 can be preempted, which forces <tt>rcu_read_unlock()</tt> to do
1126 more work.
1127 And no, this is <i>not</i> an invitation to enclose all of your RCU
1128 read-side critical sections within preempt-disable regions, because
1129 doing so would degrade real-time response.
1130
1131 <p>
1132 This non-requirement appeared with preemptible RCU.
1133 If 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>
1139 These parallelism facts of life are by no means specific to RCU, but
1140 the RCU implementation must abide by them.
1141 They 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>
1192 This last parallelism fact of life means that RCU must pay special
1193 attention to the preceding facts of life.
1194 The idea that Linux might scale to systems with thousands of CPUs would
1195 have been met with some skepticism in the 1990s, but these requirements
1196 would 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>
1201 These sections list quality-of-implementation requirements.
1202 Although an RCU implementation that ignores these requirements could
1203 still be used, it would likely be subject to limitations that would
1204 make it inappropriate for industrial-strength production use.
1205 Classes 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>
1215 These classes is covered in the following sections.
1216
1217 <h3><a name="Specialization">Specialization</a></h3>
1218
1219 <p>
1220 RCU is and always has been intended primarily for read-mostly situations, as
1221 illustrated by the following figure.
1222 This means that RCU's read-side primitives are optimized, often at the
1223 expense of its update-side primitives.
1224
1225 <p><img src="RCUApplicability.svg" alt="RCUApplicability.svg" width="70%"></p>
1226
1227 <p>
1228 This focus on read-mostly situations means that RCU must interoperate
1229 with other synchronization primitives.
1230 For example, the <tt>add_gp()</tt> and <tt>remove_gp_synchronous()</tt>
1231 examples discussed earlier use RCU to protect readers and locking to
1232 coordinate updaters.
1233 However, the need extends much farther, requiring that a variety of
1234 synchronization primitives be legal within RCU read-side critical sections,
1235 including spinlocks, sequence locks, atomic operations, reference
1236 counters, and memory barriers.
1237
1238 <p>@@QQ@@
1239 What about sleeping locks?
1240 <p>@@QQA@@
1241 These are forbidden within Linux-kernel RCU read-side critical sections
1242 because it is not legal to place a quiescent state (in this case,
1243 voluntary context switch) within an RCU read-side critical section.
1244 However, sleeping locks may be used within userspace RCU read-side critical
1245 sections, and also within Linux-kernel sleepable RCU
1246 <a href="#Sleepable RCU">(SRCU)</a>
1247 read-side critical sections.
1248 In addition, the -rt patchset turns spinlocks into a sleeping locks so
1249 that the corresponding critical sections can be preempted, which
1250 also means that these sleeplockified spinlocks (but not other sleeping locks!)
1251 may be acquire within -rt-Linux-kernel RCU read-side critical sections.
1252
1253 <p>
1254 Note that it <i>is</i> legal for a normal RCU read-side critical section
1255 to conditionally acquire a sleeping locks (as in <tt>mutex_trylock()</tt>),
1256 but only as long as it does not loop indefinitely attempting to
1257 conditionally acquire that sleeping locks.
1258 The key point is that things like <tt>mutex_trylock()</tt>
1259 either return with the mutex held, or return an error indication if
1260 the mutex was not immediately available.
1261 Either way, <tt>mutex_trylock()</tt> returns immediately without sleeping.
1262 <p>@@QQE@@
1263
1264 <p>
1265 It often comes as a surprise that many algorithms do not require a
1266 consistent view of data, but many can function in that mode,
1267 with network routing being the poster child.
1268 Internet routing algorithms take significant time to propagate
1269 updates, so that by the time an update arrives at a given system,
1270 that system has been sending network traffic the wrong way for
1271 a considerable length of time.
1272 Having a few threads continue to send traffic the wrong way for a
1273 few more milliseconds is clearly not a problem: In the worst case,
1274 TCP retransmissions will eventually get the data where it needs to go.
1275 In general, when tracking the state of the universe outside of the
1276 computer, some level of inconsistency must be tolerated due to
1277 speed-of-light delays if nothing else.
1278
1279 <p>
1280 Furthermore, uncertainty about external state is inherent in many cases.
1281 For example, a pair of veternarians might use heartbeat to determine
1282 whether or not a given cat was alive.
1283 But how long should they wait after the last heartbeat to decide that
1284 the cat is in fact dead?
1285 Waiting less than 400 milliseconds makes no sense because this would
1286 mean that a relaxed cat would be considered to cycle between death
1287 and life more than 100 times per minute.
1288 Moreover, just as with human beings, a cat's heart might stop for
1289 some period of time, so the exact wait period is a judgment call.
1290 One of our pair of veternarians might wait 30 seconds before pronouncing
1291 the cat dead, while the other might insist on waiting a full minute.
1292 The two veternarians would then disagree on the state of the cat during
1293 the final 30 seconds of the minute following the last heartbeat, as
1294 fancifully 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>
1299 Interestingly enough, this same situation applies to hardware.
1300 When push comes to shove, how do we tell whether or not some
1301 external server has failed?
1302 We send messages to it periodically, and declare it failed if we
1303 don't receive a response within a given period of time.
1304 Policy decisions can usually tolerate short
1305 periods of inconsistency.
1306 The policy was decided some time ago, and is only now being put into
1307 effect, so a few milliseconds of delay is normally inconsequential.
1308
1309 <p>
1310 However, there are algorithms that absolutely must see consistent data.
1311 For example, the translation between a user-level SystemV semaphore
1312 ID to the corresponding in-kernel data structure is protected by RCU,
1313 but it is absolutely forbidden to update a semaphore that has just been
1314 removed.
1315 In the Linux kernel, this need for consistency is accommodated by acquiring
1316 spinlocks located in the in-kernel data structure from within
1317 the RCU read-side critical section, and this is indicated by the
1318 green box in the figure above.
1319 Many other techniques may be used, and are in fact used within the
1320 Linux kernel.
1321
1322 <p>
1323 In short, RCU is not required to maintain consistency, and other
1324 mechanisms may be used in concert with RCU when consistency is required.
1325 RCU's specialization allows it to do its job extremely well, and its
1326 ability to interoperate with other synchronization mechanisms allows
1327 the 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>
1332 Energy efficiency is a critical component of performance today,
1333 and Linux-kernel RCU implementations must therefore avoid unnecessarily
1334 awakening idle CPUs.
1335 I cannot claim that this requirement was premeditated.
1336 In fact, I learned of it during a telephone conversation in which I
1337 was given &ldquo;frank and open&rdquo; feedback on the importance
1338 of energy efficiency in battery-powered systems and on specific
1339 energy-efficiency shortcomings of the Linux-kernel RCU implementation.
1340 In my experience, the battery-powered embedded community will consider
1341 any unnecessary wakeups to be extremely unfriendly acts.
1342 So much so that mere Linux-kernel-mailing-list posts are
1343 insufficient to vent their ire.
1344
1345 <p>
1346 Memory consumption is not particularly important for in most
1347 situations, and has become decreasingly
1348 so as memory sizes have expanded and memory
1349 costs have plummeted.
1350 However, as I learned from Matt Mackall's
1351 <a href="http://elinux.org/Linux_Tiny-FAQ">bloatwatch</a>
1352 efforts, memory footprint is critically important on single-CPU systems with
1353 non-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>
1355 was born.
1356 Josh Triplett has since taken over the small-memory banner with his
1357 <a href="https://tiny.wiki.kernel.org/">Linux kernel tinification</a>
1358 project, which resulted in
1359 <a href="#Sleepable RCU">SRCU</a>
1360 becoming optional for those kernels not needing it.
1361
1362 <p>
1363 The remaining performance requirements are, for the most part,
1364 unsurprising.
1365 For example, in keeping with RCU's read-side specialization,
1366 <tt>rcu_dereference()</tt> should have negligible overhead (for
1367 example, suppression of a few minor compiler optimizations).
1368 Similarly, in non-preemptible environments, <tt>rcu_read_lock()</tt> and
1369 <tt>rcu_read_unlock()</tt> should have exactly zero overhead.
1370
1371 <p>
1372 In preemptible environments, in the case where the RCU read-side
1373 critical section was not preempted (as will be the case for the
1374 highest-priority real-time process), <tt>rcu_read_lock()</tt> and
1375 <tt>rcu_read_unlock()</tt> should have minimal overhead.
1376 In particular, they should not contain atomic read-modify-write
1377 operations, memory-barrier instructions, preemption disabling,
1378 interrupt disabling, or backwards branches.
1379 However, in the case where the RCU read-side critical section was preempted,
1380 <tt>rcu_read_unlock()</tt> may acquire spinlocks and disable interrupts.
1381 This is why it is better to nest an RCU read-side critical section
1382 within a preempt-disable region than vice versa, at least in cases
1383 where that critical section is short enough to avoid unduly degrading
1384 real-time latencies.
1385
1386 <p>
1387 The <tt>synchronize_rcu()</tt> grace-period-wait primitive is
1388 optimized for throughput.
1389 It may therefore incur several milliseconds of latency in addition to
1390 the duration of the longest RCU read-side critical section.
1391 On the other hand, multiple concurrent invocations of
1392 <tt>synchronize_rcu()</tt> are required to use batching optimizations
1393 so that they can be satisfied by a single underlying grace-period-wait
1394 operation.
1395 For example, in the Linux kernel, it is not unusual for a single
1396 grace-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>
1398 of <tt>synchronize_rcu()</tt>, thus amortizing the per-invocation
1399 overhead down to nearly zero.
1400 However, the grace-period optimization is also required to avoid
1401 measurable degradation of real-time scheduling and interrupt latencies.
1402
1403 <p>
1404 In some cases, the multi-millisecond <tt>synchronize_rcu()</tt>
1405 latencies are unacceptable.
1406 In these cases, <tt>synchronize_rcu_expedited()</tt> may be used
1407 instead, reducing the grace-period latency down to a few tens of
1408 microseconds on small systems, at least in cases where the RCU read-side
1409 critical sections are short.
1410 There are currently no special latency requirements for
1411 <tt>synchronize_rcu_expedited()</tt> on large systems, but,
1412 consistent with the empirical nature of the RCU specification,
1413 that is subject to change.
1414 However, there most definitely are scalability requirements:
1415 A storm of <tt>synchronize_rcu_expedited()</tt> invocations on 4096
1416 CPUs should at least make reasonable forward progress.
1417 In return for its shorter latencies, <tt>synchronize_rcu_expedited()</tt>
1418 is permitted to impose modest degradation of real-time latency
1419 on non-idle online CPUs.
1420 That said, it will likely be necessary to take further steps to reduce this
1421 degradation, hopefully to roughly that of a scheduling-clock interrupt.
1422
1423 <p>
1424 There are a number of situations where even
1425 <tt>synchronize_rcu_expedited()</tt>'s reduced grace-period
1426 latency is unacceptable.
1427 In these situations, the asynchronous <tt>call_rcu()</tt> can be
1428 used 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);
1441 10
1442 11 kfree(p);
1443 12 }
1444 13
1445 14 bool remove_gp_asynchronous(void)
1446 15 {
1447 16 struct foo *p;
1448 17
1449 18 spin_lock(&amp;gp_lock);
1450 19 p = rcu_dereference(gp);
1451 20 if (!p) {
1452 21 spin_unlock(&amp;gp_lock);
1453 22 return false;
1454 23 }
1455 24 rcu_assign_pointer(gp, NULL);
1456 25 call_rcu(&amp;p-&gt;rh, remove_gp_cb);
1457 26 spin_unlock(&amp;gp_lock);
1458 27 return true;
1459 28 }
1460 </pre>
1461 </blockquote>
1462
1463 <p>
1464 A definition of <tt>struct foo</tt> is finally needed, and appears
1465 on lines&nbsp;1-5.
1466 The function <tt>remove_gp_cb()</tt> is passed to <tt>call_rcu()</tt>
1467 on line&nbsp;25, and will be invoked after the end of a subsequent
1468 grace period.
1469 This gets the same effect as <tt>remove_gp_synchronous()</tt>,
1470 but without forcing the updater to wait for a grace period to elapse.
1471 The <tt>call_rcu()</tt> function may be used in a number of
1472 situations where neither <tt>synchronize_rcu()</tt> nor
1473 <tt>synchronize_rcu_expedited()</tt> would be legal,
1474 including within preempt-disable code, <tt>local_bh_disable()</tt> code,
1475 interrupt-disable code, and interrupt handlers.
1476 However, even <tt>call_rcu()</tt> is illegal within NMI handlers.
1477 The callback function (<tt>remove_gp_cb()</tt> in this case) will be
1478 executed within softirq (software interrupt) environment within the
1479 Linux kernel,
1480 either within a real softirq handler or under the protection
1481 of <tt>local_bh_disable()</tt>.
1482 In both the Linux kernel and in userspace, it is bad practice to
1483 write an RCU callback function that takes too long.
1484 Long-running operations should be relegated to separate threads or
1485 (in the Linux kernel) workqueues.
1486
1487 <p>@@QQ@@
1488 Why does line&nbsp;19 use <tt>rcu_access_pointer()</tt>?
1489 After all, <tt>call_rcu()</tt> on line&nbsp;25 stores into the
1490 structure, which would interact badly with concurrent insertions.
1491 Doesn't this mean that <tt>rcu_dereference()</tt> is required?
1492 <p>@@QQA@@
1493 Presumably the <tt>-&gt;gp_lock</tt> acquired on line&nbsp;18 excludes
1494 any changes, including any insertions that <tt>rcu_dereference()</tt>
1495 would protect against.
1496 Therefore, any insertions will be delayed until after <tt>-&gt;gp_lock</tt>
1497 is released on line&nbsp;25, which in turn means that
1498 <tt>rcu_access_pointer()</tt> suffices.
1499 <p>@@QQE@@
1500
1501 <p>
1502 However, all that <tt>remove_gp_cb()</tt> is doing is
1503 invoking <tt>kfree()</tt> on the data element.
1504 This is a common idiom, and is supported by <tt>kfree_rcu()</tt>,
1505 which 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;
1518 10
1519 11 spin_lock(&amp;gp_lock);
1520 12 p = rcu_dereference(gp);
1521 13 if (!p) {
1522 14 spin_unlock(&amp;gp_lock);
1523 15 return false;
1524 16 }
1525 17 rcu_assign_pointer(gp, NULL);
1526 18 kfree_rcu(p, rh);
1527 19 spin_unlock(&amp;gp_lock);
1528 20 return true;
1529 21 }
1530 </pre>
1531 </blockquote>
1532
1533 <p>
1534 Note that <tt>remove_gp_faf()</tt> simply invokes
1535 <tt>kfree_rcu()</tt> and proceeds, without any need to pay any
1536 further attention to the subsequent grace period and <tt>kfree()</tt>.
1537 It is permissible to invoke <tt>kfree_rcu()</tt> from the same
1538 environments as for <tt>call_rcu()</tt>.
1539 Interestingly enough, DYNIX/ptx had the equivalents of
1540 <tt>call_rcu()</tt> and <tt>kfree_rcu()</tt>, but not
1541 <tt>synchronize_rcu()</tt>.
1542 This was due to the fact that RCU was not heavily used within DYNIX/ptx,
1543 so the very few places that needed something like
1544 <tt>synchronize_rcu()</tt> simply open-coded it.
1545
1546 <p>@@QQ@@
1547 Earlier it was claimed that <tt>call_rcu()</tt> and
1548 <tt>kfree_rcu()</tt> allowed updaters to avoid being blocked
1549 by readers.
1550 But how can that be correct, given that the invocation of the callback
1551 and the freeing of the memory (respectively) must still wait for
1552 a grace period to elapse?
1553 <p>@@QQA@@
1554 We could define things this way, but keep in mind that this sort of
1555 definition would say that updates in garbage-collected languages
1556 cannot complete until the next time the garbage collector runs,
1557 which does not seem at all reasonable.
1558 The 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
1560 next update as soon as it has invoked <tt>call_rcu()</tt> or
1561 <tt>kfree_rcu()</tt>, without having to wait for a subsequent
1562 grace period.
1563 <p>@@QQE@@
1564
1565 <p>
1566 But what if the updater must wait for the completion of code to be
1567 executed after the end of the grace period, but has other tasks
1568 that can be carried out in the meantime?
1569 The polling-style <tt>get_state_synchronize_rcu()</tt> and
1570 <tt>cond_synchronize_rcu()</tt> functions may be used for this
1571 purpose, 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);
1584 10 return false;
1585 11 }
1586 12 rcu_assign_pointer(gp, NULL);
1587 13 spin_unlock(&amp;gp_lock);
1588 14 s = get_state_synchronize_rcu();
1589 15 do_something_while_waiting();
1590 16 cond_synchronize_rcu(s);
1591 17 kfree(p);
1592 18 return true;
1593 19 }
1594 </pre>
1595 </blockquote>
1596
1597 <p>
1598 On line&nbsp;14, <tt>get_state_synchronize_rcu()</tt> obtains a
1599 &ldquo;cookie&rdquo; from RCU,
1600 then line&nbsp;15 carries out other tasks,
1601 and finally, line&nbsp;16 returns immediately if a grace period has
1602 elapsed in the meantime, but otherwise waits as required.
1603 The need for <tt>get_state_synchronize_rcu</tt> and
1604 <tt>cond_synchronize_rcu()</tt> has appeared quite recently,
1605 so it is too early to tell whether they will stand the test of time.
1606
1607 <p>
1608 RCU thus provides a range of tools to allow updaters to strike the
1609 required tradeoff between latency, flexibility and CPU overhead.
1610
1611 <h3><a name="Composability">Composability</a></h3>
1612
1613 <p>
1614 Composability has received much attention in recent years, perhaps in part
1615 due to the collision of multicore hardware with object-oriented techniques
1616 designed in single-threaded environments for single-threaded use.
1617 And in theory, RCU read-side critical sections may be composed, and in
1618 fact may be nested arbitrarily deeply.
1619 In practice, as with all real-world implementations of composable
1620 constructs, there are limitations.
1621
1622 <p>
1623 Implementations of RCU for which <tt>rcu_read_lock()</tt>
1624 and <tt>rcu_read_unlock()</tt> generate no code, such as
1625 Linux-kernel RCU when <tt>CONFIG_PREEMPT=n</tt>, can be
1626 nested arbitrarily deeply.
1627 After all, there is no overhead.
1628 Except that if all these instances of <tt>rcu_read_lock()</tt>
1629 and <tt>rcu_read_unlock()</tt> are visible to the compiler,
1630 compilation will eventually fail due to exhausting memory,
1631 mass storage, or user patience, whichever comes first.
1632 If the nesting is not visible to the compiler, as is the case with
1633 mutually recursive functions each in its own translation unit,
1634 stack overflow will result.
1635 If the nesting takes the form of loops, either the control variable
1636 will overflow or (in the Linux kernel) you will get an RCU CPU stall warning.
1637 Nevertheless, this class of RCU implementations is one
1638 of the most composable constructs in existence.
1639
1640 <p>
1641 RCU implementations that explicitly track nesting depth
1642 are limited by the nesting-depth counter.
1643 For example, the Linux kernel's preemptible RCU limits nesting to
1644 <tt>INT_MAX</tt>.
1645 This should suffice for almost all practical purposes.
1646 That said, a consecutive pair of RCU read-side critical sections
1647 between which there is an operation that waits for a grace period
1648 cannot be enclosed in another RCU read-side critical section.
1649 This is because it is not legal to wait for a grace period within
1650 an RCU read-side critical section: To do so would result either
1651 in deadlock or
1652 in RCU implicitly splitting the enclosing RCU read-side critical
1653 section, neither of which is conducive to a long-lived and prosperous
1654 kernel.
1655
1656 <p>
1657 It is worth noting that RCU is not alone in limiting composability.
1658 For example, many transactional-memory implementations prohibit
1659 composing a pair of transactions separated by an irrevocable
1660 operation (for example, a network receive operation).
1661 For another example, lock-based critical sections can be composed
1662 surprisingly freely, but only if deadlock is avoided.
1663
1664 <p>
1665 In short, although RCU read-side critical sections are highly composable,
1666 care is required in some situations, just as is the case for any other
1667 composable synchronization mechanism.
1668
1669 <h3><a name="Corner Cases">Corner Cases</a></h3>
1670
1671 <p>
1672 A given RCU workload might have an endless and intense stream of
1673 RCU read-side critical sections, perhaps even so intense that there
1674 was never a point in time during which there was not at least one
1675 RCU read-side critical section in flight.
1676 RCU cannot allow this situation to block grace periods: As long as
1677 all the RCU read-side critical sections are finite, grace periods
1678 must also be finite.
1679
1680 <p>
1681 That said, preemptible RCU implementations could potentially result
1682 in RCU read-side critical sections being preempted for long durations,
1683 which has the effect of creating a long-duration RCU read-side
1684 critical section.
1685 This situation can arise only in heavily loaded systems, but systems using
1686 real-time priorities are of course more vulnerable.
1687 Therefore, RCU priority boosting is provided to help deal with this
1688 case.
1689 That said, the exact requirements on RCU priority boosting will likely
1690 evolve as more experience accumulates.
1691
1692 <p>
1693 Other workloads might have very high update rates.
1694 Although one can argue that such workloads should instead use
1695 something other than RCU, the fact remains that RCU must
1696 handle such workloads gracefully.
1697 This requirement is another factor driving batching of grace periods,
1698 but it is also the driving force behind the checks for large numbers
1699 of queued RCU callbacks in the <tt>call_rcu()</tt> code path.
1700 Finally, high update rates should not delay RCU read-side critical
1701 sections, although some read-side delays can occur when using
1702 <tt>synchronize_rcu_expedited()</tt>, courtesy of this function's use
1703 of <tt>try_stop_cpus()</tt>.
1704 (In the future, <tt>synchronize_rcu_expedited()</tt> will be
1705 converted to use lighter-weight inter-processor interrupts (IPIs),
1706 but this will still disturb readers, though to a much smaller degree.)
1707
1708 <p>
1709 Although all three of these corner cases were understood in the early
1710 1990s, a simple user-level test consisting of <tt>close(open(path))</tt>
1711 in a tight loop
1712 in the early 2000s suddenly provided a much deeper appreciation of the
1713 high-update-rate corner case.
1714 This test also motivated addition of some RCU code to react to high update
1715 rates, for example, if a given CPU finds itself with more than 10,000
1716 RCU callbacks queued, it will cause RCU to take evasive action by
1717 more aggressively starting grace periods and more aggressively forcing
1718 completion of grace-period processing.
1719 This evasive action causes the grace period to complete more quickly,
1720 but at the cost of restricting RCU's batching optimizations, thus
1721 increasing the CPU overhead incurred by that grace period.
1722
1723 <h2><a name="Software-Engineering Requirements">
1724 Software-Engineering Requirements</a></h2>
1725
1726 <p>
1727 Between Murphy's Law and &ldquo;To err is human&rdquo;, it is necessary to
1728 guard 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
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.
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.
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>
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.
1815 That said, the initial implementation in DYNIX/ptx was quite
1816 generic in comparison with that of Linux.
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>
1849 This not a hard-and-fast list: RCU's diagnostic capabilities will
1850 continue to be guided by the number and type of usage bugs found
1851 in real-world RCU usage.
1852
1853 <h2><a name="Linux Kernel Complications">Linux Kernel Complications</a></h2>
1854
1855 <p>
1856 The Linux kernel provides an interesting environment for all kinds of
1857 software, including RCU.
1858 Some 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>.
1871 <li> <a href="#Memory Efficiency">Memory Efficiency</a>.
1872 <li> <a href="#Performance, Scalability, Response Time, and Reliability">
1873 Performance, Scalability, Response Time, and Reliability</a>.
1874 </ol>
1875
1876 <p>
1877 This list is probably incomplete, but it does give a feel for the
1878 most notable Linux-kernel complications.
1879 Each of the following sections covers one of the above topics.
1880
1881 <h3><a name="Configuration">Configuration</a></h3>
1882
1883 <p>
1884 RCU's goal is automatic configuration, so that almost nobody
1885 needs to worry about RCU's <tt>Kconfig</tt> options.
1886 And for almost all users, RCU does in fact work well
1887 &ldquo;out of the box.&rdquo;
1888
1889 <p>
1890 However, there are specialized use cases that are handled by
1891 kernel boot parameters and <tt>Kconfig</tt> options.
1892 Unfortunately, the <tt>Kconfig</tt> system will explicitly ask users
1893 about new <tt>Kconfig</tt> options, which requires almost all of them
1894 be hidden behind a <tt>CONFIG_RCU_EXPERT</tt> <tt>Kconfig</tt> option.
1895
1896 <p>
1897 This all should be quite obvious, but the fact remains that
1898 Linus Torvalds recently had to
1899 <a href="https://lkml.kernel.org/g/CA+55aFy4wcCwaL4okTs8wXhGZ5h-ibecy_Meg9C4MNQrUnwMcg@mail.gmail.com">remind</a>
1900 me of this requirement.
1901
1902 <h3><a name="Firmware Interface">Firmware Interface</a></h3>
1903
1904 <p>
1905 In many cases, kernel obtains information about the system from the
1906 firmware, and sometimes things are lost in translation.
1907 Or the translation is accurate, but the original message is bogus.
1908
1909 <p>
1910 For example, some systems' firmware overreports the number of CPUs,
1911 sometimes by a large factor.
1912 If RCU naively believed the firmware, as it used to do,
1913 it would create too many per-CPU kthreads.
1914 Although the resulting system will still run correctly, the extra
1915 kthreads needlessly consume memory and can cause confusion
1916 when they show up in <tt>ps</tt> listings.
1917
1918 <p>
1919 RCU must therefore wait for a given CPU to actually come online before
1920 it can allow itself to believe that the CPU actually exists.
1921 The resulting &ldquo;ghost CPUs&rdquo; (which are never going to
1922 come 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>
1928 The Linux kernel's boot sequence is an interesting process,
1929 and RCU is used early, even before <tt>rcu_init()</tt>
1930 is invoked.
1931 In fact, a number of RCU's primitives can be used as soon as the
1932 initial task's <tt>task_struct</tt> is available and the
1933 boot CPU's per-CPU variables are set up.
1934 The read-side primitives (<tt>rcu_read_lock()</tt>,
1935 <tt>rcu_read_unlock()</tt>, <tt>rcu_dereference()</tt>,
1936 and <tt>rcu_access_pointer()</tt>) will operate normally very early on,
1937 as will <tt>rcu_assign_pointer()</tt>.
1938
1939 <p>
1940 Although <tt>call_rcu()</tt> may be invoked at any
1941 time during boot, callbacks are not guaranteed to be invoked until after
1942 the scheduler is fully up and running.
1943 This delay in callback invocation is due to the fact that RCU does not
1944 invoke callbacks until it is fully initialized, and this full initialization
1945 cannot occur until after the scheduler has initialized itself to the
1946 point where RCU can spawn and run its kthreads.
1947 In theory, it would be possible to invoke callbacks earlier,
1948 however, this is not a panacea because there would be severe restrictions
1949 on what operations those callbacks could invoke.
1950
1951 <p>
1952 Perhaps 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>),
1955 and
1956 <a href="#Sched Flavor"><tt>synchronize_sched()</tt></a>
1957 will all operate normally
1958 during very early boot, the reason being that there is only one CPU
1959 and preemption is disabled.
1960 This means that the call <tt>synchronize_rcu()</tt> (or friends)
1961 itself is a quiescent
1962 state and thus a grace period, so the early-boot implementation can
1963 be a no-op.
1964
1965 <p>
1966 Both <tt>synchronize_rcu_bh()</tt> and <tt>synchronize_sched()</tt>
1967 continue to operate normally through the remainder of boot, courtesy
1968 of the fact that preemption is disabled across their RCU read-side
1969 critical sections and also courtesy of the fact that there is still
1970 only one CPU.
1971 However, once the scheduler starts initializing, preemption is enabled.
1972 There is still only a single CPU, but the fact that preemption is enabled
1973 means that the no-op implementation of <tt>synchronize_rcu()</tt> no
1974 longer works in <tt>CONFIG_PREEMPT=y</tt> kernels.
1975 Therefore, as soon as the scheduler starts initializing, the early-boot
1976 fastpath is disabled.
1977 This means that <tt>synchronize_rcu()</tt> switches to its runtime
1978 mode of operation where it posts callbacks, which in turn means that
1979 any call to <tt>synchronize_rcu()</tt> will block until the corresponding
1980 callback is invoked.
1981 Unfortunately, the callback cannot be invoked until RCU's runtime
1982 grace-period machinery is up and running, which cannot happen until
1983 the scheduler has initialized itself sufficiently to allow RCU's
1984 kthreads to be spawned.
1985 Therefore, invoking <tt>synchronize_rcu()</tt> during scheduler
1986 initialization can result in deadlock.
1987
1988 <p>@@QQ@@
1989 So what happens with <tt>synchronize_rcu()</tt> during
1990 scheduler initialization for <tt>CONFIG_PREEMPT=n</tt>
1991 kernels?
1992 <p>@@QQA@@
1993 In <tt>CONFIG_PREEMPT=n</tt> kernel, <tt>synchronize_rcu()</tt>
1994 maps directly to <tt>synchronize_sched()</tt>.
1995 Therefore, <tt>synchronize_rcu()</tt> works normally throughout
1996 boot in <tt>CONFIG_PREEMPT=n</tt> kernels.
1997 However, your code must also work in <tt>CONFIG_PREEMPT=y</tt> kernels,
1998 so it is still necessary to avoid invoking <tt>synchronize_rcu()</tt>
1999 during scheduler initialization.
2000 <p>@@QQE@@
2001
2002 <p>
2003 I learned of these boot-time requirements as a result of a series of
2004 system hangs.
2005
2006 <h3><a name="Interrupts and NMIs">Interrupts and NMIs</a></h3>
2007
2008 <p>
2009 The Linux kernel has interrupts, and RCU read-side critical sections are
2010 legal within interrupt handlers and within interrupt-disabled regions
2011 of code, as are invocations of <tt>call_rcu()</tt>.
2012
2013 <p>
2014 Some Linux-kernel architectures can enter an interrupt handler from
2015 non-idle process context, and then just never leave it, instead stealthily
2016 transitioning back to process context.
2017 This trick is sometimes used to invoke system calls from inside the kernel.
2018 These &ldquo;half-interrupts&rdquo; mean that RCU has to be very careful
2019 about how it counts interrupt nesting levels.
2020 I learned of this requirement the hard way during a rewrite
2021 of RCU's dyntick-idle code.
2022
2023 <p>
2024 The Linux kernel has non-maskable interrupts (NMIs), and
2025 RCU read-side critical sections are legal within NMI handlers.
2026 Thankfully, RCU update-side primitives, including
2027 <tt>call_rcu()</tt>, are prohibited within NMI handlers.
2028
2029 <p>
2030 The name notwithstanding, some Linux-kernel architectures
2031 can have nested NMIs, which RCU must handle correctly.
2032 Andy Lutomirski
2033 <a href="https://lkml.kernel.org/g/CALCETrXLq1y7e_dKFPgou-FKHB6Pu-r8+t-6Ds+8=va7anBWDA@mail.gmail.com">surprised me</a>
2034 with this requirement;
2035 he also kindly surprised me with
2036 <a href="https://lkml.kernel.org/g/CALCETrXSY9JpW3uE6H8WYk81sg56qasA2aqmjMPsq5dOtzso=g@mail.gmail.com">an algorithm</a>
2037 that meets this requirement.
2038
2039 <h3><a name="Loadable Modules">Loadable Modules</a></h3>
2040
2041 <p>
2042 The Linux kernel has loadable modules, and these modules can
2043 also be unloaded.
2044 After a given module has been unloaded, any attempt to call
2045 one of its functions results in a segmentation fault.
2046 The module-unload functions must therefore cancel any
2047 delayed calls to loadable-module functions, for example,
2048 any outstanding <tt>mod_timer()</tt> must be dealt with
2049 via <tt>del_timer_sync()</tt> or similar.
2050
2051 <p>
2052 Unfortunately, there is no way to cancel an RCU callback;
2053 once you invoke <tt>call_rcu()</tt>, the callback function is
2054 going to eventually be invoked, unless the system goes down first.
2055 Because it is normally considered socially irresponsible to crash the system
2056 in response to a module unload request, we need some other way
2057 to deal with in-flight RCU callbacks.
2058
2059 <p>
2060 RCU therefore provides
2061 <tt><a href="https://lwn.net/Articles/217484/">rcu_barrier()</a></tt>,
2062 which waits until all in-flight RCU callbacks have been invoked.
2063 If a module uses <tt>call_rcu()</tt>, its exit function should therefore
2064 prevent any future invocation of <tt>call_rcu()</tt>, then invoke
2065 <tt>rcu_barrier()</tt>.
2066 In theory, the underlying module-unload code could invoke
2067 <tt>rcu_barrier()</tt> unconditionally, but in practice this would
2068 incur unacceptable latencies.
2069
2070 <p>
2071 Nikita Danilov noted this requirement for an analogous filesystem-unmount
2072 situation, and Dipankar Sarma incorporated <tt>rcu_barrier()</tt> into RCU.
2073 The need for <tt>rcu_barrier()</tt> for module unloading became
2074 apparent later.
2075
2076 <h3><a name="Hotplug CPU">Hotplug CPU</a></h3>
2077
2078 <p>
2079 The Linux kernel supports CPU hotplug, which means that CPUs
2080 can come and go.
2081 It is of course illegal to use any RCU API member from an offline CPU.
2082 This requirement was present from day one in DYNIX/ptx, but
2083 on the other hand, the Linux kernel's CPU-hotplug implementation
2084 is &ldquo;interesting.&rdquo;
2085
2086 <p>
2087 The Linux-kernel CPU-hotplug implementation has notifiers that
2088 are used to allow the various kernel subsystems (including RCU)
2089 to respond appropriately to a given CPU-hotplug operation.
2090 Most RCU operations may be invoked from CPU-hotplug notifiers,
2091 including even normal synchronous grace-period operations
2092 such as <tt>synchronize_rcu()</tt>.
2093 However, expedited grace-period operations such as
2094 <tt>synchronize_rcu_expedited()</tt> are not supported,
2095 due to the fact that current implementations block CPU-hotplug
2096 operations, which could result in deadlock.
2097
2098 <p>
2099 In addition, all-callback-wait operations such as
2100 <tt>rcu_barrier()</tt> are also not supported, due to the
2101 fact that there are phases of CPU-hotplug operations where
2102 the outgoing CPU's callbacks will not be invoked until after
2103 the 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>
2108 RCU depends on the scheduler, and the scheduler uses RCU to
2109 protect some of its data structures.
2110 This means the scheduler is forbidden from acquiring
2111 the runqueue locks and the priority-inheritance locks
2112 in the middle of an outermost RCU read-side critical section unless either
2113 (1)&nbsp;it releases them before exiting that same
2114 RCU read-side critical section, or
2115 (2)&nbsp;preemption is disabled across
2116 that entire RCU read-side critical section.
2117 This same prohibition also applies (recursively!) to any lock that is acquired
2118 while holding any lock to which this prohibition applies.
2119 Adhering to this rule prevents preemptible RCU from invoking
2120 <tt>rcu_read_unlock_special()</tt> while either runqueue or
2121 priority-inheritance locks are held, thus avoiding deadlock.
2122
2123 <p>
2124 For RCU's part, the preemptible-RCU <tt>rcu_read_unlock()</tt>
2125 implementation must be written carefully to avoid similar deadlocks.
2126 In particular, <tt>rcu_read_unlock()</tt> must tolerate an
2127 interrupt where the interrupt handler invokes both
2128 <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>.
2129 This possibility requires <tt>rcu_read_unlock()</tt> to use
2130 negative nesting levels to avoid destructive recursion via
2131 interrupt handler's use of RCU.
2132
2133 <p>
2134 This pair of mutual scheduler-RCU requirements came as a
2135 <a href="https://lwn.net/Articles/453002/">complete surprise</a>.
2136
2137 <p>
2138 As noted above, RCU makes use of kthreads, and it is necessary to
2139 avoid excessive CPU-time accumulation by these kthreads.
2140 This requirement was no surprise, but RCU's violation of it
2141 when running context-switch-heavy workloads when built with
2142 <tt>CONFIG_NO_HZ_FULL=y</tt>
2143 <a href="http://www.rdrop.com/users/paulmck/scalability/paper/BareMetal.2015.01.15b.pdf">did come as a surprise [PDF]</a>.
2144 RCU has made good progress towards meeting this requirement, even
2145 for context-switch-have <tt>CONFIG_NO_HZ_FULL=y</tt> workloads,
2146 but there is room for further improvement.
2147
2148 <h3><a name="Tracing and RCU">Tracing and RCU</a></h3>
2149
2150 <p>
2151 It is possible to use tracing on RCU code, but tracing itself
2152 uses RCU.
2153 For this reason, <tt>rcu_dereference_raw_notrace()</tt>
2154 is provided for use by tracing, which avoids the destructive
2155 recursion that could otherwise ensue.
2156 This API is also used by virtualization in some architectures,
2157 where RCU readers execute in environments in which tracing
2158 cannot be used.
2159 The tracing folks both located the requirement and provided the
2160 needed fix, so this surprise requirement was relatively painless.
2161
2162 <h3><a name="Energy Efficiency">Energy Efficiency</a></h3>
2163
2164 <p>
2165 Interrupting idle CPUs is considered socially unacceptable,
2166 especially by people with battery-powered embedded systems.
2167 RCU therefore conserves energy by detecting which CPUs are
2168 idle, including tracking CPUs that have been interrupted from idle.
2169 This is a large part of the energy-efficiency requirement,
2170 so I learned of this via an irate phone call.
2171
2172 <p>
2173 Because RCU avoids interrupting idle CPUs, it is illegal to
2174 execute an RCU read-side critical section on an idle CPU.
2175 (Kernels built with <tt>CONFIG_PROVE_RCU=y</tt> will splat
2176 if you try it.)
2177 The <tt>RCU_NONIDLE()</tt> macro and <tt>_rcuidle</tt>
2178 event tracing is provided to work around this restriction.
2179 In addition, <tt>rcu_is_watching()</tt> may be used to
2180 test whether or not it is currently legal to run RCU read-side
2181 critical sections on this CPU.
2182 I learned of the need for diagnostics on the one hand
2183 and <tt>RCU_NONIDLE()</tt> on the other while inspecting
2184 idle-loop code.
2185 Steven Rostedt supplied <tt>_rcuidle</tt> event tracing,
2186 which is used quite heavily in the idle loop.
2187
2188 <p>
2189 It is similarly socially unacceptable to interrupt an
2190 <tt>nohz_full</tt> CPU running in userspace.
2191 RCU must therefore track <tt>nohz_full</tt> userspace
2192 execution.
2193 And in
2194 <a href="https://lwn.net/Articles/558284/"><tt>CONFIG_NO_HZ_FULL_SYSIDLE=y</tt></a>
2195 kernels, RCU must separately track idle CPUs on the one hand and
2196 CPUs that are either idle or executing in userspace on the other.
2197 In both cases, RCU must be able to sample state at two points in
2198 time, and be able to determine whether or not some other CPU spent
2199 any time idle and/or executing in userspace.
2200
2201 <p>
2202 These energy-efficiency requirements have proven quite difficult to
2203 understand and to meet, for example, there have been more than five
2204 clean-sheet rewrites of RCU's energy-efficiency code, the last of
2205 which was finally able to demonstrate
2206 <a href="http://www.rdrop.com/users/paulmck/realtime/paper/AMPenergy.2013.04.19a.pdf">real energy savings running on real hardware [PDF]</a>.
2207 As noted earlier,
2208 I learned of many of these requirements via angry phone calls:
2209 Flaming me on the Linux-kernel mailing list was apparently not
2210 sufficient to fully vent their ire at RCU's energy-efficiency bugs!
2211
2212 <h3><a name="Memory Efficiency">Memory Efficiency</a></h3>
2213
2214 <p>
2215 Although small-memory non-realtime systems can simply use Tiny RCU,
2216 code size is only one aspect of memory efficiency.
2217 Another aspect is the size of the <tt>rcu_head</tt> structure
2218 used by <tt>call_rcu()</tt> and <tt>kfree_rcu()</tt>.
2219 Although this structure contains nothing more than a pair of pointers,
2220 it does appear in many RCU-protected data structures, including
2221 some that are size critical.
2222 The <tt>page</tt> structure is a case in point, as evidenced by
2223 the many occurrences of the <tt>union</tt> keyword within that structure.
2224
2225 <p>
2226 This need for memory efficiency is one reason that RCU uses hand-crafted
2227 singly linked lists to track the <tt>rcu_head</tt> structures that
2228 are waiting for a grace period to elapse.
2229 It is also the reason why <tt>rcu_head</tt> structures do not contain
2230 debug information, such as fields tracking the file and line of the
2231 <tt>call_rcu()</tt> or <tt>kfree_rcu()</tt> that posted them.
2232 Although this information might appear in debug-only kernel builds at some
2233 point, in the meantime, the <tt>-&gt;func</tt> field will often provide
2234 the needed debug information.
2235
2236 <p>
2237 However, in some cases, the need for memory efficiency leads to even
2238 more extreme measures.
2239 Returning to the <tt>page</tt> structure, the <tt>rcu_head</tt> field
2240 shares storage with a great many other structures that are used at
2241 various points in the corresponding page's lifetime.
2242 In order to correctly resolve certain
2243 <a href="https://lkml.kernel.org/g/1439976106-137226-1-git-send-email-kirill.shutemov@linux.intel.com">race conditions</a>,
2244 the Linux kernel's memory-management subsystem needs a particular bit
2245 to remain zero during all phases of grace-period processing,
2246 and that bit happens to map to the bottom bit of the
2247 <tt>rcu_head</tt> structure's <tt>-&gt;next</tt> field.
2248 RCU makes this guarantee as long as <tt>call_rcu()</tt>
2249 is used to post the callback, as opposed to <tt>kfree_rcu()</tt>
2250 or some future &ldquo;lazy&rdquo;
2251 variant of <tt>call_rcu()</tt> that might one day be created for
2252 energy-efficiency purposes.
2253
2254 <h3><a name="Performance, Scalability, Response Time, and Reliability">
2255 Performance, Scalability, Response Time, and Reliability</a></h3>
2256
2257 <p>
2258 Expanding on the
2259 <a href="#Performance and Scalability">earlier discussion</a>,
2260 RCU is used heavily by hot code paths in performance-critical
2261 portions of the Linux kernel's networking, security, virtualization,
2262 and scheduling code paths.
2263 RCU must therefore use efficient implementations, especially in its
2264 read-side primitives.
2265 To that end, it would be good if preemptible RCU's implementation
2266 of <tt>rcu_read_lock()</tt> could be inlined, however, doing
2267 this requires resolving <tt>#include</tt> issues with the
2268 <tt>task_struct</tt> structure.
2269
2270 <p>
2271 The Linux kernel supports hardware configurations with up to
2272 4096 CPUs, which means that RCU must be extremely scalable.
2273 Algorithms that involve frequent acquisitions of global locks or
2274 frequent atomic operations on global variables simply cannot be
2275 tolerated within the RCU implementation.
2276 RCU therefore makes heavy use of a combining tree based on the
2277 <tt>rcu_node</tt> structure.
2278 RCU is required to tolerate all CPUs continuously invoking any
2279 combination of RCU's runtime primitives with minimal per-operation
2280 overhead.
2281 In fact, in many cases, increasing load must <i>decrease</i> the
2282 per-operation overhead, witness the batching optimizations for
2283 <tt>synchronize_rcu()</tt>, <tt>call_rcu()</tt>,
2284 <tt>synchronize_rcu_expedited()</tt>, and <tt>rcu_barrier()</tt>.
2285 As a general rule, RCU must cheerfully accept whatever the
2286 rest of the Linux kernel decides to throw at it.
2287
2288 <p>
2289 The Linux kernel is used for real-time workloads, especially
2290 in conjunction with the
2291 <a href="https://rt.wiki.kernel.org/index.php/Main_Page">-rt patchset</a>.
2292 The real-time-latency response requirements are such that the
2293 traditional approach of disabling preemption across RCU
2294 read-side critical sections is inappropriate.
2295 Kernels built with <tt>CONFIG_PREEMPT=y</tt> therefore
2296 use an RCU implementation that allows RCU read-side critical
2297 sections to be preempted.
2298 This requirement made its presence known after users made it
2299 clear that an earlier
2300 <a href="https://lwn.net/Articles/107930/">real-time patch</a>
2301 did not meet their needs, in conjunction with some
2302 <a href="https://lkml.kernel.org/g/20050318002026.GA2693@us.ibm.com">RCU issues</a>
2303 encountered by a very early version of the -rt patchset.
2304
2305 <p>
2306 In addition, RCU must make do with a sub-100-microsecond real-time latency
2307 budget.
2308 In fact, on smaller systems with the -rt patchset, the Linux kernel
2309 provides sub-20-microsecond real-time latencies for the whole kernel,
2310 including RCU.
2311 RCU's scalability and latency must therefore be sufficient for
2312 these sorts of configurations.
2313 To my surprise, the sub-100-microsecond real-time latency budget
2314 <a href="http://www.rdrop.com/users/paulmck/realtime/paper/bigrt.2013.01.31a.LCA.pdf">
2315 applies to even the largest systems [PDF]</a>,
2316 up to and including systems with 4096 CPUs.
2317 This real-time requirement motivated the grace-period kthread, which
2318 also simplified handling of a number of race conditions.
2319
2320 <p>
2321 Finally, RCU's status as a synchronization primitive means that
2322 any RCU failure can result in arbitrary memory corruption that can be
2323 extremely difficult to debug.
2324 This means that RCU must be extremely reliable, which in
2325 practice also means that RCU must have an aggressive stress-test
2326 suite.
2327 This stress-test suite is called <tt>rcutorture</tt>.
2328
2329 <p>
2330 Although the need for <tt>rcutorture</tt> was no surprise,
2331 the current immense popularity of the Linux kernel is posing
2332 interesting&mdash;and perhaps unprecedented&mdash;validation
2333 challenges.
2334 To see this, keep in mind that there are well over one billion
2335 instances of the Linux kernel running today, given Android
2336 smartphones, Linux-powered televisions, and servers.
2337 This number can be expected to increase sharply with the advent of
2338 the celebrated Internet of Things.
2339
2340 <p>
2341 Suppose that RCU contains a race condition that manifests on average
2342 once per million years of runtime.
2343 This bug will be occurring about three times per <i>day</i> across
2344 the installed base.
2345 RCU could simply hide behind hardware error rates, given that no one
2346 should really expect their smartphone to last for a million years.
2347 However, anyone taking too much comfort from this thought should
2348 consider the fact that in most jurisdictions, a successful multi-year
2349 test of a given mechanism, which might include a Linux kernel,
2350 suffices for a number of types of safety-critical certifications.
2351 In fact, rumor has it that the Linux kernel is already being used
2352 in production for safety-critical applications.
2353 I don't know about you, but I would feel quite bad if a bug in RCU
2354 killed someone.
2355 Which might explain my recent focus on validation and verification.
2356
2357 <h2><a name="Other RCU Flavors">Other RCU Flavors</a></h2>
2358
2359 <p>
2360 One of the more surprising things about RCU is that there are now
2361 no fewer than five <i>flavors</i>, or API families.
2362 In addition, the primary flavor that has been the sole focus up to
2363 this point has two different implementations, non-preemptible and
2364 preemptible.
2365 The other four flavors are listed below, with requirements for each
2366 described in a separate section.
2367
2368 <ol>
2369 <li> <a href="#Bottom-Half Flavor">Bottom-Half Flavor</a>
2370 <li> <a href="#Sched Flavor">Sched Flavor</a>
2371 <li> <a href="#Sleepable RCU">Sleepable RCU</a>
2372 <li> <a href="#Tasks RCU">Tasks RCU</a>
2373 </ol>
2374
2375 <h3><a name="Bottom-Half Flavor">Bottom-Half Flavor</a></h3>
2376
2377 <p>
2378 The softirq-disable (AKA &ldquo;bottom-half&rdquo;,
2379 hence the &ldquo;_bh&rdquo; abbreviations)
2380 flavor of RCU, or <i>RCU-bh</i>, was developed by
2381 Dipankar Sarma to provide a flavor of RCU that could withstand the
2382 network-based denial-of-service attacks researched by Robert
2383 Olsson.
2384 These attacks placed so much networking load on the system
2385 that some of the CPUs never exited softirq execution,
2386 which in turn prevented those CPUs from ever executing a context switch,
2387 which, in the RCU implementation of that time, prevented grace periods
2388 from ever ending.
2389 The result was an out-of-memory condition and a system hang.
2390
2391 <p>
2392 The solution was the creation of RCU-bh, which does
2393 <tt>local_bh_disable()</tt>
2394 across its read-side critical sections, and which uses the transition
2395 from one type of softirq processing to another as a quiescent state
2396 in addition to context switch, idle, user mode, and offline.
2397 This means that RCU-bh grace periods can complete even when some of
2398 the CPUs execute in softirq indefinitely, thus allowing algorithms
2399 based on RCU-bh to withstand network-based denial-of-service attacks.
2400
2401 <p>
2402 Because
2403 <tt>rcu_read_lock_bh()</tt> and <tt>rcu_read_unlock_bh()</tt>
2404 disable and re-enable softirq handlers, any attempt to start a softirq
2405 handlers during the
2406 RCU-bh read-side critical section will be deferred.
2407 In this case, <tt>rcu_read_unlock_bh()</tt>
2408 will invoke softirq processing, which can take considerable time.
2409 One can of course argue that this softirq overhead should be associated
2410 with the code following the RCU-bh read-side critical section rather
2411 than <tt>rcu_read_unlock_bh()</tt>, but the fact
2412 is that most profiling tools cannot be expected to make this sort
2413 of fine distinction.
2414 For example, suppose that a three-millisecond-long RCU-bh read-side
2415 critical section executes during a time of heavy networking load.
2416 There will very likely be an attempt to invoke at least one softirq
2417 handler during that three milliseconds, but any such invocation will
2418 be delayed until the time of the <tt>rcu_read_unlock_bh()</tt>.
2419 This can of course make it appear at first glance as if
2420 <tt>rcu_read_unlock_bh()</tt> was executing very slowly.
2421
2422 <p>
2423 The
2424 <a href="https://lwn.net/Articles/609973/#RCU Per-Flavor API Table">RCU-bh API</a>
2425 includes
2426 <tt>rcu_read_lock_bh()</tt>,
2427 <tt>rcu_read_unlock_bh()</tt>,
2428 <tt>rcu_dereference_bh()</tt>,
2429 <tt>rcu_dereference_bh_check()</tt>,
2430 <tt>synchronize_rcu_bh()</tt>,
2431 <tt>synchronize_rcu_bh_expedited()</tt>,
2432 <tt>call_rcu_bh()</tt>,
2433 <tt>rcu_barrier_bh()</tt>, and
2434 <tt>rcu_read_lock_bh_held()</tt>.
2435
2436 <h3><a name="Sched Flavor">Sched Flavor</a></h3>
2437
2438 <p>
2439 Before preemptible RCU, waiting for an RCU grace period had the
2440 side effect of also waiting for all pre-existing interrupt
2441 and NMI handlers.
2442 However, there are legitimate preemptible-RCU implementations that
2443 do not have this property, given that any point in the code outside
2444 of an RCU read-side critical section can be a quiescent state.
2445 Therefore, <i>RCU-sched</i> was created, which follows &ldquo;classic&rdquo;
2446 RCU in that an RCU-sched grace period waits for for pre-existing
2447 interrupt and NMI handlers.
2448 In kernels built with <tt>CONFIG_PREEMPT=n</tt>, the RCU and RCU-sched
2449 APIs have identical implementations, while kernels built with
2450 <tt>CONFIG_PREEMPT=y</tt> provide a separate implementation for each.
2451
2452 <p>
2453 Note well that in <tt>CONFIG_PREEMPT=y</tt> kernels,
2454 <tt>rcu_read_lock_sched()</tt> and <tt>rcu_read_unlock_sched()</tt>
2455 disable and re-enable preemption, respectively.
2456 This means that if there was a preemption attempt during the
2457 RCU-sched read-side critical section, <tt>rcu_read_unlock_sched()</tt>
2458 will enter the scheduler, with all the latency and overhead entailed.
2459 Just as with <tt>rcu_read_unlock_bh()</tt>, this can make it look
2460 as if <tt>rcu_read_unlock_sched()</tt> was executing very slowly.
2461 However, the highest-priority task won't be preempted, so that task
2462 will enjoy low-overhead <tt>rcu_read_unlock_sched()</tt> invocations.
2463
2464 <p>
2465 The
2466 <a href="https://lwn.net/Articles/609973/#RCU Per-Flavor API Table">RCU-sched API</a>
2467 includes
2468 <tt>rcu_read_lock_sched()</tt>,
2469 <tt>rcu_read_unlock_sched()</tt>,
2470 <tt>rcu_read_lock_sched_notrace()</tt>,
2471 <tt>rcu_read_unlock_sched_notrace()</tt>,
2472 <tt>rcu_dereference_sched()</tt>,
2473 <tt>rcu_dereference_sched_check()</tt>,
2474 <tt>synchronize_sched()</tt>,
2475 <tt>synchronize_rcu_sched_expedited()</tt>,
2476 <tt>call_rcu_sched()</tt>,
2477 <tt>rcu_barrier_sched()</tt>, and
2478 <tt>rcu_read_lock_sched_held()</tt>.
2479 However, anything that disables preemption also marks an RCU-sched
2480 read-side critical section, including
2481 <tt>preempt_disable()</tt> and <tt>preempt_enable()</tt>,
2482 <tt>local_irq_save()</tt> and <tt>local_irq_restore()</tt>,
2483 and so on.
2484
2485 <h3><a name="Sleepable RCU">Sleepable RCU</a></h3>
2486
2487 <p>
2488 For well over a decade, someone saying &ldquo;I need to block within
2489 an RCU read-side critical section&rdquo; was a reliable indication
2490 that this someone did not understand RCU.
2491 After all, if you are always blocking in an RCU read-side critical
2492 section, you can probably afford to use a higher-overhead synchronization
2493 mechanism.
2494 However, that changed with the advent of the Linux kernel's notifiers,
2495 whose RCU read-side critical
2496 sections almost never sleep, but sometimes need to.
2497 This resulted in the introduction of
2498 <a href="https://lwn.net/Articles/202847/">sleepable RCU</a>,
2499 or <i>SRCU</i>.
2500
2501 <p>
2502 SRCU allows different domains to be defined, with each such domain
2503 defined by an instance of an <tt>srcu_struct</tt> structure.
2504 A pointer to this structure must be passed in to each SRCU function,
2505 for example, <tt>synchronize_srcu(&amp;ss)</tt>, where
2506 <tt>ss</tt> is the <tt>srcu_struct</tt> structure.
2507 The key benefit of these domains is that a slow SRCU reader in one
2508 domain does not delay an SRCU grace period in some other domain.
2509 That said, one consequence of these domains is that read-side code
2510 must pass a &ldquo;cookie&rdquo; from <tt>srcu_read_lock()</tt>
2511 to <tt>srcu_read_unlock()</tt>, for example, as follows:
2512
2513 <blockquote>
2514 <pre>
2515 1 int idx;
2516 2
2517 3 idx = srcu_read_lock(&amp;ss);
2518 4 do_something();
2519 5 srcu_read_unlock(&amp;ss, idx);
2520 </pre>
2521 </blockquote>
2522
2523 <p>
2524 As noted above, it is legal to block within SRCU read-side critical sections,
2525 however, with great power comes great responsibility.
2526 If you block forever in one of a given domain's SRCU read-side critical
2527 sections, then that domain's grace periods will also be blocked forever.
2528 Of course, one good way to block forever is to deadlock, which can
2529 happen if any operation in a given domain's SRCU read-side critical
2530 section can block waiting, either directly or indirectly, for that domain's
2531 grace period to elapse.
2532 For example, this results in a self-deadlock:
2533
2534 <blockquote>
2535 <pre>
2536 1 int idx;
2537 2
2538 3 idx = srcu_read_lock(&amp;ss);
2539 4 do_something();
2540 5 synchronize_srcu(&amp;ss);
2541 6 srcu_read_unlock(&amp;ss, idx);
2542 </pre>
2543 </blockquote>
2544
2545 <p>
2546 However, if line&nbsp;5 acquired a mutex that was held across
2547 a <tt>synchronize_srcu()</tt> for domain <tt>ss</tt>,
2548 deadlock would still be possible.
2549 Furthermore, if line&nbsp;5 acquired a mutex that was held across
2550 a <tt>synchronize_srcu()</tt> for some other domain <tt>ss1</tt>,
2551 and if an <tt>ss1</tt>-domain SRCU read-side critical section
2552 acquired another mutex that was held across as <tt>ss</tt>-domain
2553 <tt>synchronize_srcu()</tt>,
2554 deadlock would again be possible.
2555 Such a deadlock cycle could extend across an arbitrarily large number
2556 of different SRCU domains.
2557 Again, with great power comes great responsibility.
2558
2559 <p>
2560 Unlike the other RCU flavors, SRCU read-side critical sections can
2561 run on idle and even offline CPUs.
2562 This ability requires that <tt>srcu_read_lock()</tt> and
2563 <tt>srcu_read_unlock()</tt> contain memory barriers, which means
2564 that SRCU readers will run a bit slower than would RCU readers.
2565 It also motivates the <tt>smp_mb__after_srcu_read_unlock()</tt>
2566 API, which, in combination with <tt>srcu_read_unlock()</tt>,
2567 guarantees a full memory barrier.
2568
2569 <p>
2570 The
2571 <a href="https://lwn.net/Articles/609973/#RCU Per-Flavor API Table">SRCU API</a>
2572 includes
2573 <tt>srcu_read_lock()</tt>,
2574 <tt>srcu_read_unlock()</tt>,
2575 <tt>srcu_dereference()</tt>,
2576 <tt>srcu_dereference_check()</tt>,
2577 <tt>synchronize_srcu()</tt>,
2578 <tt>synchronize_srcu_expedited()</tt>,
2579 <tt>call_srcu()</tt>,
2580 <tt>srcu_barrier()</tt>, and
2581 <tt>srcu_read_lock_held()</tt>.
2582 It also includes
2583 <tt>DEFINE_SRCU()</tt>,
2584 <tt>DEFINE_STATIC_SRCU()</tt>, and
2585 <tt>init_srcu_struct()</tt>
2586 APIs for defining and initializing <tt>srcu_struct</tt> structures.
2587
2588 <h3><a name="Tasks RCU">Tasks RCU</a></h3>
2589
2590 <p>
2591 Some forms of tracing use &ldquo;tramopolines&rdquo; to handle the
2592 binary rewriting required to install different types of probes.
2593 It would be good to be able to free old trampolines, which sounds
2594 like a job for some form of RCU.
2595 However, because it is necessary to be able to install a trace
2596 anywhere in the code, it is not possible to use read-side markers
2597 such as <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>.
2598 In addition, it does not work to have these markers in the trampoline
2599 itself, because there would need to be instructions following
2600 <tt>rcu_read_unlock()</tt>.
2601 Although <tt>synchronize_rcu()</tt> would guarantee that execution
2602 reached the <tt>rcu_read_unlock()</tt>, it would not be able to
2603 guarantee that execution had completely left the trampoline.
2604
2605 <p>
2606 The solution, in the form of
2607 <a href="https://lwn.net/Articles/607117/"><i>Tasks RCU</i></a>,
2608 is to have implicit
2609 read-side critical sections that are delimited by voluntary context
2610 switches, that is, calls to <tt>schedule()</tt>,
2611 <tt>cond_resched_rcu_qs()</tt>, and
2612 <tt>synchronize_rcu_tasks()</tt>.
2613 In addition, transitions to and from userspace execution also delimit
2614 tasks-RCU read-side critical sections.
2615
2616 <p>
2617 The tasks-RCU API is quite compact, consisting only of
2618 <tt>call_rcu_tasks()</tt>,
2619 <tt>synchronize_rcu_tasks()</tt>, and
2620 <tt>rcu_barrier_tasks()</tt>.
2621
2622 <h2><a name="Possible Future Changes">Possible Future Changes</a></h2>
2623
2624 <p>
2625 One of the tricks that RCU uses to attain update-side scalability is
2626 to increase grace-period latency with increasing numbers of CPUs.
2627 If this becomes a serious problem, it will be necessary to rework the
2628 grace-period state machine so as to avoid the need for the additional
2629 latency.
2630
2631 <p>
2632 Expedited grace periods scan the CPUs, so their latency and overhead
2633 increases with increasing numbers of CPUs.
2634 If this becomes a serious problem on large systems, it will be necessary
2635 to do some redesign to avoid this scalability problem.
2636
2637 <p>
2638 RCU disables CPU hotplug in a few places, perhaps most notably in the
2639 expedited grace-period and <tt>rcu_barrier()</tt> operations.
2640 If there is a strong reason to use expedited grace periods in CPU-hotplug
2641 notifiers, it will be necessary to avoid disabling CPU hotplug.
2642 This would introduce some complexity, so there had better be a <i>very</i>
2643 good reason.
2644
2645 <p>
2646 The tradeoff between grace-period latency on the one hand and interruptions
2647 of other CPUs on the other hand may need to be re-examined.
2648 The desire is of course for zero grace-period latency as well as zero
2649 interprocessor interrupts undertaken during an expedited grace period
2650 operation.
2651 While this ideal is unlikely to be achievable, it is quite possible that
2652 further improvements can be made.
2653
2654 <p>
2655 The multiprocessor implementations of RCU use a combining tree that
2656 groups CPUs so as to reduce lock contention and increase cache locality.
2657 However, this combining tree does not spread its memory across NUMA
2658 nodes nor does it align the CPU groups with hardware features such
2659 as sockets or cores.
2660 Such spreading and alignment is currently believed to be unnecessary
2661 because the hotpath read-side primitives do not access the combining
2662 tree, nor does <tt>call_rcu()</tt> in the common case.
2663 If you believe that your architecture needs such spreading and alignment,
2664 then your architecture should also benefit from the
2665 <tt>rcutree.rcu_fanout_leaf</tt> boot parameter, which can be set
2666 to the number of CPUs in a socket, NUMA node, or whatever.
2667 If the number of CPUs is too large, use a fraction of the number of
2668 CPUs.
2669 If the number of CPUs is a large prime number, well, that certainly
2670 is an &ldquo;interesting&rdquo; architectural choice!
2671 More flexible arrangements might be considered, but only if
2672 <tt>rcutree.rcu_fanout_leaf</tt> has proven inadequate, and only
2673 if the inadequacy has been demonstrated by a carefully run and
2674 realistic system-level workload.
2675
2676 <p>
2677 Please note that arrangements that require RCU to remap CPU numbers will
2678 require extremely good demonstration of need and full exploration of
2679 alternatives.
2680
2681 <p>
2682 There is an embarrassingly large number of flavors of RCU, and this
2683 number has been increasing over time.
2684 Perhaps it will be possible to combine some at some future date.
2685
2686 <p>
2687 RCU's various kthreads are reasonably recent additions.
2688 It is quite likely that adjustments will be required to more gracefully
2689 handle extreme loads.
2690 It might also be necessary to be able to relate CPU utilization by
2691 RCU's kthreads and softirq handlers to the code that instigated this
2692 CPU utilization.
2693 For example, RCU callback overhead might be charged back to the
2694 originating <tt>call_rcu()</tt> instance, though probably not
2695 in production kernels.
2696
2697 <h2><a name="Summary">Summary</a></h2>
2698
2699 <p>
2700 This document has presented more than two decade's worth of RCU
2701 requirements.
2702 Given that the requirements keep changing, this will not be the last
2703 word on this subject, but at least it serves to get an important
2704 subset of the requirements set forth.
2705
2706 <h2><a name="Acknowledgments">Acknowledgments</a></h2>
2707
2708 I am grateful to Steven Rostedt, Lai Jiangshan, Ingo Molnar,
2709 Oleg Nesterov, Borislav Petkov, Peter Zijlstra, Boqun Feng, and
2710 Andy Lutomirski for their help in rendering
2711 this article human readable, and to Michelle Rankin for her support
2712 of this effort.
2713 Other contributions are acknowledged in the Linux kernel's git archive.
2714 The cartoon is copyright (c) 2013 by Melissa Broussard,
2715 and is provided
2716 under the terms of the Creative Commons Attribution-Share Alike 3.0
2717 United States license.
2718
2719 <p>@@QQAL@@
2720
2721 </body></html>
This page took 0.094933 seconds and 6 git commands to generate.