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