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