Back to home page

LXR

 
 

    


0001 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
0002         "http://www.w3.org/TR/html4/loose.dtd">
0003         <html>
0004         <head><title>A Tour Through RCU's Requirements [LWN.net]</title>
0005         <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
0006 
0007 <h1>A Tour Through RCU's Requirements</h1>
0008 
0009 <p>Copyright IBM Corporation, 2015</p>
0010 <p>Author: Paul E.&nbsp;McKenney</p>
0011 <p><i>The initial version of this document appeared in the
0012 <a href="https://lwn.net/">LWN</a> articles
0013 <a href="https://lwn.net/Articles/652156/">here</a>,
0014 <a href="https://lwn.net/Articles/652677/">here</a>, and
0015 <a href="https://lwn.net/Articles/653326/">here</a>.</i></p>
0016 
0017 <h2>Introduction</h2>
0018 
0019 <p>
0020 Read-copy update (RCU) is a synchronization mechanism that is often
0021 used as a replacement for reader-writer locking.
0022 RCU is unusual in that updaters do not block readers,
0023 which means that RCU's read-side primitives can be exceedingly fast
0024 and scalable.
0025 In addition, updaters can make useful forward progress concurrently
0026 with readers.
0027 However, all this concurrency between RCU readers and updaters does raise
0028 the question of exactly what RCU readers are doing, which in turn
0029 raises the question of exactly what RCU's requirements are.
0030 
0031 <p>
0032 This document therefore summarizes RCU's requirements, and can be thought
0033 of as an informal, high-level specification for RCU.
0034 It is important to understand that RCU's specification is primarily
0035 empirical in nature;
0036 in fact, I learned about many of these requirements the hard way.
0037 This situation might cause some consternation, however, not only
0038 has this learning process been a lot of fun, but it has also been
0039 a great privilege to work with so many people willing to apply
0040 technologies in interesting new ways.
0041 
0042 <p>
0043 All that aside, here are the categories of currently known RCU requirements:
0044 </p>
0045 
0046 <ol>
0047 <li>    <a href="#Fundamental Requirements">
0048     Fundamental Requirements</a>
0049 <li>    <a href="#Fundamental Non-Requirements">Fundamental Non-Requirements</a>
0050 <li>    <a href="#Parallelism Facts of Life">
0051     Parallelism Facts of Life</a>
0052 <li>    <a href="#Quality-of-Implementation Requirements">
0053     Quality-of-Implementation Requirements</a>
0054 <li>    <a href="#Linux Kernel Complications">
0055     Linux Kernel Complications</a>
0056 <li>    <a href="#Software-Engineering Requirements">
0057     Software-Engineering Requirements</a>
0058 <li>    <a href="#Other RCU Flavors">
0059     Other RCU Flavors</a>
0060 <li>    <a href="#Possible Future Changes">
0061     Possible Future Changes</a>
0062 </ol>
0063 
0064 <p>
0065 This is followed by a <a href="#Summary">summary</a>,
0066 however, the answers to each quick quiz immediately follows the quiz.
0067 Select the big white space with your mouse to see the answer.
0068 
0069 <h2><a name="Fundamental Requirements">Fundamental Requirements</a></h2>
0070 
0071 <p>
0072 RCU's fundamental requirements are the closest thing RCU has to hard
0073 mathematical requirements.
0074 These are:
0075 
0076 <ol>
0077 <li>    <a href="#Grace-Period Guarantee">
0078     Grace-Period Guarantee</a>
0079 <li>    <a href="#Publish-Subscribe Guarantee">
0080     Publish-Subscribe Guarantee</a>
0081 <li>    <a href="#Memory-Barrier Guarantees">
0082     Memory-Barrier Guarantees</a>
0083 <li>    <a href="#RCU Primitives Guaranteed to Execute Unconditionally">
0084     RCU Primitives Guaranteed to Execute Unconditionally</a>
0085 <li>    <a href="#Guaranteed Read-to-Write Upgrade">
0086     Guaranteed Read-to-Write Upgrade</a>
0087 </ol>
0088 
0089 <h3><a name="Grace-Period Guarantee">Grace-Period Guarantee</a></h3>
0090 
0091 <p>
0092 RCU's grace-period guarantee is unusual in being premeditated:
0093 Jack Slingwine and I had this guarantee firmly in mind when we started
0094 work on RCU (then called &ldquo;rclock&rdquo;) in the early 1990s.
0095 That said, the past two decades of experience with RCU have produced
0096 a much more detailed understanding of this guarantee.
0097 
0098 <p>
0099 RCU's grace-period guarantee allows updaters to wait for the completion
0100 of all pre-existing RCU read-side critical sections.
0101 An RCU read-side critical section
0102 begins with the marker <tt>rcu_read_lock()</tt> and ends with
0103 the marker <tt>rcu_read_unlock()</tt>.
0104 These markers may be nested, and RCU treats a nested set as one
0105 big RCU read-side critical section.
0106 Production-quality implementations of <tt>rcu_read_lock()</tt> and
0107 <tt>rcu_read_unlock()</tt> are extremely lightweight, and in
0108 fact have exactly zero overhead in Linux kernels built for production
0109 use with <tt>CONFIG_PREEMPT=n</tt>.
0110 
0111 <p>
0112 This guarantee allows ordering to be enforced with extremely low
0113 overhead to readers, for example:
0114 
0115 <blockquote>
0116 <pre>
0117  1 int x, y;
0118  2
0119  3 void thread0(void)
0120  4 {
0121  5   rcu_read_lock();
0122  6   r1 = READ_ONCE(x);
0123  7   r2 = READ_ONCE(y);
0124  8   rcu_read_unlock();
0125  9 }
0126 10
0127 11 void thread1(void)
0128 12 {
0129 13   WRITE_ONCE(x, 1);
0130 14   synchronize_rcu();
0131 15   WRITE_ONCE(y, 1);
0132 16 }
0133 </pre>
0134 </blockquote>
0135 
0136 <p>
0137 Because the <tt>synchronize_rcu()</tt> on line&nbsp;14 waits for
0138 all pre-existing readers, any instance of <tt>thread0()</tt> that
0139 loads a value of zero from <tt>x</tt> must complete before
0140 <tt>thread1()</tt> stores to <tt>y</tt>, so that instance must
0141 also load a value of zero from <tt>y</tt>.
0142 Similarly, any instance of <tt>thread0()</tt> that loads a value of
0143 one from <tt>y</tt> must have started after the
0144 <tt>synchronize_rcu()</tt> started, and must therefore also load
0145 a value of one from <tt>x</tt>.
0146 Therefore, the outcome:
0147 <blockquote>
0148 <pre>
0149 (r1 == 0 &amp;&amp; r2 == 1)
0150 </pre>
0151 </blockquote>
0152 cannot happen.
0153 
0154 <table>
0155 <tr><th>&nbsp;</th></tr>
0156 <tr><th align="left">Quick Quiz:</th></tr>
0157 <tr><td>
0158     Wait a minute!
0159     You said that updaters can make useful forward progress concurrently
0160     with readers, but pre-existing readers will block
0161     <tt>synchronize_rcu()</tt>!!!
0162     Just who are you trying to fool???
0163 </td></tr>
0164 <tr><th align="left">Answer:</th></tr>
0165 <tr><td bgcolor="#ffffff"><font color="ffffff">
0166     First, if updaters do not wish to be blocked by readers, they can use
0167     <tt>call_rcu()</tt> or <tt>kfree_rcu()</tt>, which will
0168     be discussed later.
0169     Second, even when using <tt>synchronize_rcu()</tt>, the other
0170     update-side code does run concurrently with readers, whether
0171     pre-existing or not.
0172 </font></td></tr>
0173 <tr><td>&nbsp;</td></tr>
0174 </table>
0175 
0176 <p>
0177 This scenario resembles one of the first uses of RCU in
0178 <a href="https://en.wikipedia.org/wiki/DYNIX">DYNIX/ptx</a>,
0179 which managed a distributed lock manager's transition into
0180 a state suitable for handling recovery from node failure,
0181 more or less as follows:
0182 
0183 <blockquote>
0184 <pre>
0185  1 #define STATE_NORMAL        0
0186  2 #define STATE_WANT_RECOVERY 1
0187  3 #define STATE_RECOVERING    2
0188  4 #define STATE_WANT_NORMAL   3
0189  5
0190  6 int state = STATE_NORMAL;
0191  7
0192  8 void do_something_dlm(void)
0193  9 {
0194 10   int state_snap;
0195 11
0196 12   rcu_read_lock();
0197 13   state_snap = READ_ONCE(state);
0198 14   if (state_snap == STATE_NORMAL)
0199 15     do_something();
0200 16   else
0201 17     do_something_carefully();
0202 18   rcu_read_unlock();
0203 19 }
0204 20
0205 21 void start_recovery(void)
0206 22 {
0207 23   WRITE_ONCE(state, STATE_WANT_RECOVERY);
0208 24   synchronize_rcu();
0209 25   WRITE_ONCE(state, STATE_RECOVERING);
0210 26   recovery();
0211 27   WRITE_ONCE(state, STATE_WANT_NORMAL);
0212 28   synchronize_rcu();
0213 29   WRITE_ONCE(state, STATE_NORMAL);
0214 30 }
0215 </pre>
0216 </blockquote>
0217 
0218 <p>
0219 The RCU read-side critical section in <tt>do_something_dlm()</tt>
0220 works with the <tt>synchronize_rcu()</tt> in <tt>start_recovery()</tt>
0221 to guarantee that <tt>do_something()</tt> never runs concurrently
0222 with <tt>recovery()</tt>, but with little or no synchronization
0223 overhead in <tt>do_something_dlm()</tt>.
0224 
0225 <table>
0226 <tr><th>&nbsp;</th></tr>
0227 <tr><th align="left">Quick Quiz:</th></tr>
0228 <tr><td>
0229     Why is the <tt>synchronize_rcu()</tt> on line&nbsp;28 needed?
0230 </td></tr>
0231 <tr><th align="left">Answer:</th></tr>
0232 <tr><td bgcolor="#ffffff"><font color="ffffff">
0233     Without that extra grace period, memory reordering could result in
0234     <tt>do_something_dlm()</tt> executing <tt>do_something()</tt>
0235     concurrently with the last bits of <tt>recovery()</tt>.
0236 </font></td></tr>
0237 <tr><td>&nbsp;</td></tr>
0238 </table>
0239 
0240 <p>
0241 In order to avoid fatal problems such as deadlocks,
0242 an RCU read-side critical section must not contain calls to
0243 <tt>synchronize_rcu()</tt>.
0244 Similarly, an RCU read-side critical section must not
0245 contain anything that waits, directly or indirectly, on completion of
0246 an invocation of <tt>synchronize_rcu()</tt>.
0247 
0248 <p>
0249 Although RCU's grace-period guarantee is useful in and of itself, with
0250 <a href="https://lwn.net/Articles/573497/">quite a few use cases</a>,
0251 it would be good to be able to use RCU to coordinate read-side
0252 access to linked data structures.
0253 For this, the grace-period guarantee is not sufficient, as can
0254 be seen in function <tt>add_gp_buggy()</tt> below.
0255 We will look at the reader's code later, but in the meantime, just think of
0256 the reader as locklessly picking up the <tt>gp</tt> pointer,
0257 and, if the value loaded is non-<tt>NULL</tt>, locklessly accessing the
0258 <tt>-&gt;a</tt> and <tt>-&gt;b</tt> fields.
0259 
0260 <blockquote>
0261 <pre>
0262  1 bool add_gp_buggy(int a, int b)
0263  2 {
0264  3   p = kmalloc(sizeof(*p), GFP_KERNEL);
0265  4   if (!p)
0266  5     return -ENOMEM;
0267  6   spin_lock(&amp;gp_lock);
0268  7   if (rcu_access_pointer(gp)) {
0269  8     spin_unlock(&amp;gp_lock);
0270  9     return false;
0271 10   }
0272 11   p-&gt;a = a;
0273 12   p-&gt;b = a;
0274 13   gp = p; /* ORDERING BUG */
0275 14   spin_unlock(&amp;gp_lock);
0276 15   return true;
0277 16 }
0278 </pre>
0279 </blockquote>
0280 
0281 <p>
0282 The problem is that both the compiler and weakly ordered CPUs are within
0283 their rights to reorder this code as follows:
0284 
0285 <blockquote>
0286 <pre>
0287  1 bool add_gp_buggy_optimized(int a, int b)
0288  2 {
0289  3   p = kmalloc(sizeof(*p), GFP_KERNEL);
0290  4   if (!p)
0291  5     return -ENOMEM;
0292  6   spin_lock(&amp;gp_lock);
0293  7   if (rcu_access_pointer(gp)) {
0294  8     spin_unlock(&amp;gp_lock);
0295  9     return false;
0296 10   }
0297 <b>11   gp = p; /* ORDERING BUG */
0298 12   p-&gt;a = a;
0299 13   p-&gt;b = a;</b>
0300 14   spin_unlock(&amp;gp_lock);
0301 15   return true;
0302 16 }
0303 </pre>
0304 </blockquote>
0305 
0306 <p>
0307 If an RCU reader fetches <tt>gp</tt> just after
0308 <tt>add_gp_buggy_optimized</tt> executes line&nbsp;11,
0309 it will see garbage in the <tt>-&gt;a</tt> and <tt>-&gt;b</tt>
0310 fields.
0311 And this is but one of many ways in which compiler and hardware optimizations
0312 could cause trouble.
0313 Therefore, we clearly need some way to prevent the compiler and the CPU from
0314 reordering in this manner, which brings us to the publish-subscribe
0315 guarantee discussed in the next section.
0316 
0317 <h3><a name="Publish-Subscribe Guarantee">Publish/Subscribe Guarantee</a></h3>
0318 
0319 <p>
0320 RCU's publish-subscribe guarantee allows data to be inserted
0321 into a linked data structure without disrupting RCU readers.
0322 The updater uses <tt>rcu_assign_pointer()</tt> to insert the
0323 new data, and readers use <tt>rcu_dereference()</tt> to
0324 access data, whether new or old.
0325 The following shows an example of insertion:
0326 
0327 <blockquote>
0328 <pre>
0329  1 bool add_gp(int a, int b)
0330  2 {
0331  3   p = kmalloc(sizeof(*p), GFP_KERNEL);
0332  4   if (!p)
0333  5     return -ENOMEM;
0334  6   spin_lock(&amp;gp_lock);
0335  7   if (rcu_access_pointer(gp)) {
0336  8     spin_unlock(&amp;gp_lock);
0337  9     return false;
0338 10   }
0339 11   p-&gt;a = a;
0340 12   p-&gt;b = a;
0341 13   rcu_assign_pointer(gp, p);
0342 14   spin_unlock(&amp;gp_lock);
0343 15   return true;
0344 16 }
0345 </pre>
0346 </blockquote>
0347 
0348 <p>
0349 The <tt>rcu_assign_pointer()</tt> on line&nbsp;13 is conceptually
0350 equivalent to a simple assignment statement, but also guarantees
0351 that its assignment will
0352 happen after the two assignments in lines&nbsp;11 and&nbsp;12,
0353 similar to the C11 <tt>memory_order_release</tt> store operation.
0354 It also prevents any number of &ldquo;interesting&rdquo; compiler
0355 optimizations, for example, the use of <tt>gp</tt> as a scratch
0356 location immediately preceding the assignment.
0357 
0358 <table>
0359 <tr><th>&nbsp;</th></tr>
0360 <tr><th align="left">Quick Quiz:</th></tr>
0361 <tr><td>
0362     But <tt>rcu_assign_pointer()</tt> does nothing to prevent the
0363     two assignments to <tt>p-&gt;a</tt> and <tt>p-&gt;b</tt>
0364     from being reordered.
0365     Can't that also cause problems?
0366 </td></tr>
0367 <tr><th align="left">Answer:</th></tr>
0368 <tr><td bgcolor="#ffffff"><font color="ffffff">
0369     No, it cannot.
0370     The readers cannot see either of these two fields until
0371     the assignment to <tt>gp</tt>, by which time both fields are
0372     fully initialized.
0373     So reordering the assignments
0374     to <tt>p-&gt;a</tt> and <tt>p-&gt;b</tt> cannot possibly
0375     cause any problems.
0376 </font></td></tr>
0377 <tr><td>&nbsp;</td></tr>
0378 </table>
0379 
0380 <p>
0381 It is tempting to assume that the reader need not do anything special
0382 to control its accesses to the RCU-protected data,
0383 as shown in <tt>do_something_gp_buggy()</tt> below:
0384 
0385 <blockquote>
0386 <pre>
0387  1 bool do_something_gp_buggy(void)
0388  2 {
0389  3   rcu_read_lock();
0390  4   p = gp;  /* OPTIMIZATIONS GALORE!!! */
0391  5   if (p) {
0392  6     do_something(p-&gt;a, p-&gt;b);
0393  7     rcu_read_unlock();
0394  8     return true;
0395  9   }
0396 10   rcu_read_unlock();
0397 11   return false;
0398 12 }
0399 </pre>
0400 </blockquote>
0401 
0402 <p>
0403 However, this temptation must be resisted because there are a
0404 surprisingly large number of ways that the compiler
0405 (to say nothing of
0406 <a href="https://h71000.www7.hp.com/wizard/wiz_2637.html">DEC Alpha CPUs</a>)
0407 can trip this code up.
0408 For but one example, if the compiler were short of registers, it
0409 might choose to refetch from <tt>gp</tt> rather than keeping
0410 a separate copy in <tt>p</tt> as follows:
0411 
0412 <blockquote>
0413 <pre>
0414  1 bool do_something_gp_buggy_optimized(void)
0415  2 {
0416  3   rcu_read_lock();
0417  4   if (gp) { /* OPTIMIZATIONS GALORE!!! */
0418 <b> 5     do_something(gp-&gt;a, gp-&gt;b);</b>
0419  6     rcu_read_unlock();
0420  7     return true;
0421  8   }
0422  9   rcu_read_unlock();
0423 10   return false;
0424 11 }
0425 </pre>
0426 </blockquote>
0427 
0428 <p>
0429 If this function ran concurrently with a series of updates that
0430 replaced the current structure with a new one,
0431 the fetches of <tt>gp-&gt;a</tt>
0432 and <tt>gp-&gt;b</tt> might well come from two different structures,
0433 which could cause serious confusion.
0434 To prevent this (and much else besides), <tt>do_something_gp()</tt> uses
0435 <tt>rcu_dereference()</tt> to fetch from <tt>gp</tt>:
0436 
0437 <blockquote>
0438 <pre>
0439  1 bool do_something_gp(void)
0440  2 {
0441  3   rcu_read_lock();
0442  4   p = rcu_dereference(gp);
0443  5   if (p) {
0444  6     do_something(p-&gt;a, p-&gt;b);
0445  7     rcu_read_unlock();
0446  8     return true;
0447  9   }
0448 10   rcu_read_unlock();
0449 11   return false;
0450 12 }
0451 </pre>
0452 </blockquote>
0453 
0454 <p>
0455 The <tt>rcu_dereference()</tt> uses volatile casts and (for DEC Alpha)
0456 memory barriers in the Linux kernel.
0457 Should a
0458 <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>
0459 ever appear, then <tt>rcu_dereference()</tt> could be implemented
0460 as a <tt>memory_order_consume</tt> load.
0461 Regardless of the exact implementation, a pointer fetched by
0462 <tt>rcu_dereference()</tt> may not be used outside of the
0463 outermost RCU read-side critical section containing that
0464 <tt>rcu_dereference()</tt>, unless protection of
0465 the corresponding data element has been passed from RCU to some
0466 other synchronization mechanism, most commonly locking or
0467 <a href="https://www.kernel.org/doc/Documentation/RCU/rcuref.txt">reference counting</a>.
0468 
0469 <p>
0470 In short, updaters use <tt>rcu_assign_pointer()</tt> and readers
0471 use <tt>rcu_dereference()</tt>, and these two RCU API elements
0472 work together to ensure that readers have a consistent view of
0473 newly added data elements.
0474 
0475 <p>
0476 Of course, it is also necessary to remove elements from RCU-protected
0477 data structures, for example, using the following process:
0478 
0479 <ol>
0480 <li>    Remove the data element from the enclosing structure.
0481 <li>    Wait for all pre-existing RCU read-side critical sections
0482     to complete (because only pre-existing readers can possibly have
0483     a reference to the newly removed data element).
0484 <li>    At this point, only the updater has a reference to the
0485     newly removed data element, so it can safely reclaim
0486     the data element, for example, by passing it to <tt>kfree()</tt>.
0487 </ol>
0488 
0489 This process is implemented by <tt>remove_gp_synchronous()</tt>:
0490 
0491 <blockquote>
0492 <pre>
0493  1 bool remove_gp_synchronous(void)
0494  2 {
0495  3   struct foo *p;
0496  4
0497  5   spin_lock(&amp;gp_lock);
0498  6   p = rcu_access_pointer(gp);
0499  7   if (!p) {
0500  8     spin_unlock(&amp;gp_lock);
0501  9     return false;
0502 10   }
0503 11   rcu_assign_pointer(gp, NULL);
0504 12   spin_unlock(&amp;gp_lock);
0505 13   synchronize_rcu();
0506 14   kfree(p);
0507 15   return true;
0508 16 }
0509 </pre>
0510 </blockquote>
0511 
0512 <p>
0513 This function is straightforward, with line&nbsp;13 waiting for a grace
0514 period before line&nbsp;14 frees the old data element.
0515 This waiting ensures that readers will reach line&nbsp;7 of
0516 <tt>do_something_gp()</tt> before the data element referenced by
0517 <tt>p</tt> is freed.
0518 The <tt>rcu_access_pointer()</tt> on line&nbsp;6 is similar to
0519 <tt>rcu_dereference()</tt>, except that:
0520 
0521 <ol>
0522 <li>    The value returned by <tt>rcu_access_pointer()</tt>
0523     cannot be dereferenced.
0524     If you want to access the value pointed to as well as
0525     the pointer itself, use <tt>rcu_dereference()</tt>
0526     instead of <tt>rcu_access_pointer()</tt>.
0527 <li>    The call to <tt>rcu_access_pointer()</tt> need not be
0528     protected.
0529     In contrast, <tt>rcu_dereference()</tt> must either be
0530     within an RCU read-side critical section or in a code
0531     segment where the pointer cannot change, for example, in
0532     code protected by the corresponding update-side lock.
0533 </ol>
0534 
0535 <table>
0536 <tr><th>&nbsp;</th></tr>
0537 <tr><th align="left">Quick Quiz:</th></tr>
0538 <tr><td>
0539     Without the <tt>rcu_dereference()</tt> or the
0540     <tt>rcu_access_pointer()</tt>, what destructive optimizations
0541     might the compiler make use of?
0542 </td></tr>
0543 <tr><th align="left">Answer:</th></tr>
0544 <tr><td bgcolor="#ffffff"><font color="ffffff">
0545     Let's start with what happens to <tt>do_something_gp()</tt>
0546     if it fails to use <tt>rcu_dereference()</tt>.
0547     It could reuse a value formerly fetched from this same pointer.
0548     It could also fetch the pointer from <tt>gp</tt> in a byte-at-a-time
0549     manner, resulting in <i>load tearing</i>, in turn resulting a bytewise
0550     mash-up of two distinct pointer values.
0551     It might even use value-speculation optimizations, where it makes
0552     a wrong guess, but by the time it gets around to checking the
0553     value, an update has changed the pointer to match the wrong guess.
0554     Too bad about any dereferences that returned pre-initialization garbage
0555     in the meantime!
0556     </font>
0557 
0558     <p><font color="ffffff">
0559     For <tt>remove_gp_synchronous()</tt>, as long as all modifications
0560     to <tt>gp</tt> are carried out while holding <tt>gp_lock</tt>,
0561     the above optimizations are harmless.
0562     However,
0563     with <tt>CONFIG_SPARSE_RCU_POINTER=y</tt>,
0564     <tt>sparse</tt> will complain if you
0565     define <tt>gp</tt> with <tt>__rcu</tt> and then
0566     access it without using
0567     either <tt>rcu_access_pointer()</tt> or <tt>rcu_dereference()</tt>.
0568 </font></td></tr>
0569 <tr><td>&nbsp;</td></tr>
0570 </table>
0571 
0572 <p>
0573 In short, RCU's publish-subscribe guarantee is provided by the combination
0574 of <tt>rcu_assign_pointer()</tt> and <tt>rcu_dereference()</tt>.
0575 This guarantee allows data elements to be safely added to RCU-protected
0576 linked data structures without disrupting RCU readers.
0577 This guarantee can be used in combination with the grace-period
0578 guarantee to also allow data elements to be removed from RCU-protected
0579 linked data structures, again without disrupting RCU readers.
0580 
0581 <p>
0582 This guarantee was only partially premeditated.
0583 DYNIX/ptx used an explicit memory barrier for publication, but had nothing
0584 resembling <tt>rcu_dereference()</tt> for subscription, nor did it
0585 have anything resembling the <tt>smp_read_barrier_depends()</tt>
0586 that was later subsumed into <tt>rcu_dereference()</tt>.
0587 The need for these operations made itself known quite suddenly at a
0588 late-1990s meeting with the DEC Alpha architects, back in the days when
0589 DEC was still a free-standing company.
0590 It took the Alpha architects a good hour to convince me that any sort
0591 of barrier would ever be needed, and it then took me a good <i>two</i> hours
0592 to convince them that their documentation did not make this point clear.
0593 More recent work with the C and C++ standards committees have provided
0594 much education on tricks and traps from the compiler.
0595 In short, compilers were much less tricky in the early 1990s, but in
0596 2015, don't even think about omitting <tt>rcu_dereference()</tt>!
0597 
0598 <h3><a name="Memory-Barrier Guarantees">Memory-Barrier Guarantees</a></h3>
0599 
0600 <p>
0601 The previous section's simple linked-data-structure scenario clearly
0602 demonstrates the need for RCU's stringent memory-ordering guarantees on
0603 systems with more than one CPU:
0604 
0605 <ol>
0606 <li>    Each CPU that has an RCU read-side critical section that
0607     begins before <tt>synchronize_rcu()</tt> starts is
0608     guaranteed to execute a full memory barrier between the time
0609     that the RCU read-side critical section ends and the time that
0610     <tt>synchronize_rcu()</tt> returns.
0611     Without this guarantee, a pre-existing RCU read-side critical section
0612     might hold a reference to the newly removed <tt>struct foo</tt>
0613     after the <tt>kfree()</tt> on line&nbsp;14 of
0614     <tt>remove_gp_synchronous()</tt>.
0615 <li>    Each CPU that has an RCU read-side critical section that ends
0616     after <tt>synchronize_rcu()</tt> returns is guaranteed
0617     to execute a full memory barrier between the time that
0618     <tt>synchronize_rcu()</tt> begins and the time that the RCU
0619     read-side critical section begins.
0620     Without this guarantee, a later RCU read-side critical section
0621     running after the <tt>kfree()</tt> on line&nbsp;14 of
0622     <tt>remove_gp_synchronous()</tt> might
0623     later run <tt>do_something_gp()</tt> and find the
0624     newly deleted <tt>struct foo</tt>.
0625 <li>    If the task invoking <tt>synchronize_rcu()</tt> remains
0626     on a given CPU, then that CPU is guaranteed to execute a full
0627     memory barrier sometime during the execution of
0628     <tt>synchronize_rcu()</tt>.
0629     This guarantee ensures that the <tt>kfree()</tt> on
0630     line&nbsp;14 of <tt>remove_gp_synchronous()</tt> really does
0631     execute after the removal on line&nbsp;11.
0632 <li>    If the task invoking <tt>synchronize_rcu()</tt> migrates
0633     among a group of CPUs during that invocation, then each of the
0634     CPUs in that group is guaranteed to execute a full memory barrier
0635     sometime during the execution of <tt>synchronize_rcu()</tt>.
0636     This guarantee also ensures that the <tt>kfree()</tt> on
0637     line&nbsp;14 of <tt>remove_gp_synchronous()</tt> really does
0638     execute after the removal on
0639     line&nbsp;11, but also in the case where the thread executing the
0640     <tt>synchronize_rcu()</tt> migrates in the meantime.
0641 </ol>
0642 
0643 <table>
0644 <tr><th>&nbsp;</th></tr>
0645 <tr><th align="left">Quick Quiz:</th></tr>
0646 <tr><td>
0647     Given that multiple CPUs can start RCU read-side critical sections
0648     at any time without any ordering whatsoever, how can RCU possibly
0649     tell whether or not a given RCU read-side critical section starts
0650     before a given instance of <tt>synchronize_rcu()</tt>?
0651 </td></tr>
0652 <tr><th align="left">Answer:</th></tr>
0653 <tr><td bgcolor="#ffffff"><font color="ffffff">
0654     If RCU cannot tell whether or not a given
0655     RCU read-side critical section starts before a
0656     given instance of <tt>synchronize_rcu()</tt>,
0657     then it must assume that the RCU read-side critical section
0658     started first.
0659     In other words, a given instance of <tt>synchronize_rcu()</tt>
0660     can avoid waiting on a given RCU read-side critical section only
0661     if it can prove that <tt>synchronize_rcu()</tt> started first.
0662 
0663     <p>
0664     A related question is &ldquo;When <tt>rcu_read_lock()</tt>
0665     doesn't generate any code, why does it matter how it relates
0666     to a grace period?&rdquo;
0667     The answer is that it is not the relationship of
0668     <tt>rcu_read_lock()</tt> itself that is important, but rather
0669     the relationship of the code within the enclosed RCU read-side
0670     critical section to the code preceding and following the
0671     grace period.
0672     If we take this viewpoint, then a given RCU read-side critical
0673     section begins before a given grace period when some access
0674     preceding the grace period observes the effect of some access
0675     within the critical section, in which case none of the accesses
0676     within the critical section may observe the effects of any
0677     access following the grace period.
0678 
0679     <p>
0680     As of late 2016, mathematical models of RCU take this
0681     viewpoint, for example, see slides&nbsp;62 and&nbsp;63
0682     of the
0683     <a href="http://www2.rdrop.com/users/paulmck/scalability/paper/LinuxMM.2016.10.04c.LCE.pdf">2016 LinuxCon EU</a>
0684     presentation.
0685 </font></td></tr>
0686 <tr><td>&nbsp;</td></tr>
0687 </table>
0688 
0689 <table>
0690 <tr><th>&nbsp;</th></tr>
0691 <tr><th align="left">Quick Quiz:</th></tr>
0692 <tr><td>
0693     The first and second guarantees require unbelievably strict ordering!
0694     Are all these memory barriers <i> really</i> required?
0695 </td></tr>
0696 <tr><th align="left">Answer:</th></tr>
0697 <tr><td bgcolor="#ffffff"><font color="ffffff">
0698     Yes, they really are required.
0699     To see why the first guarantee is required, consider the following
0700     sequence of events:
0701     </font>
0702 
0703     <ol>
0704     <li>    <font color="ffffff">
0705         CPU 1: <tt>rcu_read_lock()</tt>
0706         </font>
0707     <li>    <font color="ffffff">
0708         CPU 1: <tt>q = rcu_dereference(gp);
0709         /* Very likely to return p. */</tt>
0710         </font>
0711     <li>    <font color="ffffff">
0712         CPU 0: <tt>list_del_rcu(p);</tt>
0713         </font>
0714     <li>    <font color="ffffff">
0715         CPU 0: <tt>synchronize_rcu()</tt> starts.
0716         </font>
0717     <li>    <font color="ffffff">
0718         CPU 1: <tt>do_something_with(q-&gt;a);
0719         /* No smp_mb(), so might happen after kfree(). */</tt>
0720         </font>
0721     <li>    <font color="ffffff">
0722         CPU 1: <tt>rcu_read_unlock()</tt>
0723         </font>
0724     <li>    <font color="ffffff">
0725         CPU 0: <tt>synchronize_rcu()</tt> returns.
0726         </font>
0727     <li>    <font color="ffffff">
0728         CPU 0: <tt>kfree(p);</tt>
0729         </font>
0730     </ol>
0731 
0732     <p><font color="ffffff">
0733     Therefore, there absolutely must be a full memory barrier between the
0734     end of the RCU read-side critical section and the end of the
0735     grace period.
0736     </font>
0737 
0738     <p><font color="ffffff">
0739     The sequence of events demonstrating the necessity of the second rule
0740     is roughly similar:
0741     </font>
0742 
0743     <ol>
0744     <li>    <font color="ffffff">CPU 0: <tt>list_del_rcu(p);</tt>
0745         </font>
0746     <li>    <font color="ffffff">CPU 0: <tt>synchronize_rcu()</tt> starts.
0747         </font>
0748     <li>    <font color="ffffff">CPU 1: <tt>rcu_read_lock()</tt>
0749         </font>
0750     <li>    <font color="ffffff">CPU 1: <tt>q = rcu_dereference(gp);
0751         /* Might return p if no memory barrier. */</tt>
0752         </font>
0753     <li>    <font color="ffffff">CPU 0: <tt>synchronize_rcu()</tt> returns.
0754         </font>
0755     <li>    <font color="ffffff">CPU 0: <tt>kfree(p);</tt>
0756         </font>
0757     <li>    <font color="ffffff">
0758         CPU 1: <tt>do_something_with(q-&gt;a); /* Boom!!! */</tt>
0759         </font>
0760     <li>    <font color="ffffff">CPU 1: <tt>rcu_read_unlock()</tt>
0761         </font>
0762     </ol>
0763 
0764     <p><font color="ffffff">
0765     And similarly, without a memory barrier between the beginning of the
0766     grace period and the beginning of the RCU read-side critical section,
0767     CPU&nbsp;1 might end up accessing the freelist.
0768     </font>
0769 
0770     <p><font color="ffffff">
0771     The &ldquo;as if&rdquo; rule of course applies, so that any
0772     implementation that acts as if the appropriate memory barriers
0773     were in place is a correct implementation.
0774     That said, it is much easier to fool yourself into believing
0775     that you have adhered to the as-if rule than it is to actually
0776     adhere to it!
0777 </font></td></tr>
0778 <tr><td>&nbsp;</td></tr>
0779 </table>
0780 
0781 <table>
0782 <tr><th>&nbsp;</th></tr>
0783 <tr><th align="left">Quick Quiz:</th></tr>
0784 <tr><td>
0785     You claim that <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>
0786     generate absolutely no code in some kernel builds.
0787     This means that the compiler might arbitrarily rearrange consecutive
0788     RCU read-side critical sections.
0789     Given such rearrangement, if a given RCU read-side critical section
0790     is done, how can you be sure that all prior RCU read-side critical
0791     sections are done?
0792     Won't the compiler rearrangements make that impossible to determine?
0793 </td></tr>
0794 <tr><th align="left">Answer:</th></tr>
0795 <tr><td bgcolor="#ffffff"><font color="ffffff">
0796     In cases where <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>
0797     generate absolutely no code, RCU infers quiescent states only at
0798     special locations, for example, within the scheduler.
0799     Because calls to <tt>schedule()</tt> had better prevent calling-code
0800     accesses to shared variables from being rearranged across the call to
0801     <tt>schedule()</tt>, if RCU detects the end of a given RCU read-side
0802     critical section, it will necessarily detect the end of all prior
0803     RCU read-side critical sections, no matter how aggressively the
0804     compiler scrambles the code.
0805     </font>
0806 
0807     <p><font color="ffffff">
0808     Again, this all assumes that the compiler cannot scramble code across
0809     calls to the scheduler, out of interrupt handlers, into the idle loop,
0810     into user-mode code, and so on.
0811     But if your kernel build allows that sort of scrambling, you have broken
0812     far more than just RCU!
0813 </font></td></tr>
0814 <tr><td>&nbsp;</td></tr>
0815 </table>
0816 
0817 <p>
0818 Note that these memory-barrier requirements do not replace the fundamental
0819 RCU requirement that a grace period wait for all pre-existing readers.
0820 On the contrary, the memory barriers called out in this section must operate in
0821 such a way as to <i>enforce</i> this fundamental requirement.
0822 Of course, different implementations enforce this requirement in different
0823 ways, but enforce it they must.
0824 
0825 <h3><a name="RCU Primitives Guaranteed to Execute Unconditionally">RCU Primitives Guaranteed to Execute Unconditionally</a></h3>
0826 
0827 <p>
0828 The common-case RCU primitives are unconditional.
0829 They are invoked, they do their job, and they return, with no possibility
0830 of error, and no need to retry.
0831 This is a key RCU design philosophy.
0832 
0833 <p>
0834 However, this philosophy is pragmatic rather than pigheaded.
0835 If someone comes up with a good justification for a particular conditional
0836 RCU primitive, it might well be implemented and added.
0837 After all, this guarantee was reverse-engineered, not premeditated.
0838 The unconditional nature of the RCU primitives was initially an
0839 accident of implementation, and later experience with synchronization
0840 primitives with conditional primitives caused me to elevate this
0841 accident to a guarantee.
0842 Therefore, the justification for adding a conditional primitive to
0843 RCU would need to be based on detailed and compelling use cases.
0844 
0845 <h3><a name="Guaranteed Read-to-Write Upgrade">Guaranteed Read-to-Write Upgrade</a></h3>
0846 
0847 <p>
0848 As far as RCU is concerned, it is always possible to carry out an
0849 update within an RCU read-side critical section.
0850 For example, that RCU read-side critical section might search for
0851 a given data element, and then might acquire the update-side
0852 spinlock in order to update that element, all while remaining
0853 in that RCU read-side critical section.
0854 Of course, it is necessary to exit the RCU read-side critical section
0855 before invoking <tt>synchronize_rcu()</tt>, however, this
0856 inconvenience can be avoided through use of the
0857 <tt>call_rcu()</tt> and <tt>kfree_rcu()</tt> API members
0858 described later in this document.
0859 
0860 <table>
0861 <tr><th>&nbsp;</th></tr>
0862 <tr><th align="left">Quick Quiz:</th></tr>
0863 <tr><td>
0864     But how does the upgrade-to-write operation exclude other readers?
0865 </td></tr>
0866 <tr><th align="left">Answer:</th></tr>
0867 <tr><td bgcolor="#ffffff"><font color="ffffff">
0868     It doesn't, just like normal RCU updates, which also do not exclude
0869     RCU readers.
0870 </font></td></tr>
0871 <tr><td>&nbsp;</td></tr>
0872 </table>
0873 
0874 <p>
0875 This guarantee allows lookup code to be shared between read-side
0876 and update-side code, and was premeditated, appearing in the earliest
0877 DYNIX/ptx RCU documentation.
0878 
0879 <h2><a name="Fundamental Non-Requirements">Fundamental Non-Requirements</a></h2>
0880 
0881 <p>
0882 RCU provides extremely lightweight readers, and its read-side guarantees,
0883 though quite useful, are correspondingly lightweight.
0884 It is therefore all too easy to assume that RCU is guaranteeing more
0885 than it really is.
0886 Of course, the list of things that RCU does not guarantee is infinitely
0887 long, however, the following sections list a few non-guarantees that
0888 have caused confusion.
0889 Except where otherwise noted, these non-guarantees were premeditated.
0890 
0891 <ol>
0892 <li>    <a href="#Readers Impose Minimal Ordering">
0893     Readers Impose Minimal Ordering</a>
0894 <li>    <a href="#Readers Do Not Exclude Updaters">
0895     Readers Do Not Exclude Updaters</a>
0896 <li>    <a href="#Updaters Only Wait For Old Readers">
0897     Updaters Only Wait For Old Readers</a>
0898 <li>    <a href="#Grace Periods Don't Partition Read-Side Critical Sections">
0899     Grace Periods Don't Partition Read-Side Critical Sections</a>
0900 <li>    <a href="#Read-Side Critical Sections Don't Partition Grace Periods">
0901     Read-Side Critical Sections Don't Partition Grace Periods</a>
0902 <li>    <a href="#Disabling Preemption Does Not Block Grace Periods">
0903     Disabling Preemption Does Not Block Grace Periods</a>
0904 </ol>
0905 
0906 <h3><a name="Readers Impose Minimal Ordering">Readers Impose Minimal Ordering</a></h3>
0907 
0908 <p>
0909 Reader-side markers such as <tt>rcu_read_lock()</tt> and
0910 <tt>rcu_read_unlock()</tt> provide absolutely no ordering guarantees
0911 except through their interaction with the grace-period APIs such as
0912 <tt>synchronize_rcu()</tt>.
0913 To see this, consider the following pair of threads:
0914 
0915 <blockquote>
0916 <pre>
0917  1 void thread0(void)
0918  2 {
0919  3   rcu_read_lock();
0920  4   WRITE_ONCE(x, 1);
0921  5   rcu_read_unlock();
0922  6   rcu_read_lock();
0923  7   WRITE_ONCE(y, 1);
0924  8   rcu_read_unlock();
0925  9 }
0926 10
0927 11 void thread1(void)
0928 12 {
0929 13   rcu_read_lock();
0930 14   r1 = READ_ONCE(y);
0931 15   rcu_read_unlock();
0932 16   rcu_read_lock();
0933 17   r2 = READ_ONCE(x);
0934 18   rcu_read_unlock();
0935 19 }
0936 </pre>
0937 </blockquote>
0938 
0939 <p>
0940 After <tt>thread0()</tt> and <tt>thread1()</tt> execute
0941 concurrently, it is quite possible to have
0942 
0943 <blockquote>
0944 <pre>
0945 (r1 == 1 &amp;&amp; r2 == 0)
0946 </pre>
0947 </blockquote>
0948 
0949 (that is, <tt>y</tt> appears to have been assigned before <tt>x</tt>),
0950 which would not be possible if <tt>rcu_read_lock()</tt> and
0951 <tt>rcu_read_unlock()</tt> had much in the way of ordering
0952 properties.
0953 But they do not, so the CPU is within its rights
0954 to do significant reordering.
0955 This is by design:  Any significant ordering constraints would slow down
0956 these fast-path APIs.
0957 
0958 <table>
0959 <tr><th>&nbsp;</th></tr>
0960 <tr><th align="left">Quick Quiz:</th></tr>
0961 <tr><td>
0962     Can't the compiler also reorder this code?
0963 </td></tr>
0964 <tr><th align="left">Answer:</th></tr>
0965 <tr><td bgcolor="#ffffff"><font color="ffffff">
0966     No, the volatile casts in <tt>READ_ONCE()</tt> and
0967     <tt>WRITE_ONCE()</tt> prevent the compiler from reordering in
0968     this particular case.
0969 </font></td></tr>
0970 <tr><td>&nbsp;</td></tr>
0971 </table>
0972 
0973 <h3><a name="Readers Do Not Exclude Updaters">Readers Do Not Exclude Updaters</a></h3>
0974 
0975 <p>
0976 Neither <tt>rcu_read_lock()</tt> nor <tt>rcu_read_unlock()</tt>
0977 exclude updates.
0978 All they do is to prevent grace periods from ending.
0979 The following example illustrates this:
0980 
0981 <blockquote>
0982 <pre>
0983  1 void thread0(void)
0984  2 {
0985  3   rcu_read_lock();
0986  4   r1 = READ_ONCE(y);
0987  5   if (r1) {
0988  6     do_something_with_nonzero_x();
0989  7     r2 = READ_ONCE(x);
0990  8     WARN_ON(!r2); /* BUG!!! */
0991  9   }
0992 10   rcu_read_unlock();
0993 11 }
0994 12
0995 13 void thread1(void)
0996 14 {
0997 15   spin_lock(&amp;my_lock);
0998 16   WRITE_ONCE(x, 1);
0999 17   WRITE_ONCE(y, 1);
1000 18   spin_unlock(&amp;my_lock);
1001 19 }
1002 </pre>
1003 </blockquote>
1004 
1005 <p>
1006 If the <tt>thread0()</tt> function's <tt>rcu_read_lock()</tt>
1007 excluded the <tt>thread1()</tt> function's update,
1008 the <tt>WARN_ON()</tt> could never fire.
1009 But the fact is that <tt>rcu_read_lock()</tt> does not exclude
1010 much of anything aside from subsequent grace periods, of which
1011 <tt>thread1()</tt> has none, so the
1012 <tt>WARN_ON()</tt> can and does fire.
1013 
1014 <h3><a name="Updaters Only Wait For Old Readers">Updaters Only Wait For Old Readers</a></h3>
1015 
1016 <p>
1017 It might be tempting to assume that after <tt>synchronize_rcu()</tt>
1018 completes, there are no readers executing.
1019 This temptation must be avoided because
1020 new readers can start immediately after <tt>synchronize_rcu()</tt>
1021 starts, and <tt>synchronize_rcu()</tt> is under no
1022 obligation to wait for these new readers.
1023 
1024 <table>
1025 <tr><th>&nbsp;</th></tr>
1026 <tr><th align="left">Quick Quiz:</th></tr>
1027 <tr><td>
1028     Suppose that synchronize_rcu() did wait until <i>all</i>
1029     readers had completed instead of waiting only on
1030     pre-existing readers.
1031     For how long would the updater be able to rely on there
1032     being no readers?
1033 </td></tr>
1034 <tr><th align="left">Answer:</th></tr>
1035 <tr><td bgcolor="#ffffff"><font color="ffffff">
1036     For no time at all.
1037     Even if <tt>synchronize_rcu()</tt> were to wait until
1038     all readers had completed, a new reader might start immediately after
1039     <tt>synchronize_rcu()</tt> completed.
1040     Therefore, the code following
1041     <tt>synchronize_rcu()</tt> can <i>never</i> rely on there being
1042     no readers.
1043 </font></td></tr>
1044 <tr><td>&nbsp;</td></tr>
1045 </table>
1046 
1047 <h3><a name="Grace Periods Don't Partition Read-Side Critical Sections">
1048 Grace Periods Don't Partition Read-Side Critical Sections</a></h3>
1049 
1050 <p>
1051 It is tempting to assume that if any part of one RCU read-side critical
1052 section precedes a given grace period, and if any part of another RCU
1053 read-side critical section follows that same grace period, then all of
1054 the first RCU read-side critical section must precede all of the second.
1055 However, this just isn't the case: A single grace period does not
1056 partition the set of RCU read-side critical sections.
1057 An example of this situation can be illustrated as follows, where
1058 <tt>x</tt>, <tt>y</tt>, and <tt>z</tt> are initially all zero:
1059 
1060 <blockquote>
1061 <pre>
1062  1 void thread0(void)
1063  2 {
1064  3   rcu_read_lock();
1065  4   WRITE_ONCE(a, 1);
1066  5   WRITE_ONCE(b, 1);
1067  6   rcu_read_unlock();
1068  7 }
1069  8
1070  9 void thread1(void)
1071 10 {
1072 11   r1 = READ_ONCE(a);
1073 12   synchronize_rcu();
1074 13   WRITE_ONCE(c, 1);
1075 14 }
1076 15
1077 16 void thread2(void)
1078 17 {
1079 18   rcu_read_lock();
1080 19   r2 = READ_ONCE(b);
1081 20   r3 = READ_ONCE(c);
1082 21   rcu_read_unlock();
1083 22 }
1084 </pre>
1085 </blockquote>
1086 
1087 <p>
1088 It turns out that the outcome:
1089 
1090 <blockquote>
1091 <pre>
1092 (r1 == 1 &amp;&amp; r2 == 0 &amp;&amp; r3 == 1)
1093 </pre>
1094 </blockquote>
1095 
1096 is entirely possible.
1097 The following figure show how this can happen, with each circled
1098 <tt>QS</tt> indicating the point at which RCU recorded a
1099 <i>quiescent state</i> for each thread, that is, a state in which
1100 RCU knows that the thread cannot be in the midst of an RCU read-side
1101 critical section that started before the current grace period:
1102 
1103 <p><img src="GPpartitionReaders1.svg" alt="GPpartitionReaders1.svg" width="60%"></p>
1104 
1105 <p>
1106 If it is necessary to partition RCU read-side critical sections in this
1107 manner, it is necessary to use two grace periods, where the first
1108 grace period is known to end before the second grace period starts:
1109 
1110 <blockquote>
1111 <pre>
1112  1 void thread0(void)
1113  2 {
1114  3   rcu_read_lock();
1115  4   WRITE_ONCE(a, 1);
1116  5   WRITE_ONCE(b, 1);
1117  6   rcu_read_unlock();
1118  7 }
1119  8
1120  9 void thread1(void)
1121 10 {
1122 11   r1 = READ_ONCE(a);
1123 12   synchronize_rcu();
1124 13   WRITE_ONCE(c, 1);
1125 14 }
1126 15
1127 16 void thread2(void)
1128 17 {
1129 18   r2 = READ_ONCE(c);
1130 19   synchronize_rcu();
1131 20   WRITE_ONCE(d, 1);
1132 21 }
1133 22
1134 23 void thread3(void)
1135 24 {
1136 25   rcu_read_lock();
1137 26   r3 = READ_ONCE(b);
1138 27   r4 = READ_ONCE(d);
1139 28   rcu_read_unlock();
1140 29 }
1141 </pre>
1142 </blockquote>
1143 
1144 <p>
1145 Here, if <tt>(r1 == 1)</tt>, then
1146 <tt>thread0()</tt>'s write to <tt>b</tt> must happen
1147 before the end of <tt>thread1()</tt>'s grace period.
1148 If in addition <tt>(r4 == 1)</tt>, then
1149 <tt>thread3()</tt>'s read from <tt>b</tt> must happen
1150 after the beginning of <tt>thread2()</tt>'s grace period.
1151 If it is also the case that <tt>(r2 == 1)</tt>, then the
1152 end of <tt>thread1()</tt>'s grace period must precede the
1153 beginning of <tt>thread2()</tt>'s grace period.
1154 This mean that the two RCU read-side critical sections cannot overlap,
1155 guaranteeing that <tt>(r3 == 1)</tt>.
1156 As a result, the outcome:
1157 
1158 <blockquote>
1159 <pre>
1160 (r1 == 1 &amp;&amp; r2 == 1 &amp;&amp; r3 == 0 &amp;&amp; r4 == 1)
1161 </pre>
1162 </blockquote>
1163 
1164 cannot happen.
1165 
1166 <p>
1167 This non-requirement was also non-premeditated, but became apparent
1168 when studying RCU's interaction with memory ordering.
1169 
1170 <h3><a name="Read-Side Critical Sections Don't Partition Grace Periods">
1171 Read-Side Critical Sections Don't Partition Grace Periods</a></h3>
1172 
1173 <p>
1174 It is also tempting to assume that if an RCU read-side critical section
1175 happens between a pair of grace periods, then those grace periods cannot
1176 overlap.
1177 However, this temptation leads nowhere good, as can be illustrated by
1178 the following, with all variables initially zero:
1179 
1180 <blockquote>
1181 <pre>
1182  1 void thread0(void)
1183  2 {
1184  3   rcu_read_lock();
1185  4   WRITE_ONCE(a, 1);
1186  5   WRITE_ONCE(b, 1);
1187  6   rcu_read_unlock();
1188  7 }
1189  8
1190  9 void thread1(void)
1191 10 {
1192 11   r1 = READ_ONCE(a);
1193 12   synchronize_rcu();
1194 13   WRITE_ONCE(c, 1);
1195 14 }
1196 15
1197 16 void thread2(void)
1198 17 {
1199 18   rcu_read_lock();
1200 19   WRITE_ONCE(d, 1);
1201 20   r2 = READ_ONCE(c);
1202 21   rcu_read_unlock();
1203 22 }
1204 23
1205 24 void thread3(void)
1206 25 {
1207 26   r3 = READ_ONCE(d);
1208 27   synchronize_rcu();
1209 28   WRITE_ONCE(e, 1);
1210 29 }
1211 30
1212 31 void thread4(void)
1213 32 {
1214 33   rcu_read_lock();
1215 34   r4 = READ_ONCE(b);
1216 35   r5 = READ_ONCE(e);
1217 36   rcu_read_unlock();
1218 37 }
1219 </pre>
1220 </blockquote>
1221 
1222 <p>
1223 In this case, the outcome:
1224 
1225 <blockquote>
1226 <pre>
1227 (r1 == 1 &amp;&amp; r2 == 1 &amp;&amp; r3 == 1 &amp;&amp; r4 == 0 &amp&amp; r5 == 1)
1228 </pre>
1229 </blockquote>
1230 
1231 is entirely possible, as illustrated below:
1232 
1233 <p><img src="ReadersPartitionGP1.svg" alt="ReadersPartitionGP1.svg" width="100%"></p>
1234 
1235 <p>
1236 Again, an RCU read-side critical section can overlap almost all of a
1237 given grace period, just so long as it does not overlap the entire
1238 grace period.
1239 As a result, an RCU read-side critical section cannot partition a pair
1240 of RCU grace periods.
1241 
1242 <table>
1243 <tr><th>&nbsp;</th></tr>
1244 <tr><th align="left">Quick Quiz:</th></tr>
1245 <tr><td>
1246     How long a sequence of grace periods, each separated by an RCU
1247     read-side critical section, would be required to partition the RCU
1248     read-side critical sections at the beginning and end of the chain?
1249 </td></tr>
1250 <tr><th align="left">Answer:</th></tr>
1251 <tr><td bgcolor="#ffffff"><font color="ffffff">
1252     In theory, an infinite number.
1253     In practice, an unknown number that is sensitive to both implementation
1254     details and timing considerations.
1255     Therefore, even in practice, RCU users must abide by the
1256     theoretical rather than the practical answer.
1257 </font></td></tr>
1258 <tr><td>&nbsp;</td></tr>
1259 </table>
1260 
1261 <h3><a name="Disabling Preemption Does Not Block Grace Periods">
1262 Disabling Preemption Does Not Block Grace Periods</a></h3>
1263 
1264 <p>
1265 There was a time when disabling preemption on any given CPU would block
1266 subsequent grace periods.
1267 However, this was an accident of implementation and is not a requirement.
1268 And in the current Linux-kernel implementation, disabling preemption
1269 on a given CPU in fact does not block grace periods, as Oleg Nesterov
1270 <a href="https://lkml.kernel.org/g/20150614193825.GA19582@redhat.com">demonstrated</a>.
1271 
1272 <p>
1273 If you need a preempt-disable region to block grace periods, you need to add
1274 <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>, for example
1275 as follows:
1276 
1277 <blockquote>
1278 <pre>
1279  1 preempt_disable();
1280  2 rcu_read_lock();
1281  3 do_something();
1282  4 rcu_read_unlock();
1283  5 preempt_enable();
1284  6
1285  7 /* Spinlocks implicitly disable preemption. */
1286  8 spin_lock(&amp;mylock);
1287  9 rcu_read_lock();
1288 10 do_something();
1289 11 rcu_read_unlock();
1290 12 spin_unlock(&amp;mylock);
1291 </pre>
1292 </blockquote>
1293 
1294 <p>
1295 In theory, you could enter the RCU read-side critical section first,
1296 but it is more efficient to keep the entire RCU read-side critical
1297 section contained in the preempt-disable region as shown above.
1298 Of course, RCU read-side critical sections that extend outside of
1299 preempt-disable regions will work correctly, but such critical sections
1300 can be preempted, which forces <tt>rcu_read_unlock()</tt> to do
1301 more work.
1302 And no, this is <i>not</i> an invitation to enclose all of your RCU
1303 read-side critical sections within preempt-disable regions, because
1304 doing so would degrade real-time response.
1305 
1306 <p>
1307 This non-requirement appeared with preemptible RCU.
1308 If you need a grace period that waits on non-preemptible code regions, use
1309 <a href="#Sched Flavor">RCU-sched</a>.
1310 
1311 <h2><a name="Parallelism Facts of Life">Parallelism Facts of Life</a></h2>
1312 
1313 <p>
1314 These parallelism facts of life are by no means specific to RCU, but
1315 the RCU implementation must abide by them.
1316 They therefore bear repeating:
1317 
1318 <ol>
1319 <li>    Any CPU or task may be delayed at any time,
1320     and any attempts to avoid these delays by disabling
1321     preemption, interrupts, or whatever are completely futile.
1322     This is most obvious in preemptible user-level
1323     environments and in virtualized environments (where
1324     a given guest OS's VCPUs can be preempted at any time by
1325     the underlying hypervisor), but can also happen in bare-metal
1326     environments due to ECC errors, NMIs, and other hardware
1327     events.
1328     Although a delay of more than about 20 seconds can result
1329     in splats, the RCU implementation is obligated to use
1330     algorithms that can tolerate extremely long delays, but where
1331     &ldquo;extremely long&rdquo; is not long enough to allow
1332     wrap-around when incrementing a 64-bit counter.
1333 <li>    Both the compiler and the CPU can reorder memory accesses.
1334     Where it matters, RCU must use compiler directives and
1335     memory-barrier instructions to preserve ordering.
1336 <li>    Conflicting writes to memory locations in any given cache line
1337     will result in expensive cache misses.
1338     Greater numbers of concurrent writes and more-frequent
1339     concurrent writes will result in more dramatic slowdowns.
1340     RCU is therefore obligated to use algorithms that have
1341     sufficient locality to avoid significant performance and
1342     scalability problems.
1343 <li>    As a rough rule of thumb, only one CPU's worth of processing
1344     may be carried out under the protection of any given exclusive
1345     lock.
1346     RCU must therefore use scalable locking designs.
1347 <li>    Counters are finite, especially on 32-bit systems.
1348     RCU's use of counters must therefore tolerate counter wrap,
1349     or be designed such that counter wrap would take way more
1350     time than a single system is likely to run.
1351     An uptime of ten years is quite possible, a runtime
1352     of a century much less so.
1353     As an example of the latter, RCU's dyntick-idle nesting counter
1354     allows 54 bits for interrupt nesting level (this counter
1355     is 64 bits even on a 32-bit system).
1356     Overflowing this counter requires 2<sup>54</sup>
1357     half-interrupts on a given CPU without that CPU ever going idle.
1358     If a half-interrupt happened every microsecond, it would take
1359     570 years of runtime to overflow this counter, which is currently
1360     believed to be an acceptably long time.
1361 <li>    Linux systems can have thousands of CPUs running a single
1362     Linux kernel in a single shared-memory environment.
1363     RCU must therefore pay close attention to high-end scalability.
1364 </ol>
1365 
1366 <p>
1367 This last parallelism fact of life means that RCU must pay special
1368 attention to the preceding facts of life.
1369 The idea that Linux might scale to systems with thousands of CPUs would
1370 have been met with some skepticism in the 1990s, but these requirements
1371 would have otherwise have been unsurprising, even in the early 1990s.
1372 
1373 <h2><a name="Quality-of-Implementation Requirements">Quality-of-Implementation Requirements</a></h2>
1374 
1375 <p>
1376 These sections list quality-of-implementation requirements.
1377 Although an RCU implementation that ignores these requirements could
1378 still be used, it would likely be subject to limitations that would
1379 make it inappropriate for industrial-strength production use.
1380 Classes of quality-of-implementation requirements are as follows:
1381 
1382 <ol>
1383 <li>    <a href="#Specialization">Specialization</a>
1384 <li>    <a href="#Performance and Scalability">Performance and Scalability</a>
1385 <li>    <a href="#Composability">Composability</a>
1386 <li>    <a href="#Corner Cases">Corner Cases</a>
1387 </ol>
1388 
1389 <p>
1390 These classes is covered in the following sections.
1391 
1392 <h3><a name="Specialization">Specialization</a></h3>
1393 
1394 <p>
1395 RCU is and always has been intended primarily for read-mostly situations,
1396 which means that RCU's read-side primitives are optimized, often at the
1397 expense of its update-side primitives.
1398 Experience thus far is captured by the following list of situations:
1399 
1400 <ol>
1401 <li>    Read-mostly data, where stale and inconsistent data is not
1402     a problem:   RCU works great!
1403 <li>    Read-mostly data, where data must be consistent:
1404     RCU works well.
1405 <li>    Read-write data, where data must be consistent:
1406     RCU <i>might</i> work OK.
1407     Or not.
1408 <li>    Write-mostly data, where data must be consistent:
1409     RCU is very unlikely to be the right tool for the job,
1410     with the following exceptions, where RCU can provide:
1411     <ol type=a>
1412     <li>    Existence guarantees for update-friendly mechanisms.
1413     <li>    Wait-free read-side primitives for real-time use.
1414     </ol>
1415 </ol>
1416 
1417 <p>
1418 This focus on read-mostly situations means that RCU must interoperate
1419 with other synchronization primitives.
1420 For example, the <tt>add_gp()</tt> and <tt>remove_gp_synchronous()</tt>
1421 examples discussed earlier use RCU to protect readers and locking to
1422 coordinate updaters.
1423 However, the need extends much farther, requiring that a variety of
1424 synchronization primitives be legal within RCU read-side critical sections,
1425 including spinlocks, sequence locks, atomic operations, reference
1426 counters, and memory barriers.
1427 
1428 <table>
1429 <tr><th>&nbsp;</th></tr>
1430 <tr><th align="left">Quick Quiz:</th></tr>
1431 <tr><td>
1432     What about sleeping locks?
1433 </td></tr>
1434 <tr><th align="left">Answer:</th></tr>
1435 <tr><td bgcolor="#ffffff"><font color="ffffff">
1436     These are forbidden within Linux-kernel RCU read-side critical
1437     sections because it is not legal to place a quiescent state
1438     (in this case, voluntary context switch) within an RCU read-side
1439     critical section.
1440     However, sleeping locks may be used within userspace RCU read-side
1441     critical sections, and also within Linux-kernel sleepable RCU
1442     <a href="#Sleepable RCU"><font color="ffffff">(SRCU)</font></a>
1443     read-side critical sections.
1444     In addition, the -rt patchset turns spinlocks into a
1445     sleeping locks so that the corresponding critical sections
1446     can be preempted, which also means that these sleeplockified
1447     spinlocks (but not other sleeping locks!)  may be acquire within
1448     -rt-Linux-kernel RCU read-side critical sections.
1449     </font>
1450 
1451     <p><font color="ffffff">
1452     Note that it <i>is</i> legal for a normal RCU read-side
1453     critical section to conditionally acquire a sleeping locks
1454     (as in <tt>mutex_trylock()</tt>), but only as long as it does
1455     not loop indefinitely attempting to conditionally acquire that
1456     sleeping locks.
1457     The key point is that things like <tt>mutex_trylock()</tt>
1458     either return with the mutex held, or return an error indication if
1459     the mutex was not immediately available.
1460     Either way, <tt>mutex_trylock()</tt> returns immediately without
1461     sleeping.
1462 </font></td></tr>
1463 <tr><td>&nbsp;</td></tr>
1464 </table>
1465 
1466 <p>
1467 It often comes as a surprise that many algorithms do not require a
1468 consistent view of data, but many can function in that mode,
1469 with network routing being the poster child.
1470 Internet routing algorithms take significant time to propagate
1471 updates, so that by the time an update arrives at a given system,
1472 that system has been sending network traffic the wrong way for
1473 a considerable length of time.
1474 Having a few threads continue to send traffic the wrong way for a
1475 few more milliseconds is clearly not a problem:  In the worst case,
1476 TCP retransmissions will eventually get the data where it needs to go.
1477 In general, when tracking the state of the universe outside of the
1478 computer, some level of inconsistency must be tolerated due to
1479 speed-of-light delays if nothing else.
1480 
1481 <p>
1482 Furthermore, uncertainty about external state is inherent in many cases.
1483 For example, a pair of veternarians might use heartbeat to determine
1484 whether or not a given cat was alive.
1485 But how long should they wait after the last heartbeat to decide that
1486 the cat is in fact dead?
1487 Waiting less than 400 milliseconds makes no sense because this would
1488 mean that a relaxed cat would be considered to cycle between death
1489 and life more than 100 times per minute.
1490 Moreover, just as with human beings, a cat's heart might stop for
1491 some period of time, so the exact wait period is a judgment call.
1492 One of our pair of veternarians might wait 30 seconds before pronouncing
1493 the cat dead, while the other might insist on waiting a full minute.
1494 The two veternarians would then disagree on the state of the cat during
1495 the final 30 seconds of the minute following the last heartbeat.
1496 
1497 <p>
1498 Interestingly enough, this same situation applies to hardware.
1499 When push comes to shove, how do we tell whether or not some
1500 external server has failed?
1501 We send messages to it periodically, and declare it failed if we
1502 don't receive a response within a given period of time.
1503 Policy decisions can usually tolerate short
1504 periods of inconsistency.
1505 The policy was decided some time ago, and is only now being put into
1506 effect, so a few milliseconds of delay is normally inconsequential.
1507 
1508 <p>
1509 However, there are algorithms that absolutely must see consistent data.
1510 For example, the translation between a user-level SystemV semaphore
1511 ID to the corresponding in-kernel data structure is protected by RCU,
1512 but it is absolutely forbidden to update a semaphore that has just been
1513 removed.
1514 In the Linux kernel, this need for consistency is accommodated by acquiring
1515 spinlocks located in the in-kernel data structure from within
1516 the RCU read-side critical section, and this is indicated by the
1517 green box in the figure above.
1518 Many other techniques may be used, and are in fact used within the
1519 Linux kernel.
1520 
1521 <p>
1522 In short, RCU is not required to maintain consistency, and other
1523 mechanisms may be used in concert with RCU when consistency is required.
1524 RCU's specialization allows it to do its job extremely well, and its
1525 ability to interoperate with other synchronization mechanisms allows
1526 the right mix of synchronization tools to be used for a given job.
1527 
1528 <h3><a name="Performance and Scalability">Performance and Scalability</a></h3>
1529 
1530 <p>
1531 Energy efficiency is a critical component of performance today,
1532 and Linux-kernel RCU implementations must therefore avoid unnecessarily
1533 awakening idle CPUs.
1534 I cannot claim that this requirement was premeditated.
1535 In fact, I learned of it during a telephone conversation in which I
1536 was given &ldquo;frank and open&rdquo; feedback on the importance
1537 of energy efficiency in battery-powered systems and on specific
1538 energy-efficiency shortcomings of the Linux-kernel RCU implementation.
1539 In my experience, the battery-powered embedded community will consider
1540 any unnecessary wakeups to be extremely unfriendly acts.
1541 So much so that mere Linux-kernel-mailing-list posts are
1542 insufficient to vent their ire.
1543 
1544 <p>
1545 Memory consumption is not particularly important for in most
1546 situations, and has become decreasingly
1547 so as memory sizes have expanded and memory
1548 costs have plummeted.
1549 However, as I learned from Matt Mackall's
1550 <a href="http://elinux.org/Linux_Tiny-FAQ">bloatwatch</a>
1551 efforts, memory footprint is critically important on single-CPU systems with
1552 non-preemptible (<tt>CONFIG_PREEMPT=n</tt>) kernels, and thus
1553 <a href="https://lkml.kernel.org/g/20090113221724.GA15307@linux.vnet.ibm.com">tiny RCU</a>
1554 was born.
1555 Josh Triplett has since taken over the small-memory banner with his
1556 <a href="https://tiny.wiki.kernel.org/">Linux kernel tinification</a>
1557 project, which resulted in
1558 <a href="#Sleepable RCU">SRCU</a>
1559 becoming optional for those kernels not needing it.
1560 
1561 <p>
1562 The remaining performance requirements are, for the most part,
1563 unsurprising.
1564 For example, in keeping with RCU's read-side specialization,
1565 <tt>rcu_dereference()</tt> should have negligible overhead (for
1566 example, suppression of a few minor compiler optimizations).
1567 Similarly, in non-preemptible environments, <tt>rcu_read_lock()</tt> and
1568 <tt>rcu_read_unlock()</tt> should have exactly zero overhead.
1569 
1570 <p>
1571 In preemptible environments, in the case where the RCU read-side
1572 critical section was not preempted (as will be the case for the
1573 highest-priority real-time process), <tt>rcu_read_lock()</tt> and
1574 <tt>rcu_read_unlock()</tt> should have minimal overhead.
1575 In particular, they should not contain atomic read-modify-write
1576 operations, memory-barrier instructions, preemption disabling,
1577 interrupt disabling, or backwards branches.
1578 However, in the case where the RCU read-side critical section was preempted,
1579 <tt>rcu_read_unlock()</tt> may acquire spinlocks and disable interrupts.
1580 This is why it is better to nest an RCU read-side critical section
1581 within a preempt-disable region than vice versa, at least in cases
1582 where that critical section is short enough to avoid unduly degrading
1583 real-time latencies.
1584 
1585 <p>
1586 The <tt>synchronize_rcu()</tt> grace-period-wait primitive is
1587 optimized for throughput.
1588 It may therefore incur several milliseconds of latency in addition to
1589 the duration of the longest RCU read-side critical section.
1590 On the other hand, multiple concurrent invocations of
1591 <tt>synchronize_rcu()</tt> are required to use batching optimizations
1592 so that they can be satisfied by a single underlying grace-period-wait
1593 operation.
1594 For example, in the Linux kernel, it is not unusual for a single
1595 grace-period-wait operation to serve more than
1596 <a href="https://www.usenix.org/conference/2004-usenix-annual-technical-conference/making-rcu-safe-deep-sub-millisecond-response">1,000 separate invocations</a>
1597 of <tt>synchronize_rcu()</tt>, thus amortizing the per-invocation
1598 overhead down to nearly zero.
1599 However, the grace-period optimization is also required to avoid
1600 measurable degradation of real-time scheduling and interrupt latencies.
1601 
1602 <p>
1603 In some cases, the multi-millisecond <tt>synchronize_rcu()</tt>
1604 latencies are unacceptable.
1605 In these cases, <tt>synchronize_rcu_expedited()</tt> may be used
1606 instead, reducing the grace-period latency down to a few tens of
1607 microseconds on small systems, at least in cases where the RCU read-side
1608 critical sections are short.
1609 There are currently no special latency requirements for
1610 <tt>synchronize_rcu_expedited()</tt> on large systems, but,
1611 consistent with the empirical nature of the RCU specification,
1612 that is subject to change.
1613 However, there most definitely are scalability requirements:
1614 A storm of <tt>synchronize_rcu_expedited()</tt> invocations on 4096
1615 CPUs should at least make reasonable forward progress.
1616 In return for its shorter latencies, <tt>synchronize_rcu_expedited()</tt>
1617 is permitted to impose modest degradation of real-time latency
1618 on non-idle online CPUs.
1619 That said, it will likely be necessary to take further steps to reduce this
1620 degradation, hopefully to roughly that of a scheduling-clock interrupt.
1621 
1622 <p>
1623 There are a number of situations where even
1624 <tt>synchronize_rcu_expedited()</tt>'s reduced grace-period
1625 latency is unacceptable.
1626 In these situations, the asynchronous <tt>call_rcu()</tt> can be
1627 used in place of <tt>synchronize_rcu()</tt> as follows:
1628 
1629 <blockquote>
1630 <pre>
1631  1 struct foo {
1632  2   int a;
1633  3   int b;
1634  4   struct rcu_head rh;
1635  5 };
1636  6
1637  7 static void remove_gp_cb(struct rcu_head *rhp)
1638  8 {
1639  9   struct foo *p = container_of(rhp, struct foo, rh);
1640 10
1641 11   kfree(p);
1642 12 }
1643 13
1644 14 bool remove_gp_asynchronous(void)
1645 15 {
1646 16   struct foo *p;
1647 17
1648 18   spin_lock(&amp;gp_lock);
1649 19   p = rcu_dereference(gp);
1650 20   if (!p) {
1651 21     spin_unlock(&amp;gp_lock);
1652 22     return false;
1653 23   }
1654 24   rcu_assign_pointer(gp, NULL);
1655 25   call_rcu(&amp;p-&gt;rh, remove_gp_cb);
1656 26   spin_unlock(&amp;gp_lock);
1657 27   return true;
1658 28 }
1659 </pre>
1660 </blockquote>
1661 
1662 <p>
1663 A definition of <tt>struct foo</tt> is finally needed, and appears
1664 on lines&nbsp;1-5.
1665 The function <tt>remove_gp_cb()</tt> is passed to <tt>call_rcu()</tt>
1666 on line&nbsp;25, and will be invoked after the end of a subsequent
1667 grace period.
1668 This gets the same effect as <tt>remove_gp_synchronous()</tt>,
1669 but without forcing the updater to wait for a grace period to elapse.
1670 The <tt>call_rcu()</tt> function may be used in a number of
1671 situations where neither <tt>synchronize_rcu()</tt> nor
1672 <tt>synchronize_rcu_expedited()</tt> would be legal,
1673 including within preempt-disable code, <tt>local_bh_disable()</tt> code,
1674 interrupt-disable code, and interrupt handlers.
1675 However, even <tt>call_rcu()</tt> is illegal within NMI handlers
1676 and from idle and offline CPUs.
1677 The callback function (<tt>remove_gp_cb()</tt> in this case) will be
1678 executed within softirq (software interrupt) environment within the
1679 Linux kernel,
1680 either within a real softirq handler or under the protection
1681 of <tt>local_bh_disable()</tt>.
1682 In both the Linux kernel and in userspace, it is bad practice to
1683 write an RCU callback function that takes too long.
1684 Long-running operations should be relegated to separate threads or
1685 (in the Linux kernel) workqueues.
1686 
1687 <table>
1688 <tr><th>&nbsp;</th></tr>
1689 <tr><th align="left">Quick Quiz:</th></tr>
1690 <tr><td>
1691     Why does line&nbsp;19 use <tt>rcu_access_pointer()</tt>?
1692     After all, <tt>call_rcu()</tt> on line&nbsp;25 stores into the
1693     structure, which would interact badly with concurrent insertions.
1694     Doesn't this mean that <tt>rcu_dereference()</tt> is required?
1695 </td></tr>
1696 <tr><th align="left">Answer:</th></tr>
1697 <tr><td bgcolor="#ffffff"><font color="ffffff">
1698     Presumably the <tt>-&gt;gp_lock</tt> acquired on line&nbsp;18 excludes
1699     any changes, including any insertions that <tt>rcu_dereference()</tt>
1700     would protect against.
1701     Therefore, any insertions will be delayed until after
1702     <tt>-&gt;gp_lock</tt>
1703     is released on line&nbsp;25, which in turn means that
1704     <tt>rcu_access_pointer()</tt> suffices.
1705 </font></td></tr>
1706 <tr><td>&nbsp;</td></tr>
1707 </table>
1708 
1709 <p>
1710 However, all that <tt>remove_gp_cb()</tt> is doing is
1711 invoking <tt>kfree()</tt> on the data element.
1712 This is a common idiom, and is supported by <tt>kfree_rcu()</tt>,
1713 which allows &ldquo;fire and forget&rdquo; operation as shown below:
1714 
1715 <blockquote>
1716 <pre>
1717  1 struct foo {
1718  2   int a;
1719  3   int b;
1720  4   struct rcu_head rh;
1721  5 };
1722  6
1723  7 bool remove_gp_faf(void)
1724  8 {
1725  9   struct foo *p;
1726 10
1727 11   spin_lock(&amp;gp_lock);
1728 12   p = rcu_dereference(gp);
1729 13   if (!p) {
1730 14     spin_unlock(&amp;gp_lock);
1731 15     return false;
1732 16   }
1733 17   rcu_assign_pointer(gp, NULL);
1734 18   kfree_rcu(p, rh);
1735 19   spin_unlock(&amp;gp_lock);
1736 20   return true;
1737 21 }
1738 </pre>
1739 </blockquote>
1740 
1741 <p>
1742 Note that <tt>remove_gp_faf()</tt> simply invokes
1743 <tt>kfree_rcu()</tt> and proceeds, without any need to pay any
1744 further attention to the subsequent grace period and <tt>kfree()</tt>.
1745 It is permissible to invoke <tt>kfree_rcu()</tt> from the same
1746 environments as for <tt>call_rcu()</tt>.
1747 Interestingly enough, DYNIX/ptx had the equivalents of
1748 <tt>call_rcu()</tt> and <tt>kfree_rcu()</tt>, but not
1749 <tt>synchronize_rcu()</tt>.
1750 This was due to the fact that RCU was not heavily used within DYNIX/ptx,
1751 so the very few places that needed something like
1752 <tt>synchronize_rcu()</tt> simply open-coded it.
1753 
1754 <table>
1755 <tr><th>&nbsp;</th></tr>
1756 <tr><th align="left">Quick Quiz:</th></tr>
1757 <tr><td>
1758     Earlier it was claimed that <tt>call_rcu()</tt> and
1759     <tt>kfree_rcu()</tt> allowed updaters to avoid being blocked
1760     by readers.
1761     But how can that be correct, given that the invocation of the callback
1762     and the freeing of the memory (respectively) must still wait for
1763     a grace period to elapse?
1764 </td></tr>
1765 <tr><th align="left">Answer:</th></tr>
1766 <tr><td bgcolor="#ffffff"><font color="ffffff">
1767     We could define things this way, but keep in mind that this sort of
1768     definition would say that updates in garbage-collected languages
1769     cannot complete until the next time the garbage collector runs,
1770     which does not seem at all reasonable.
1771     The key point is that in most cases, an updater using either
1772     <tt>call_rcu()</tt> or <tt>kfree_rcu()</tt> can proceed to the
1773     next update as soon as it has invoked <tt>call_rcu()</tt> or
1774     <tt>kfree_rcu()</tt>, without having to wait for a subsequent
1775     grace period.
1776 </font></td></tr>
1777 <tr><td>&nbsp;</td></tr>
1778 </table>
1779 
1780 <p>
1781 But what if the updater must wait for the completion of code to be
1782 executed after the end of the grace period, but has other tasks
1783 that can be carried out in the meantime?
1784 The polling-style <tt>get_state_synchronize_rcu()</tt> and
1785 <tt>cond_synchronize_rcu()</tt> functions may be used for this
1786 purpose, as shown below:
1787 
1788 <blockquote>
1789 <pre>
1790  1 bool remove_gp_poll(void)
1791  2 {
1792  3   struct foo *p;
1793  4   unsigned long s;
1794  5
1795  6   spin_lock(&amp;gp_lock);
1796  7   p = rcu_access_pointer(gp);
1797  8   if (!p) {
1798  9     spin_unlock(&amp;gp_lock);
1799 10     return false;
1800 11   }
1801 12   rcu_assign_pointer(gp, NULL);
1802 13   spin_unlock(&amp;gp_lock);
1803 14   s = get_state_synchronize_rcu();
1804 15   do_something_while_waiting();
1805 16   cond_synchronize_rcu(s);
1806 17   kfree(p);
1807 18   return true;
1808 19 }
1809 </pre>
1810 </blockquote>
1811 
1812 <p>
1813 On line&nbsp;14, <tt>get_state_synchronize_rcu()</tt> obtains a
1814 &ldquo;cookie&rdquo; from RCU,
1815 then line&nbsp;15 carries out other tasks,
1816 and finally, line&nbsp;16 returns immediately if a grace period has
1817 elapsed in the meantime, but otherwise waits as required.
1818 The need for <tt>get_state_synchronize_rcu</tt> and
1819 <tt>cond_synchronize_rcu()</tt> has appeared quite recently,
1820 so it is too early to tell whether they will stand the test of time.
1821 
1822 <p>
1823 RCU thus provides a range of tools to allow updaters to strike the
1824 required tradeoff between latency, flexibility and CPU overhead.
1825 
1826 <h3><a name="Composability">Composability</a></h3>
1827 
1828 <p>
1829 Composability has received much attention in recent years, perhaps in part
1830 due to the collision of multicore hardware with object-oriented techniques
1831 designed in single-threaded environments for single-threaded use.
1832 And in theory, RCU read-side critical sections may be composed, and in
1833 fact may be nested arbitrarily deeply.
1834 In practice, as with all real-world implementations of composable
1835 constructs, there are limitations.
1836 
1837 <p>
1838 Implementations of RCU for which <tt>rcu_read_lock()</tt>
1839 and <tt>rcu_read_unlock()</tt> generate no code, such as
1840 Linux-kernel RCU when <tt>CONFIG_PREEMPT=n</tt>, can be
1841 nested arbitrarily deeply.
1842 After all, there is no overhead.
1843 Except that if all these instances of <tt>rcu_read_lock()</tt>
1844 and <tt>rcu_read_unlock()</tt> are visible to the compiler,
1845 compilation will eventually fail due to exhausting memory,
1846 mass storage, or user patience, whichever comes first.
1847 If the nesting is not visible to the compiler, as is the case with
1848 mutually recursive functions each in its own translation unit,
1849 stack overflow will result.
1850 If the nesting takes the form of loops, either the control variable
1851 will overflow or (in the Linux kernel) you will get an RCU CPU stall warning.
1852 Nevertheless, this class of RCU implementations is one
1853 of the most composable constructs in existence.
1854 
1855 <p>
1856 RCU implementations that explicitly track nesting depth
1857 are limited by the nesting-depth counter.
1858 For example, the Linux kernel's preemptible RCU limits nesting to
1859 <tt>INT_MAX</tt>.
1860 This should suffice for almost all practical purposes.
1861 That said, a consecutive pair of RCU read-side critical sections
1862 between which there is an operation that waits for a grace period
1863 cannot be enclosed in another RCU read-side critical section.
1864 This is because it is not legal to wait for a grace period within
1865 an RCU read-side critical section:  To do so would result either
1866 in deadlock or
1867 in RCU implicitly splitting the enclosing RCU read-side critical
1868 section, neither of which is conducive to a long-lived and prosperous
1869 kernel.
1870 
1871 <p>
1872 It is worth noting that RCU is not alone in limiting composability.
1873 For example, many transactional-memory implementations prohibit
1874 composing a pair of transactions separated by an irrevocable
1875 operation (for example, a network receive operation).
1876 For another example, lock-based critical sections can be composed
1877 surprisingly freely, but only if deadlock is avoided.
1878 
1879 <p>
1880 In short, although RCU read-side critical sections are highly composable,
1881 care is required in some situations, just as is the case for any other
1882 composable synchronization mechanism.
1883 
1884 <h3><a name="Corner Cases">Corner Cases</a></h3>
1885 
1886 <p>
1887 A given RCU workload might have an endless and intense stream of
1888 RCU read-side critical sections, perhaps even so intense that there
1889 was never a point in time during which there was not at least one
1890 RCU read-side critical section in flight.
1891 RCU cannot allow this situation to block grace periods:  As long as
1892 all the RCU read-side critical sections are finite, grace periods
1893 must also be finite.
1894 
1895 <p>
1896 That said, preemptible RCU implementations could potentially result
1897 in RCU read-side critical sections being preempted for long durations,
1898 which has the effect of creating a long-duration RCU read-side
1899 critical section.
1900 This situation can arise only in heavily loaded systems, but systems using
1901 real-time priorities are of course more vulnerable.
1902 Therefore, RCU priority boosting is provided to help deal with this
1903 case.
1904 That said, the exact requirements on RCU priority boosting will likely
1905 evolve as more experience accumulates.
1906 
1907 <p>
1908 Other workloads might have very high update rates.
1909 Although one can argue that such workloads should instead use
1910 something other than RCU, the fact remains that RCU must
1911 handle such workloads gracefully.
1912 This requirement is another factor driving batching of grace periods,
1913 but it is also the driving force behind the checks for large numbers
1914 of queued RCU callbacks in the <tt>call_rcu()</tt> code path.
1915 Finally, high update rates should not delay RCU read-side critical
1916 sections, although some read-side delays can occur when using
1917 <tt>synchronize_rcu_expedited()</tt>, courtesy of this function's use
1918 of <tt>try_stop_cpus()</tt>.
1919 (In the future, <tt>synchronize_rcu_expedited()</tt> will be
1920 converted to use lighter-weight inter-processor interrupts (IPIs),
1921 but this will still disturb readers, though to a much smaller degree.)
1922 
1923 <p>
1924 Although all three of these corner cases were understood in the early
1925 1990s, a simple user-level test consisting of <tt>close(open(path))</tt>
1926 in a tight loop
1927 in the early 2000s suddenly provided a much deeper appreciation of the
1928 high-update-rate corner case.
1929 This test also motivated addition of some RCU code to react to high update
1930 rates, for example, if a given CPU finds itself with more than 10,000
1931 RCU callbacks queued, it will cause RCU to take evasive action by
1932 more aggressively starting grace periods and more aggressively forcing
1933 completion of grace-period processing.
1934 This evasive action causes the grace period to complete more quickly,
1935 but at the cost of restricting RCU's batching optimizations, thus
1936 increasing the CPU overhead incurred by that grace period.
1937 
1938 <h2><a name="Software-Engineering Requirements">
1939 Software-Engineering Requirements</a></h2>
1940 
1941 <p>
1942 Between Murphy's Law and &ldquo;To err is human&rdquo;, it is necessary to
1943 guard against mishaps and misuse:
1944 
1945 <ol>
1946 <li>    It is all too easy to forget to use <tt>rcu_read_lock()</tt>
1947     everywhere that it is needed, so kernels built with
1948     <tt>CONFIG_PROVE_RCU=y</tt> will spat if
1949     <tt>rcu_dereference()</tt> is used outside of an
1950     RCU read-side critical section.
1951     Update-side code can use <tt>rcu_dereference_protected()</tt>,
1952     which takes a
1953     <a href="https://lwn.net/Articles/371986/">lockdep expression</a>
1954     to indicate what is providing the protection.
1955     If the indicated protection is not provided, a lockdep splat
1956     is emitted.
1957 
1958     <p>
1959     Code shared between readers and updaters can use
1960     <tt>rcu_dereference_check()</tt>, which also takes a
1961     lockdep expression, and emits a lockdep splat if neither
1962     <tt>rcu_read_lock()</tt> nor the indicated protection
1963     is in place.
1964     In addition, <tt>rcu_dereference_raw()</tt> is used in those
1965     (hopefully rare) cases where the required protection cannot
1966     be easily described.
1967     Finally, <tt>rcu_read_lock_held()</tt> is provided to
1968     allow a function to verify that it has been invoked within
1969     an RCU read-side critical section.
1970     I was made aware of this set of requirements shortly after Thomas
1971     Gleixner audited a number of RCU uses.
1972 <li>    A given function might wish to check for RCU-related preconditions
1973     upon entry, before using any other RCU API.
1974     The <tt>rcu_lockdep_assert()</tt> does this job,
1975     asserting the expression in kernels having lockdep enabled
1976     and doing nothing otherwise.
1977 <li>    It is also easy to forget to use <tt>rcu_assign_pointer()</tt>
1978     and <tt>rcu_dereference()</tt>, perhaps (incorrectly)
1979     substituting a simple assignment.
1980     To catch this sort of error, a given RCU-protected pointer may be
1981     tagged with <tt>__rcu</tt>, after which running sparse
1982     with <tt>CONFIG_SPARSE_RCU_POINTER=y</tt> will complain
1983     about simple-assignment accesses to that pointer.
1984     Arnd Bergmann made me aware of this requirement, and also
1985     supplied the needed
1986     <a href="https://lwn.net/Articles/376011/">patch series</a>.
1987 <li>    Kernels built with <tt>CONFIG_DEBUG_OBJECTS_RCU_HEAD=y</tt>
1988     will splat if a data element is passed to <tt>call_rcu()</tt>
1989     twice in a row, without a grace period in between.
1990     (This error is similar to a double free.)
1991     The corresponding <tt>rcu_head</tt> structures that are
1992     dynamically allocated are automatically tracked, but
1993     <tt>rcu_head</tt> structures allocated on the stack
1994     must be initialized with <tt>init_rcu_head_on_stack()</tt>
1995     and cleaned up with <tt>destroy_rcu_head_on_stack()</tt>.
1996     Similarly, statically allocated non-stack <tt>rcu_head</tt>
1997     structures must be initialized with <tt>init_rcu_head()</tt>
1998     and cleaned up with <tt>destroy_rcu_head()</tt>.
1999     Mathieu Desnoyers made me aware of this requirement, and also
2000     supplied the needed
2001     <a href="https://lkml.kernel.org/g/20100319013024.GA28456@Krystal">patch</a>.
2002 <li>    An infinite loop in an RCU read-side critical section will
2003     eventually trigger an RCU CPU stall warning splat, with
2004     the duration of &ldquo;eventually&rdquo; being controlled by the
2005     <tt>RCU_CPU_STALL_TIMEOUT</tt> <tt>Kconfig</tt> option, or,
2006     alternatively, by the
2007     <tt>rcupdate.rcu_cpu_stall_timeout</tt> boot/sysfs
2008     parameter.
2009     However, RCU is not obligated to produce this splat
2010     unless there is a grace period waiting on that particular
2011     RCU read-side critical section.
2012     <p>
2013     Some extreme workloads might intentionally delay
2014     RCU grace periods, and systems running those workloads can
2015     be booted with <tt>rcupdate.rcu_cpu_stall_suppress</tt>
2016     to suppress the splats.
2017     This kernel parameter may also be set via <tt>sysfs</tt>.
2018     Furthermore, RCU CPU stall warnings are counter-productive
2019     during sysrq dumps and during panics.
2020     RCU therefore supplies the <tt>rcu_sysrq_start()</tt> and
2021     <tt>rcu_sysrq_end()</tt> API members to be called before
2022     and after long sysrq dumps.
2023     RCU also supplies the <tt>rcu_panic()</tt> notifier that is
2024     automatically invoked at the beginning of a panic to suppress
2025     further RCU CPU stall warnings.
2026 
2027     <p>
2028     This requirement made itself known in the early 1990s, pretty
2029     much the first time that it was necessary to debug a CPU stall.
2030     That said, the initial implementation in DYNIX/ptx was quite
2031     generic in comparison with that of Linux.
2032 <li>    Although it would be very good to detect pointers leaking out
2033     of RCU read-side critical sections, there is currently no
2034     good way of doing this.
2035     One complication is the need to distinguish between pointers
2036     leaking and pointers that have been handed off from RCU to
2037     some other synchronization mechanism, for example, reference
2038     counting.
2039 <li>    In kernels built with <tt>CONFIG_RCU_TRACE=y</tt>, RCU-related
2040     information is provided via both debugfs and event tracing.
2041 <li>    Open-coded use of <tt>rcu_assign_pointer()</tt> and
2042     <tt>rcu_dereference()</tt> to create typical linked
2043     data structures can be surprisingly error-prone.
2044     Therefore, RCU-protected
2045     <a href="https://lwn.net/Articles/609973/#RCU List APIs">linked lists</a>
2046     and, more recently, RCU-protected
2047     <a href="https://lwn.net/Articles/612100/">hash tables</a>
2048     are available.
2049     Many other special-purpose RCU-protected data structures are
2050     available in the Linux kernel and the userspace RCU library.
2051 <li>    Some linked structures are created at compile time, but still
2052     require <tt>__rcu</tt> checking.
2053     The <tt>RCU_POINTER_INITIALIZER()</tt> macro serves this
2054     purpose.
2055 <li>    It is not necessary to use <tt>rcu_assign_pointer()</tt>
2056     when creating linked structures that are to be published via
2057     a single external pointer.
2058     The <tt>RCU_INIT_POINTER()</tt> macro is provided for
2059     this task and also for assigning <tt>NULL</tt> pointers
2060     at runtime.
2061 </ol>
2062 
2063 <p>
2064 This not a hard-and-fast list:  RCU's diagnostic capabilities will
2065 continue to be guided by the number and type of usage bugs found
2066 in real-world RCU usage.
2067 
2068 <h2><a name="Linux Kernel Complications">Linux Kernel Complications</a></h2>
2069 
2070 <p>
2071 The Linux kernel provides an interesting environment for all kinds of
2072 software, including RCU.
2073 Some of the relevant points of interest are as follows:
2074 
2075 <ol>
2076 <li>    <a href="#Configuration">Configuration</a>.
2077 <li>    <a href="#Firmware Interface">Firmware Interface</a>.
2078 <li>    <a href="#Early Boot">Early Boot</a>.
2079 <li>    <a href="#Interrupts and NMIs">
2080     Interrupts and non-maskable interrupts (NMIs)</a>.
2081 <li>    <a href="#Loadable Modules">Loadable Modules</a>.
2082 <li>    <a href="#Hotplug CPU">Hotplug CPU</a>.
2083 <li>    <a href="#Scheduler and RCU">Scheduler and RCU</a>.
2084 <li>    <a href="#Tracing and RCU">Tracing and RCU</a>.
2085 <li>    <a href="#Energy Efficiency">Energy Efficiency</a>.
2086 <li>    <a href="#Memory Efficiency">Memory Efficiency</a>.
2087 <li>    <a href="#Performance, Scalability, Response Time, and Reliability">
2088     Performance, Scalability, Response Time, and Reliability</a>.
2089 </ol>
2090 
2091 <p>
2092 This list is probably incomplete, but it does give a feel for the
2093 most notable Linux-kernel complications.
2094 Each of the following sections covers one of the above topics.
2095 
2096 <h3><a name="Configuration">Configuration</a></h3>
2097 
2098 <p>
2099 RCU's goal is automatic configuration, so that almost nobody
2100 needs to worry about RCU's <tt>Kconfig</tt> options.
2101 And for almost all users, RCU does in fact work well
2102 &ldquo;out of the box.&rdquo;
2103 
2104 <p>
2105 However, there are specialized use cases that are handled by
2106 kernel boot parameters and <tt>Kconfig</tt> options.
2107 Unfortunately, the <tt>Kconfig</tt> system will explicitly ask users
2108 about new <tt>Kconfig</tt> options, which requires almost all of them
2109 be hidden behind a <tt>CONFIG_RCU_EXPERT</tt> <tt>Kconfig</tt> option.
2110 
2111 <p>
2112 This all should be quite obvious, but the fact remains that
2113 Linus Torvalds recently had to
2114 <a href="https://lkml.kernel.org/g/CA+55aFy4wcCwaL4okTs8wXhGZ5h-ibecy_Meg9C4MNQrUnwMcg@mail.gmail.com">remind</a>
2115 me of this requirement.
2116 
2117 <h3><a name="Firmware Interface">Firmware Interface</a></h3>
2118 
2119 <p>
2120 In many cases, kernel obtains information about the system from the
2121 firmware, and sometimes things are lost in translation.
2122 Or the translation is accurate, but the original message is bogus.
2123 
2124 <p>
2125 For example, some systems' firmware overreports the number of CPUs,
2126 sometimes by a large factor.
2127 If RCU naively believed the firmware, as it used to do,
2128 it would create too many per-CPU kthreads.
2129 Although the resulting system will still run correctly, the extra
2130 kthreads needlessly consume memory and can cause confusion
2131 when they show up in <tt>ps</tt> listings.
2132 
2133 <p>
2134 RCU must therefore wait for a given CPU to actually come online before
2135 it can allow itself to believe that the CPU actually exists.
2136 The resulting &ldquo;ghost CPUs&rdquo; (which are never going to
2137 come online) cause a number of
2138 <a href="https://paulmck.livejournal.com/37494.html">interesting complications</a>.
2139 
2140 <h3><a name="Early Boot">Early Boot</a></h3>
2141 
2142 <p>
2143 The Linux kernel's boot sequence is an interesting process,
2144 and RCU is used early, even before <tt>rcu_init()</tt>
2145 is invoked.
2146 In fact, a number of RCU's primitives can be used as soon as the
2147 initial task's <tt>task_struct</tt> is available and the
2148 boot CPU's per-CPU variables are set up.
2149 The read-side primitives (<tt>rcu_read_lock()</tt>,
2150 <tt>rcu_read_unlock()</tt>, <tt>rcu_dereference()</tt>,
2151 and <tt>rcu_access_pointer()</tt>) will operate normally very early on,
2152 as will <tt>rcu_assign_pointer()</tt>.
2153 
2154 <p>
2155 Although <tt>call_rcu()</tt> may be invoked at any
2156 time during boot, callbacks are not guaranteed to be invoked until after
2157 the scheduler is fully up and running.
2158 This delay in callback invocation is due to the fact that RCU does not
2159 invoke callbacks until it is fully initialized, and this full initialization
2160 cannot occur until after the scheduler has initialized itself to the
2161 point where RCU can spawn and run its kthreads.
2162 In theory, it would be possible to invoke callbacks earlier,
2163 however, this is not a panacea because there would be severe restrictions
2164 on what operations those callbacks could invoke.
2165 
2166 <p>
2167 Perhaps surprisingly, <tt>synchronize_rcu()</tt>,
2168 <a href="#Bottom-Half Flavor"><tt>synchronize_rcu_bh()</tt></a>
2169 (<a href="#Bottom-Half Flavor">discussed below</a>),
2170 and
2171 <a href="#Sched Flavor"><tt>synchronize_sched()</tt></a>
2172 will all operate normally
2173 during very early boot, the reason being that there is only one CPU
2174 and preemption is disabled.
2175 This means that the call <tt>synchronize_rcu()</tt> (or friends)
2176 itself is a quiescent
2177 state and thus a grace period, so the early-boot implementation can
2178 be a no-op.
2179 
2180 <p>
2181 Both <tt>synchronize_rcu_bh()</tt> and <tt>synchronize_sched()</tt>
2182 continue to operate normally through the remainder of boot, courtesy
2183 of the fact that preemption is disabled across their RCU read-side
2184 critical sections and also courtesy of the fact that there is still
2185 only one CPU.
2186 However, once the scheduler starts initializing, preemption is enabled.
2187 There is still only a single CPU, but the fact that preemption is enabled
2188 means that the no-op implementation of <tt>synchronize_rcu()</tt> no
2189 longer works in <tt>CONFIG_PREEMPT=y</tt> kernels.
2190 Therefore, as soon as the scheduler starts initializing, the early-boot
2191 fastpath is disabled.
2192 This means that <tt>synchronize_rcu()</tt> switches to its runtime
2193 mode of operation where it posts callbacks, which in turn means that
2194 any call to <tt>synchronize_rcu()</tt> will block until the corresponding
2195 callback is invoked.
2196 Unfortunately, the callback cannot be invoked until RCU's runtime
2197 grace-period machinery is up and running, which cannot happen until
2198 the scheduler has initialized itself sufficiently to allow RCU's
2199 kthreads to be spawned.
2200 Therefore, invoking <tt>synchronize_rcu()</tt> during scheduler
2201 initialization can result in deadlock.
2202 
2203 <table>
2204 <tr><th>&nbsp;</th></tr>
2205 <tr><th align="left">Quick Quiz:</th></tr>
2206 <tr><td>
2207     So what happens with <tt>synchronize_rcu()</tt> during
2208     scheduler initialization for <tt>CONFIG_PREEMPT=n</tt>
2209     kernels?
2210 </td></tr>
2211 <tr><th align="left">Answer:</th></tr>
2212 <tr><td bgcolor="#ffffff"><font color="ffffff">
2213     In <tt>CONFIG_PREEMPT=n</tt> kernel, <tt>synchronize_rcu()</tt>
2214     maps directly to <tt>synchronize_sched()</tt>.
2215     Therefore, <tt>synchronize_rcu()</tt> works normally throughout
2216     boot in <tt>CONFIG_PREEMPT=n</tt> kernels.
2217     However, your code must also work in <tt>CONFIG_PREEMPT=y</tt> kernels,
2218     so it is still necessary to avoid invoking <tt>synchronize_rcu()</tt>
2219     during scheduler initialization.
2220 </font></td></tr>
2221 <tr><td>&nbsp;</td></tr>
2222 </table>
2223 
2224 <p>
2225 I learned of these boot-time requirements as a result of a series of
2226 system hangs.
2227 
2228 <h3><a name="Interrupts and NMIs">Interrupts and NMIs</a></h3>
2229 
2230 <p>
2231 The Linux kernel has interrupts, and RCU read-side critical sections are
2232 legal within interrupt handlers and within interrupt-disabled regions
2233 of code, as are invocations of <tt>call_rcu()</tt>.
2234 
2235 <p>
2236 Some Linux-kernel architectures can enter an interrupt handler from
2237 non-idle process context, and then just never leave it, instead stealthily
2238 transitioning back to process context.
2239 This trick is sometimes used to invoke system calls from inside the kernel.
2240 These &ldquo;half-interrupts&rdquo; mean that RCU has to be very careful
2241 about how it counts interrupt nesting levels.
2242 I learned of this requirement the hard way during a rewrite
2243 of RCU's dyntick-idle code.
2244 
2245 <p>
2246 The Linux kernel has non-maskable interrupts (NMIs), and
2247 RCU read-side critical sections are legal within NMI handlers.
2248 Thankfully, RCU update-side primitives, including
2249 <tt>call_rcu()</tt>, are prohibited within NMI handlers.
2250 
2251 <p>
2252 The name notwithstanding, some Linux-kernel architectures
2253 can have nested NMIs, which RCU must handle correctly.
2254 Andy Lutomirski
2255 <a href="https://lkml.kernel.org/g/CALCETrXLq1y7e_dKFPgou-FKHB6Pu-r8+t-6Ds+8=va7anBWDA@mail.gmail.com">surprised me</a>
2256 with this requirement;
2257 he also kindly surprised me with
2258 <a href="https://lkml.kernel.org/g/CALCETrXSY9JpW3uE6H8WYk81sg56qasA2aqmjMPsq5dOtzso=g@mail.gmail.com">an algorithm</a>
2259 that meets this requirement.
2260 
2261 <h3><a name="Loadable Modules">Loadable Modules</a></h3>
2262 
2263 <p>
2264 The Linux kernel has loadable modules, and these modules can
2265 also be unloaded.
2266 After a given module has been unloaded, any attempt to call
2267 one of its functions results in a segmentation fault.
2268 The module-unload functions must therefore cancel any
2269 delayed calls to loadable-module functions, for example,
2270 any outstanding <tt>mod_timer()</tt> must be dealt with
2271 via <tt>del_timer_sync()</tt> or similar.
2272 
2273 <p>
2274 Unfortunately, there is no way to cancel an RCU callback;
2275 once you invoke <tt>call_rcu()</tt>, the callback function is
2276 going to eventually be invoked, unless the system goes down first.
2277 Because it is normally considered socially irresponsible to crash the system
2278 in response to a module unload request, we need some other way
2279 to deal with in-flight RCU callbacks.
2280 
2281 <p>
2282 RCU therefore provides
2283 <tt><a href="https://lwn.net/Articles/217484/">rcu_barrier()</a></tt>,
2284 which waits until all in-flight RCU callbacks have been invoked.
2285 If a module uses <tt>call_rcu()</tt>, its exit function should therefore
2286 prevent any future invocation of <tt>call_rcu()</tt>, then invoke
2287 <tt>rcu_barrier()</tt>.
2288 In theory, the underlying module-unload code could invoke
2289 <tt>rcu_barrier()</tt> unconditionally, but in practice this would
2290 incur unacceptable latencies.
2291 
2292 <p>
2293 Nikita Danilov noted this requirement for an analogous filesystem-unmount
2294 situation, and Dipankar Sarma incorporated <tt>rcu_barrier()</tt> into RCU.
2295 The need for <tt>rcu_barrier()</tt> for module unloading became
2296 apparent later.
2297 
2298 <h3><a name="Hotplug CPU">Hotplug CPU</a></h3>
2299 
2300 <p>
2301 The Linux kernel supports CPU hotplug, which means that CPUs
2302 can come and go.
2303 It is of course illegal to use any RCU API member from an offline CPU.
2304 This requirement was present from day one in DYNIX/ptx, but
2305 on the other hand, the Linux kernel's CPU-hotplug implementation
2306 is &ldquo;interesting.&rdquo;
2307 
2308 <p>
2309 The Linux-kernel CPU-hotplug implementation has notifiers that
2310 are used to allow the various kernel subsystems (including RCU)
2311 to respond appropriately to a given CPU-hotplug operation.
2312 Most RCU operations may be invoked from CPU-hotplug notifiers,
2313 including even normal synchronous grace-period operations
2314 such as <tt>synchronize_rcu()</tt>.
2315 However, expedited grace-period operations such as
2316 <tt>synchronize_rcu_expedited()</tt> are not supported,
2317 due to the fact that current implementations block CPU-hotplug
2318 operations, which could result in deadlock.
2319 
2320 <p>
2321 In addition, all-callback-wait operations such as
2322 <tt>rcu_barrier()</tt> are also not supported, due to the
2323 fact that there are phases of CPU-hotplug operations where
2324 the outgoing CPU's callbacks will not be invoked until after
2325 the CPU-hotplug operation ends, which could also result in deadlock.
2326 
2327 <h3><a name="Scheduler and RCU">Scheduler and RCU</a></h3>
2328 
2329 <p>
2330 RCU depends on the scheduler, and the scheduler uses RCU to
2331 protect some of its data structures.
2332 This means the scheduler is forbidden from acquiring
2333 the runqueue locks and the priority-inheritance locks
2334 in the middle of an outermost RCU read-side critical section unless either
2335 (1)&nbsp;it releases them before exiting that same
2336 RCU read-side critical section, or
2337 (2)&nbsp;interrupts are disabled across
2338 that entire RCU read-side critical section.
2339 This same prohibition also applies (recursively!) to any lock that is acquired
2340 while holding any lock to which this prohibition applies.
2341 Adhering to this rule prevents preemptible RCU from invoking
2342 <tt>rcu_read_unlock_special()</tt> while either runqueue or
2343 priority-inheritance locks are held, thus avoiding deadlock.
2344 
2345 <p>
2346 Prior to v4.4, it was only necessary to disable preemption across
2347 RCU read-side critical sections that acquired scheduler locks.
2348 In v4.4, expedited grace periods started using IPIs, and these
2349 IPIs could force a <tt>rcu_read_unlock()</tt> to take the slowpath.
2350 Therefore, this expedited-grace-period change required disabling of
2351 interrupts, not just preemption.
2352 
2353 <p>
2354 For RCU's part, the preemptible-RCU <tt>rcu_read_unlock()</tt>
2355 implementation must be written carefully to avoid similar deadlocks.
2356 In particular, <tt>rcu_read_unlock()</tt> must tolerate an
2357 interrupt where the interrupt handler invokes both
2358 <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>.
2359 This possibility requires <tt>rcu_read_unlock()</tt> to use
2360 negative nesting levels to avoid destructive recursion via
2361 interrupt handler's use of RCU.
2362 
2363 <p>
2364 This pair of mutual scheduler-RCU requirements came as a
2365 <a href="https://lwn.net/Articles/453002/">complete surprise</a>.
2366 
2367 <p>
2368 As noted above, RCU makes use of kthreads, and it is necessary to
2369 avoid excessive CPU-time accumulation by these kthreads.
2370 This requirement was no surprise, but RCU's violation of it
2371 when running context-switch-heavy workloads when built with
2372 <tt>CONFIG_NO_HZ_FULL=y</tt>
2373 <a href="http://www.rdrop.com/users/paulmck/scalability/paper/BareMetal.2015.01.15b.pdf">did come as a surprise [PDF]</a>.
2374 RCU has made good progress towards meeting this requirement, even
2375 for context-switch-have <tt>CONFIG_NO_HZ_FULL=y</tt> workloads,
2376 but there is room for further improvement.
2377 
2378 <h3><a name="Tracing and RCU">Tracing and RCU</a></h3>
2379 
2380 <p>
2381 It is possible to use tracing on RCU code, but tracing itself
2382 uses RCU.
2383 For this reason, <tt>rcu_dereference_raw_notrace()</tt>
2384 is provided for use by tracing, which avoids the destructive
2385 recursion that could otherwise ensue.
2386 This API is also used by virtualization in some architectures,
2387 where RCU readers execute in environments in which tracing
2388 cannot be used.
2389 The tracing folks both located the requirement and provided the
2390 needed fix, so this surprise requirement was relatively painless.
2391 
2392 <h3><a name="Energy Efficiency">Energy Efficiency</a></h3>
2393 
2394 <p>
2395 Interrupting idle CPUs is considered socially unacceptable,
2396 especially by people with battery-powered embedded systems.
2397 RCU therefore conserves energy by detecting which CPUs are
2398 idle, including tracking CPUs that have been interrupted from idle.
2399 This is a large part of the energy-efficiency requirement,
2400 so I learned of this via an irate phone call.
2401 
2402 <p>
2403 Because RCU avoids interrupting idle CPUs, it is illegal to
2404 execute an RCU read-side critical section on an idle CPU.
2405 (Kernels built with <tt>CONFIG_PROVE_RCU=y</tt> will splat
2406 if you try it.)
2407 The <tt>RCU_NONIDLE()</tt> macro and <tt>_rcuidle</tt>
2408 event tracing is provided to work around this restriction.
2409 In addition, <tt>rcu_is_watching()</tt> may be used to
2410 test whether or not it is currently legal to run RCU read-side
2411 critical sections on this CPU.
2412 I learned of the need for diagnostics on the one hand
2413 and <tt>RCU_NONIDLE()</tt> on the other while inspecting
2414 idle-loop code.
2415 Steven Rostedt supplied <tt>_rcuidle</tt> event tracing,
2416 which is used quite heavily in the idle loop.
2417 However, there are some restrictions on the code placed within
2418 <tt>RCU_NONIDLE()</tt>:
2419 
2420 <ol>
2421 <li>    Blocking is prohibited.
2422     In practice, this is not a serious restriction given that idle
2423     tasks are prohibited from blocking to begin with.
2424 <li>    Although nesting <tt>RCU_NONIDLE()</tt> is permited, they cannot
2425     nest indefinitely deeply.
2426     However, given that they can be nested on the order of a million
2427     deep, even on 32-bit systems, this should not be a serious
2428     restriction.
2429     This nesting limit would probably be reached long after the
2430     compiler OOMed or the stack overflowed.
2431 <li>    Any code path that enters <tt>RCU_NONIDLE()</tt> must sequence
2432     out of that same <tt>RCU_NONIDLE()</tt>.
2433     For example, the following is grossly illegal:
2434 
2435     <blockquote>
2436     <pre>
2437  1     RCU_NONIDLE({
2438  2       do_something();
2439  3       goto bad_idea;  /* BUG!!! */
2440  4       do_something_else();});
2441  5   bad_idea:
2442     </pre>
2443     </blockquote>
2444 
2445     <p>
2446     It is just as illegal to transfer control into the middle of
2447     <tt>RCU_NONIDLE()</tt>'s argument.
2448     Yes, in theory, you could transfer in as long as you also
2449     transferred out, but in practice you could also expect to get sharply
2450     worded review comments.
2451 </ol>
2452 
2453 <p>
2454 It is similarly socially unacceptable to interrupt an
2455 <tt>nohz_full</tt> CPU running in userspace.
2456 RCU must therefore track <tt>nohz_full</tt> userspace
2457 execution.
2458 And in
2459 <a href="https://lwn.net/Articles/558284/"><tt>CONFIG_NO_HZ_FULL_SYSIDLE=y</tt></a>
2460 kernels, RCU must separately track idle CPUs on the one hand and
2461 CPUs that are either idle or executing in userspace on the other.
2462 In both cases, RCU must be able to sample state at two points in
2463 time, and be able to determine whether or not some other CPU spent
2464 any time idle and/or executing in userspace.
2465 
2466 <p>
2467 These energy-efficiency requirements have proven quite difficult to
2468 understand and to meet, for example, there have been more than five
2469 clean-sheet rewrites of RCU's energy-efficiency code, the last of
2470 which was finally able to demonstrate
2471 <a href="http://www.rdrop.com/users/paulmck/realtime/paper/AMPenergy.2013.04.19a.pdf">real energy savings running on real hardware [PDF]</a>.
2472 As noted earlier,
2473 I learned of many of these requirements via angry phone calls:
2474 Flaming me on the Linux-kernel mailing list was apparently not
2475 sufficient to fully vent their ire at RCU's energy-efficiency bugs!
2476 
2477 <h3><a name="Memory Efficiency">Memory Efficiency</a></h3>
2478 
2479 <p>
2480 Although small-memory non-realtime systems can simply use Tiny RCU,
2481 code size is only one aspect of memory efficiency.
2482 Another aspect is the size of the <tt>rcu_head</tt> structure
2483 used by <tt>call_rcu()</tt> and <tt>kfree_rcu()</tt>.
2484 Although this structure contains nothing more than a pair of pointers,
2485 it does appear in many RCU-protected data structures, including
2486 some that are size critical.
2487 The <tt>page</tt> structure is a case in point, as evidenced by
2488 the many occurrences of the <tt>union</tt> keyword within that structure.
2489 
2490 <p>
2491 This need for memory efficiency is one reason that RCU uses hand-crafted
2492 singly linked lists to track the <tt>rcu_head</tt> structures that
2493 are waiting for a grace period to elapse.
2494 It is also the reason why <tt>rcu_head</tt> structures do not contain
2495 debug information, such as fields tracking the file and line of the
2496 <tt>call_rcu()</tt> or <tt>kfree_rcu()</tt> that posted them.
2497 Although this information might appear in debug-only kernel builds at some
2498 point, in the meantime, the <tt>-&gt;func</tt> field will often provide
2499 the needed debug information.
2500 
2501 <p>
2502 However, in some cases, the need for memory efficiency leads to even
2503 more extreme measures.
2504 Returning to the <tt>page</tt> structure, the <tt>rcu_head</tt> field
2505 shares storage with a great many other structures that are used at
2506 various points in the corresponding page's lifetime.
2507 In order to correctly resolve certain
2508 <a href="https://lkml.kernel.org/g/1439976106-137226-1-git-send-email-kirill.shutemov@linux.intel.com">race conditions</a>,
2509 the Linux kernel's memory-management subsystem needs a particular bit
2510 to remain zero during all phases of grace-period processing,
2511 and that bit happens to map to the bottom bit of the
2512 <tt>rcu_head</tt> structure's <tt>-&gt;next</tt> field.
2513 RCU makes this guarantee as long as <tt>call_rcu()</tt>
2514 is used to post the callback, as opposed to <tt>kfree_rcu()</tt>
2515 or some future &ldquo;lazy&rdquo;
2516 variant of <tt>call_rcu()</tt> that might one day be created for
2517 energy-efficiency purposes.
2518 
2519 <p>
2520 That said, there are limits.
2521 RCU requires that the <tt>rcu_head</tt> structure be aligned to a
2522 two-byte boundary, and passing a misaligned <tt>rcu_head</tt>
2523 structure to one of the <tt>call_rcu()</tt> family of functions
2524 will result in a splat.
2525 It is therefore necessary to exercise caution when packing
2526 structures containing fields of type <tt>rcu_head</tt>.
2527 Why not a four-byte or even eight-byte alignment requirement?
2528 Because the m68k architecture provides only two-byte alignment,
2529 and thus acts as alignment's least common denominator.
2530 
2531 <p>
2532 The reason for reserving the bottom bit of pointers to
2533 <tt>rcu_head</tt> structures is to leave the door open to
2534 &ldquo;lazy&rdquo; callbacks whose invocations can safely be deferred.
2535 Deferring invocation could potentially have energy-efficiency
2536 benefits, but only if the rate of non-lazy callbacks decreases
2537 significantly for some important workload.
2538 In the meantime, reserving the bottom bit keeps this option open
2539 in case it one day becomes useful.
2540 
2541 <h3><a name="Performance, Scalability, Response Time, and Reliability">
2542 Performance, Scalability, Response Time, and Reliability</a></h3>
2543 
2544 <p>
2545 Expanding on the
2546 <a href="#Performance and Scalability">earlier discussion</a>,
2547 RCU is used heavily by hot code paths in performance-critical
2548 portions of the Linux kernel's networking, security, virtualization,
2549 and scheduling code paths.
2550 RCU must therefore use efficient implementations, especially in its
2551 read-side primitives.
2552 To that end, it would be good if preemptible RCU's implementation
2553 of <tt>rcu_read_lock()</tt> could be inlined, however, doing
2554 this requires resolving <tt>#include</tt> issues with the
2555 <tt>task_struct</tt> structure.
2556 
2557 <p>
2558 The Linux kernel supports hardware configurations with up to
2559 4096 CPUs, which means that RCU must be extremely scalable.
2560 Algorithms that involve frequent acquisitions of global locks or
2561 frequent atomic operations on global variables simply cannot be
2562 tolerated within the RCU implementation.
2563 RCU therefore makes heavy use of a combining tree based on the
2564 <tt>rcu_node</tt> structure.
2565 RCU is required to tolerate all CPUs continuously invoking any
2566 combination of RCU's runtime primitives with minimal per-operation
2567 overhead.
2568 In fact, in many cases, increasing load must <i>decrease</i> the
2569 per-operation overhead, witness the batching optimizations for
2570 <tt>synchronize_rcu()</tt>, <tt>call_rcu()</tt>,
2571 <tt>synchronize_rcu_expedited()</tt>, and <tt>rcu_barrier()</tt>.
2572 As a general rule, RCU must cheerfully accept whatever the
2573 rest of the Linux kernel decides to throw at it.
2574 
2575 <p>
2576 The Linux kernel is used for real-time workloads, especially
2577 in conjunction with the
2578 <a href="https://rt.wiki.kernel.org/index.php/Main_Page">-rt patchset</a>.
2579 The real-time-latency response requirements are such that the
2580 traditional approach of disabling preemption across RCU
2581 read-side critical sections is inappropriate.
2582 Kernels built with <tt>CONFIG_PREEMPT=y</tt> therefore
2583 use an RCU implementation that allows RCU read-side critical
2584 sections to be preempted.
2585 This requirement made its presence known after users made it
2586 clear that an earlier
2587 <a href="https://lwn.net/Articles/107930/">real-time patch</a>
2588 did not meet their needs, in conjunction with some
2589 <a href="https://lkml.kernel.org/g/20050318002026.GA2693@us.ibm.com">RCU issues</a>
2590 encountered by a very early version of the -rt patchset.
2591 
2592 <p>
2593 In addition, RCU must make do with a sub-100-microsecond real-time latency
2594 budget.
2595 In fact, on smaller systems with the -rt patchset, the Linux kernel
2596 provides sub-20-microsecond real-time latencies for the whole kernel,
2597 including RCU.
2598 RCU's scalability and latency must therefore be sufficient for
2599 these sorts of configurations.
2600 To my surprise, the sub-100-microsecond real-time latency budget
2601 <a href="http://www.rdrop.com/users/paulmck/realtime/paper/bigrt.2013.01.31a.LCA.pdf">
2602 applies to even the largest systems [PDF]</a>,
2603 up to and including systems with 4096 CPUs.
2604 This real-time requirement motivated the grace-period kthread, which
2605 also simplified handling of a number of race conditions.
2606 
2607 <p>
2608 RCU must avoid degrading real-time response for CPU-bound threads, whether
2609 executing in usermode (which is one use case for
2610 <tt>CONFIG_NO_HZ_FULL=y</tt>) or in the kernel.
2611 That said, CPU-bound loops in the kernel must execute
2612 <tt>cond_resched_rcu_qs()</tt> at least once per few tens of milliseconds
2613 in order to avoid receiving an IPI from RCU.
2614 
2615 <p>
2616 Finally, RCU's status as a synchronization primitive means that
2617 any RCU failure can result in arbitrary memory corruption that can be
2618 extremely difficult to debug.
2619 This means that RCU must be extremely reliable, which in
2620 practice also means that RCU must have an aggressive stress-test
2621 suite.
2622 This stress-test suite is called <tt>rcutorture</tt>.
2623 
2624 <p>
2625 Although the need for <tt>rcutorture</tt> was no surprise,
2626 the current immense popularity of the Linux kernel is posing
2627 interesting&mdash;and perhaps unprecedented&mdash;validation
2628 challenges.
2629 To see this, keep in mind that there are well over one billion
2630 instances of the Linux kernel running today, given Android
2631 smartphones, Linux-powered televisions, and servers.
2632 This number can be expected to increase sharply with the advent of
2633 the celebrated Internet of Things.
2634 
2635 <p>
2636 Suppose that RCU contains a race condition that manifests on average
2637 once per million years of runtime.
2638 This bug will be occurring about three times per <i>day</i> across
2639 the installed base.
2640 RCU could simply hide behind hardware error rates, given that no one
2641 should really expect their smartphone to last for a million years.
2642 However, anyone taking too much comfort from this thought should
2643 consider the fact that in most jurisdictions, a successful multi-year
2644 test of a given mechanism, which might include a Linux kernel,
2645 suffices for a number of types of safety-critical certifications.
2646 In fact, rumor has it that the Linux kernel is already being used
2647 in production for safety-critical applications.
2648 I don't know about you, but I would feel quite bad if a bug in RCU
2649 killed someone.
2650 Which might explain my recent focus on validation and verification.
2651 
2652 <h2><a name="Other RCU Flavors">Other RCU Flavors</a></h2>
2653 
2654 <p>
2655 One of the more surprising things about RCU is that there are now
2656 no fewer than five <i>flavors</i>, or API families.
2657 In addition, the primary flavor that has been the sole focus up to
2658 this point has two different implementations, non-preemptible and
2659 preemptible.
2660 The other four flavors are listed below, with requirements for each
2661 described in a separate section.
2662 
2663 <ol>
2664 <li>    <a href="#Bottom-Half Flavor">Bottom-Half Flavor</a>
2665 <li>    <a href="#Sched Flavor">Sched Flavor</a>
2666 <li>    <a href="#Sleepable RCU">Sleepable RCU</a>
2667 <li>    <a href="#Tasks RCU">Tasks RCU</a>
2668 <li>    <a href="#Waiting for Multiple Grace Periods">
2669     Waiting for Multiple Grace Periods</a>
2670 </ol>
2671 
2672 <h3><a name="Bottom-Half Flavor">Bottom-Half Flavor</a></h3>
2673 
2674 <p>
2675 The softirq-disable (AKA &ldquo;bottom-half&rdquo;,
2676 hence the &ldquo;_bh&rdquo; abbreviations)
2677 flavor of RCU, or <i>RCU-bh</i>, was developed by
2678 Dipankar Sarma to provide a flavor of RCU that could withstand the
2679 network-based denial-of-service attacks researched by Robert
2680 Olsson.
2681 These attacks placed so much networking load on the system
2682 that some of the CPUs never exited softirq execution,
2683 which in turn prevented those CPUs from ever executing a context switch,
2684 which, in the RCU implementation of that time, prevented grace periods
2685 from ever ending.
2686 The result was an out-of-memory condition and a system hang.
2687 
2688 <p>
2689 The solution was the creation of RCU-bh, which does
2690 <tt>local_bh_disable()</tt>
2691 across its read-side critical sections, and which uses the transition
2692 from one type of softirq processing to another as a quiescent state
2693 in addition to context switch, idle, user mode, and offline.
2694 This means that RCU-bh grace periods can complete even when some of
2695 the CPUs execute in softirq indefinitely, thus allowing algorithms
2696 based on RCU-bh to withstand network-based denial-of-service attacks.
2697 
2698 <p>
2699 Because
2700 <tt>rcu_read_lock_bh()</tt> and <tt>rcu_read_unlock_bh()</tt>
2701 disable and re-enable softirq handlers, any attempt to start a softirq
2702 handlers during the
2703 RCU-bh read-side critical section will be deferred.
2704 In this case, <tt>rcu_read_unlock_bh()</tt>
2705 will invoke softirq processing, which can take considerable time.
2706 One can of course argue that this softirq overhead should be associated
2707 with the code following the RCU-bh read-side critical section rather
2708 than <tt>rcu_read_unlock_bh()</tt>, but the fact
2709 is that most profiling tools cannot be expected to make this sort
2710 of fine distinction.
2711 For example, suppose that a three-millisecond-long RCU-bh read-side
2712 critical section executes during a time of heavy networking load.
2713 There will very likely be an attempt to invoke at least one softirq
2714 handler during that three milliseconds, but any such invocation will
2715 be delayed until the time of the <tt>rcu_read_unlock_bh()</tt>.
2716 This can of course make it appear at first glance as if
2717 <tt>rcu_read_unlock_bh()</tt> was executing very slowly.
2718 
2719 <p>
2720 The
2721 <a href="https://lwn.net/Articles/609973/#RCU Per-Flavor API Table">RCU-bh API</a>
2722 includes
2723 <tt>rcu_read_lock_bh()</tt>,
2724 <tt>rcu_read_unlock_bh()</tt>,
2725 <tt>rcu_dereference_bh()</tt>,
2726 <tt>rcu_dereference_bh_check()</tt>,
2727 <tt>synchronize_rcu_bh()</tt>,
2728 <tt>synchronize_rcu_bh_expedited()</tt>,
2729 <tt>call_rcu_bh()</tt>,
2730 <tt>rcu_barrier_bh()</tt>, and
2731 <tt>rcu_read_lock_bh_held()</tt>.
2732 
2733 <h3><a name="Sched Flavor">Sched Flavor</a></h3>
2734 
2735 <p>
2736 Before preemptible RCU, waiting for an RCU grace period had the
2737 side effect of also waiting for all pre-existing interrupt
2738 and NMI handlers.
2739 However, there are legitimate preemptible-RCU implementations that
2740 do not have this property, given that any point in the code outside
2741 of an RCU read-side critical section can be a quiescent state.
2742 Therefore, <i>RCU-sched</i> was created, which follows &ldquo;classic&rdquo;
2743 RCU in that an RCU-sched grace period waits for for pre-existing
2744 interrupt and NMI handlers.
2745 In kernels built with <tt>CONFIG_PREEMPT=n</tt>, the RCU and RCU-sched
2746 APIs have identical implementations, while kernels built with
2747 <tt>CONFIG_PREEMPT=y</tt> provide a separate implementation for each.
2748 
2749 <p>
2750 Note well that in <tt>CONFIG_PREEMPT=y</tt> kernels,
2751 <tt>rcu_read_lock_sched()</tt> and <tt>rcu_read_unlock_sched()</tt>
2752 disable and re-enable preemption, respectively.
2753 This means that if there was a preemption attempt during the
2754 RCU-sched read-side critical section, <tt>rcu_read_unlock_sched()</tt>
2755 will enter the scheduler, with all the latency and overhead entailed.
2756 Just as with <tt>rcu_read_unlock_bh()</tt>, this can make it look
2757 as if <tt>rcu_read_unlock_sched()</tt> was executing very slowly.
2758 However, the highest-priority task won't be preempted, so that task
2759 will enjoy low-overhead <tt>rcu_read_unlock_sched()</tt> invocations.
2760 
2761 <p>
2762 The
2763 <a href="https://lwn.net/Articles/609973/#RCU Per-Flavor API Table">RCU-sched API</a>
2764 includes
2765 <tt>rcu_read_lock_sched()</tt>,
2766 <tt>rcu_read_unlock_sched()</tt>,
2767 <tt>rcu_read_lock_sched_notrace()</tt>,
2768 <tt>rcu_read_unlock_sched_notrace()</tt>,
2769 <tt>rcu_dereference_sched()</tt>,
2770 <tt>rcu_dereference_sched_check()</tt>,
2771 <tt>synchronize_sched()</tt>,
2772 <tt>synchronize_rcu_sched_expedited()</tt>,
2773 <tt>call_rcu_sched()</tt>,
2774 <tt>rcu_barrier_sched()</tt>, and
2775 <tt>rcu_read_lock_sched_held()</tt>.
2776 However, anything that disables preemption also marks an RCU-sched
2777 read-side critical section, including
2778 <tt>preempt_disable()</tt> and <tt>preempt_enable()</tt>,
2779 <tt>local_irq_save()</tt> and <tt>local_irq_restore()</tt>,
2780 and so on.
2781 
2782 <h3><a name="Sleepable RCU">Sleepable RCU</a></h3>
2783 
2784 <p>
2785 For well over a decade, someone saying &ldquo;I need to block within
2786 an RCU read-side critical section&rdquo; was a reliable indication
2787 that this someone did not understand RCU.
2788 After all, if you are always blocking in an RCU read-side critical
2789 section, you can probably afford to use a higher-overhead synchronization
2790 mechanism.
2791 However, that changed with the advent of the Linux kernel's notifiers,
2792 whose RCU read-side critical
2793 sections almost never sleep, but sometimes need to.
2794 This resulted in the introduction of
2795 <a href="https://lwn.net/Articles/202847/">sleepable RCU</a>,
2796 or <i>SRCU</i>.
2797 
2798 <p>
2799 SRCU allows different domains to be defined, with each such domain
2800 defined by an instance of an <tt>srcu_struct</tt> structure.
2801 A pointer to this structure must be passed in to each SRCU function,
2802 for example, <tt>synchronize_srcu(&amp;ss)</tt>, where
2803 <tt>ss</tt> is the <tt>srcu_struct</tt> structure.
2804 The key benefit of these domains is that a slow SRCU reader in one
2805 domain does not delay an SRCU grace period in some other domain.
2806 That said, one consequence of these domains is that read-side code
2807 must pass a &ldquo;cookie&rdquo; from <tt>srcu_read_lock()</tt>
2808 to <tt>srcu_read_unlock()</tt>, for example, as follows:
2809 
2810 <blockquote>
2811 <pre>
2812  1 int idx;
2813  2
2814  3 idx = srcu_read_lock(&amp;ss);
2815  4 do_something();
2816  5 srcu_read_unlock(&amp;ss, idx);
2817 </pre>
2818 </blockquote>
2819 
2820 <p>
2821 As noted above, it is legal to block within SRCU read-side critical sections,
2822 however, with great power comes great responsibility.
2823 If you block forever in one of a given domain's SRCU read-side critical
2824 sections, then that domain's grace periods will also be blocked forever.
2825 Of course, one good way to block forever is to deadlock, which can
2826 happen if any operation in a given domain's SRCU read-side critical
2827 section can block waiting, either directly or indirectly, for that domain's
2828 grace period to elapse.
2829 For example, this results in a self-deadlock:
2830 
2831 <blockquote>
2832 <pre>
2833  1 int idx;
2834  2
2835  3 idx = srcu_read_lock(&amp;ss);
2836  4 do_something();
2837  5 synchronize_srcu(&amp;ss);
2838  6 srcu_read_unlock(&amp;ss, idx);
2839 </pre>
2840 </blockquote>
2841 
2842 <p>
2843 However, if line&nbsp;5 acquired a mutex that was held across
2844 a <tt>synchronize_srcu()</tt> for domain <tt>ss</tt>,
2845 deadlock would still be possible.
2846 Furthermore, if line&nbsp;5 acquired a mutex that was held across
2847 a <tt>synchronize_srcu()</tt> for some other domain <tt>ss1</tt>,
2848 and if an <tt>ss1</tt>-domain SRCU read-side critical section
2849 acquired another mutex that was held across as <tt>ss</tt>-domain
2850 <tt>synchronize_srcu()</tt>,
2851 deadlock would again be possible.
2852 Such a deadlock cycle could extend across an arbitrarily large number
2853 of different SRCU domains.
2854 Again, with great power comes great responsibility.
2855 
2856 <p>
2857 Unlike the other RCU flavors, SRCU read-side critical sections can
2858 run on idle and even offline CPUs.
2859 This ability requires that <tt>srcu_read_lock()</tt> and
2860 <tt>srcu_read_unlock()</tt> contain memory barriers, which means
2861 that SRCU readers will run a bit slower than would RCU readers.
2862 It also motivates the <tt>smp_mb__after_srcu_read_unlock()</tt>
2863 API, which, in combination with <tt>srcu_read_unlock()</tt>,
2864 guarantees a full memory barrier.
2865 
2866 <p>
2867 The
2868 <a href="https://lwn.net/Articles/609973/#RCU Per-Flavor API Table">SRCU API</a>
2869 includes
2870 <tt>srcu_read_lock()</tt>,
2871 <tt>srcu_read_unlock()</tt>,
2872 <tt>srcu_dereference()</tt>,
2873 <tt>srcu_dereference_check()</tt>,
2874 <tt>synchronize_srcu()</tt>,
2875 <tt>synchronize_srcu_expedited()</tt>,
2876 <tt>call_srcu()</tt>,
2877 <tt>srcu_barrier()</tt>, and
2878 <tt>srcu_read_lock_held()</tt>.
2879 It also includes
2880 <tt>DEFINE_SRCU()</tt>,
2881 <tt>DEFINE_STATIC_SRCU()</tt>, and
2882 <tt>init_srcu_struct()</tt>
2883 APIs for defining and initializing <tt>srcu_struct</tt> structures.
2884 
2885 <h3><a name="Tasks RCU">Tasks RCU</a></h3>
2886 
2887 <p>
2888 Some forms of tracing use &ldquo;tramopolines&rdquo; to handle the
2889 binary rewriting required to install different types of probes.
2890 It would be good to be able to free old trampolines, which sounds
2891 like a job for some form of RCU.
2892 However, because it is necessary to be able to install a trace
2893 anywhere in the code, it is not possible to use read-side markers
2894 such as <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>.
2895 In addition, it does not work to have these markers in the trampoline
2896 itself, because there would need to be instructions following
2897 <tt>rcu_read_unlock()</tt>.
2898 Although <tt>synchronize_rcu()</tt> would guarantee that execution
2899 reached the <tt>rcu_read_unlock()</tt>, it would not be able to
2900 guarantee that execution had completely left the trampoline.
2901 
2902 <p>
2903 The solution, in the form of
2904 <a href="https://lwn.net/Articles/607117/"><i>Tasks RCU</i></a>,
2905 is to have implicit
2906 read-side critical sections that are delimited by voluntary context
2907 switches, that is, calls to <tt>schedule()</tt>,
2908 <tt>cond_resched_rcu_qs()</tt>, and
2909 <tt>synchronize_rcu_tasks()</tt>.
2910 In addition, transitions to and from userspace execution also delimit
2911 tasks-RCU read-side critical sections.
2912 
2913 <p>
2914 The tasks-RCU API is quite compact, consisting only of
2915 <tt>call_rcu_tasks()</tt>,
2916 <tt>synchronize_rcu_tasks()</tt>, and
2917 <tt>rcu_barrier_tasks()</tt>.
2918 
2919 <h3><a name="Waiting for Multiple Grace Periods">
2920 Waiting for Multiple Grace Periods</a></h3>
2921 
2922 <p>
2923 Perhaps you have an RCU protected data structure that is accessed from
2924 RCU read-side critical sections, from softirq handlers, and from
2925 hardware interrupt handlers.
2926 That is three flavors of RCU, the normal flavor, the bottom-half flavor,
2927 and the sched flavor.
2928 How to wait for a compound grace period?
2929 
2930 <p>
2931 The best approach is usually to &ldquo;just say no!&rdquo; and
2932 insert <tt>rcu_read_lock()</tt> and <tt>rcu_read_unlock()</tt>
2933 around each RCU read-side critical section, regardless of what
2934 environment it happens to be in.
2935 But suppose that some of the RCU read-side critical sections are
2936 on extremely hot code paths, and that use of <tt>CONFIG_PREEMPT=n</tt>
2937 is not a viable option, so that <tt>rcu_read_lock()</tt> and
2938 <tt>rcu_read_unlock()</tt> are not free.
2939 What then?
2940 
2941 <p>
2942 You <i>could</i> wait on all three grace periods in succession, as follows:
2943 
2944 <blockquote>
2945 <pre>
2946  1 synchronize_rcu();
2947  2 synchronize_rcu_bh();
2948  3 synchronize_sched();
2949 </pre>
2950 </blockquote>
2951 
2952 <p>
2953 This works, but triples the update-side latency penalty.
2954 In cases where this is not acceptable, <tt>synchronize_rcu_mult()</tt>
2955 may be used to wait on all three flavors of grace period concurrently:
2956 
2957 <blockquote>
2958 <pre>
2959  1 synchronize_rcu_mult(call_rcu, call_rcu_bh, call_rcu_sched);
2960 </pre>
2961 </blockquote>
2962 
2963 <p>
2964 But what if it is necessary to also wait on SRCU?
2965 This can be done as follows:
2966 
2967 <blockquote>
2968 <pre>
2969  1 static void call_my_srcu(struct rcu_head *head,
2970  2        void (*func)(struct rcu_head *head))
2971  3 {
2972  4   call_srcu(&amp;my_srcu, head, func);
2973  5 }
2974  6
2975  7 synchronize_rcu_mult(call_rcu, call_rcu_bh, call_rcu_sched, call_my_srcu);
2976 </pre>
2977 </blockquote>
2978 
2979 <p>
2980 If you needed to wait on multiple different flavors of SRCU
2981 (but why???), you would need to create a wrapper function resembling
2982 <tt>call_my_srcu()</tt> for each SRCU flavor.
2983 
2984 <table>
2985 <tr><th>&nbsp;</th></tr>
2986 <tr><th align="left">Quick Quiz:</th></tr>
2987 <tr><td>
2988     But what if I need to wait for multiple RCU flavors, but I also need
2989     the grace periods to be expedited?
2990 </td></tr>
2991 <tr><th align="left">Answer:</th></tr>
2992 <tr><td bgcolor="#ffffff"><font color="ffffff">
2993     If you are using expedited grace periods, there should be less penalty
2994     for waiting on them in succession.
2995     But if that is nevertheless a problem, you can use workqueues
2996     or multiple kthreads to wait on the various expedited grace
2997     periods concurrently.
2998 </font></td></tr>
2999 <tr><td>&nbsp;</td></tr>
3000 </table>
3001 
3002 <p>
3003 Again, it is usually better to adjust the RCU read-side critical sections
3004 to use a single flavor of RCU, but when this is not feasible, you can use
3005 <tt>synchronize_rcu_mult()</tt>.
3006 
3007 <h2><a name="Possible Future Changes">Possible Future Changes</a></h2>
3008 
3009 <p>
3010 One of the tricks that RCU uses to attain update-side scalability is
3011 to increase grace-period latency with increasing numbers of CPUs.
3012 If this becomes a serious problem, it will be necessary to rework the
3013 grace-period state machine so as to avoid the need for the additional
3014 latency.
3015 
3016 <p>
3017 Expedited grace periods scan the CPUs, so their latency and overhead
3018 increases with increasing numbers of CPUs.
3019 If this becomes a serious problem on large systems, it will be necessary
3020 to do some redesign to avoid this scalability problem.
3021 
3022 <p>
3023 RCU disables CPU hotplug in a few places, perhaps most notably in the
3024 expedited grace-period and <tt>rcu_barrier()</tt> operations.
3025 If there is a strong reason to use expedited grace periods in CPU-hotplug
3026 notifiers, it will be necessary to avoid disabling CPU hotplug.
3027 This would introduce some complexity, so there had better be a <i>very</i>
3028 good reason.
3029 
3030 <p>
3031 The tradeoff between grace-period latency on the one hand and interruptions
3032 of other CPUs on the other hand may need to be re-examined.
3033 The desire is of course for zero grace-period latency as well as zero
3034 interprocessor interrupts undertaken during an expedited grace period
3035 operation.
3036 While this ideal is unlikely to be achievable, it is quite possible that
3037 further improvements can be made.
3038 
3039 <p>
3040 The multiprocessor implementations of RCU use a combining tree that
3041 groups CPUs so as to reduce lock contention and increase cache locality.
3042 However, this combining tree does not spread its memory across NUMA
3043 nodes nor does it align the CPU groups with hardware features such
3044 as sockets or cores.
3045 Such spreading and alignment is currently believed to be unnecessary
3046 because the hotpath read-side primitives do not access the combining
3047 tree, nor does <tt>call_rcu()</tt> in the common case.
3048 If you believe that your architecture needs such spreading and alignment,
3049 then your architecture should also benefit from the
3050 <tt>rcutree.rcu_fanout_leaf</tt> boot parameter, which can be set
3051 to the number of CPUs in a socket, NUMA node, or whatever.
3052 If the number of CPUs is too large, use a fraction of the number of
3053 CPUs.
3054 If the number of CPUs is a large prime number, well, that certainly
3055 is an &ldquo;interesting&rdquo; architectural choice!
3056 More flexible arrangements might be considered, but only if
3057 <tt>rcutree.rcu_fanout_leaf</tt> has proven inadequate, and only
3058 if the inadequacy has been demonstrated by a carefully run and
3059 realistic system-level workload.
3060 
3061 <p>
3062 Please note that arrangements that require RCU to remap CPU numbers will
3063 require extremely good demonstration of need and full exploration of
3064 alternatives.
3065 
3066 <p>
3067 There is an embarrassingly large number of flavors of RCU, and this
3068 number has been increasing over time.
3069 Perhaps it will be possible to combine some at some future date.
3070 
3071 <p>
3072 RCU's various kthreads are reasonably recent additions.
3073 It is quite likely that adjustments will be required to more gracefully
3074 handle extreme loads.
3075 It might also be necessary to be able to relate CPU utilization by
3076 RCU's kthreads and softirq handlers to the code that instigated this
3077 CPU utilization.
3078 For example, RCU callback overhead might be charged back to the
3079 originating <tt>call_rcu()</tt> instance, though probably not
3080 in production kernels.
3081 
3082 <h2><a name="Summary">Summary</a></h2>
3083 
3084 <p>
3085 This document has presented more than two decade's worth of RCU
3086 requirements.
3087 Given that the requirements keep changing, this will not be the last
3088 word on this subject, but at least it serves to get an important
3089 subset of the requirements set forth.
3090 
3091 <h2><a name="Acknowledgments">Acknowledgments</a></h2>
3092 
3093 I am grateful to Steven Rostedt, Lai Jiangshan, Ingo Molnar,
3094 Oleg Nesterov, Borislav Petkov, Peter Zijlstra, Boqun Feng, and
3095 Andy Lutomirski for their help in rendering
3096 this article human readable, and to Michelle Rankin for her support
3097 of this effort.
3098 Other contributions are acknowledged in the Linux kernel's git archive.
3099 The cartoon is copyright (c) 2013 by Melissa Broussard,
3100 and is provided
3101 under the terms of the Creative Commons Attribution-Share Alike 3.0
3102 United States license.
3103 
3104 </body></html>