__  __    __   __  _____      _            _          _____ _          _ _ 
 |  \/  |   \ \ / / |  __ \    (_)          | |        / ____| |        | | |
 | \  / |_ __\ V /  | |__) | __ ___   ____ _| |_ ___  | (___ | |__   ___| | |
 | |\/| | '__|> <   |  ___/ '__| \ \ / / _` | __/ _ \  \___ \| '_ \ / _ \ | |
 | |  | | |_ / . \  | |   | |  | |\ V / (_| | ||  __/  ____) | | | |  __/ | |
 |_|  |_|_(_)_/ \_\ |_|   |_|  |_| \_/ \__,_|\__\___| |_____/|_| |_|\___V 2.1
 if you need WebShell for Seo everyday contact me on Telegram
 Telegram Address : @jackleet
        
        
For_More_Tools: Telegram: @jackleet | Bulk Smtp support mail sender | Business Mail Collector | Mail Bouncer All Mail | Bulk Office Mail Validator | Html Letter private



Upload:

Command:

www-data@216.73.217.138: ~ $
<!DOCTYPE html>

<html lang="en" data-content_root="../../../">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>A Tour Through RCU’s Requirements &#8212; The Linux Kernel  documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../_static/pygments.css?v=fa44fd50" />
    <link rel="stylesheet" type="text/css" href="../../../_static/alabaster.css?v=3918102e" />
    <script src="../../../_static/documentation_options.js?v=5929fcd5"></script>
    <script src="../../../_static/doctools.js?v=9bcbadda"></script>
    <script src="../../../_static/sphinx_highlight.js?v=dc90522c"></script>
    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" />
    <link rel="next" title="A Tour Through TREE_RCU’s Data Structures [LWN.net]" href="../Data-Structures/Data-Structures.html" />
    <link rel="prev" title="A Tour Through TREE_RCU’s Expedited Grace Periods" href="../Expedited-Grace-Periods/Expedited-Grace-Periods.html" />
   
  <link rel="stylesheet" href="../../../_static/custom.css" type="text/css" />
  

  
  

  </head><body>
  <div class="document">
    
      <div class="sphinxsidebar" role="navigation" aria-label="Main">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="../../../index.html">
              <img class="logo" src="../../../_static/logo.svg" alt="Logo of The Linux Kernel"/>
            </a></p>
<h1 class="logo"><a href="../../../index.html">The Linux Kernel</a></h1>



<p class="blurb">6.18.50</p>







<search id="searchbox" style="display: none" role="search">
  <h3 id="searchlabel">Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>
    </div>
</search>
<script>document.getElementById('searchbox').style.display = "block"</script>


<p>
<h3 class="kernel-toc-contents">Contents</h3>
<input type="checkbox" class="kernel-toc-toggle" id = "kernel-toc-toggle" checked>
<label class="kernel-toc-title" for="kernel-toc-toggle"></label>

<div class="kerneltoc" id="kerneltoc">
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../process/development-process.html">Development process</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../process/submitting-patches.html">Submitting patches</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../process/code-of-conduct.html">Code of conduct</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../maintainer/index.html">Maintainer handbook</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../process/index.html">All development-process docs</a></li>
</ul>
<ul class="current">
<li class="toctree-l1 current"><a class="reference internal" href="../../../core-api/index.html">Core API</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="../../../core-api/index.html#core-utilities">Core utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../../core-api/index.html#data-structures-and-low-level-utilities">Data structures and low-level utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../../core-api/index.html#low-level-entry-and-exit">Low level entry and exit</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="../../../core-api/index.html#concurrency-primitives">Concurrency primitives</a><ul class="current">
<li class="toctree-l3"><a class="reference internal" href="../../../core-api/refcount-vs-atomic.html">refcount_t API compared to atomic_t</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../core-api/irq/index.html">IRQs</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../core-api/local_ops.html">Semantics and Behavior of Local Atomic Operations</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../core-api/padata.html">The padata parallel execution mechanism</a></li>
<li class="toctree-l3 current"><a class="reference internal" href="../../index.html">RCU Handbook</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../core-api/wrappers/memory-barriers.html">Linux kernel memory barriers</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../../../core-api/index.html#low-level-hardware-management">Low-level hardware management</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../../core-api/index.html#memory-management">Memory management</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../../core-api/index.html#interfaces-for-kernel-debugging">Interfaces for kernel debugging</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../../core-api/index.html#everything-else">Everything else</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../../driver-api/index.html">Driver APIs</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../../../subsystem-apis.html">Subsystems</a><ul class="current">
<li class="toctree-l2 current"><a class="reference internal" href="../../../subsystem-apis.html#core-subsystems">Core subsystems</a><ul class="current">
<li class="toctree-l3 current"><a class="reference internal" href="../../../core-api/index.html">Core API Documentation</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../driver-api/index.html">Driver implementer’s API guide</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../mm/index.html">Memory Management Documentation</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../power/index.html">Power Management</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../scheduler/index.html">Scheduler</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../timers/index.html">Timers</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../locking/index.html">Locking</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../../../subsystem-apis.html#human-interfaces">Human interfaces</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../../subsystem-apis.html#networking-interfaces">Networking interfaces</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../../subsystem-apis.html#storage-interfaces">Storage interfaces</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../../subsystem-apis.html#other-subsystems">Other subsystems</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../../locking/index.html">Locking</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../process/license-rules.html">Licensing rules</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../doc-guide/index.html">Writing documentation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../dev-tools/index.html">Development tools</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../dev-tools/testing-overview.html">Testing guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../kernel-hacking/index.html">Hacking guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../trace/index.html">Tracing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../fault-injection/index.html">Fault injection</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../livepatch/index.html">Livepatching</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../rust/index.html">Rust</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../admin-guide/index.html">Administration</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../kbuild/index.html">Build system</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../admin-guide/reporting-issues.html">Reporting issues</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../tools/index.html">Userspace tools</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../userspace-api/index.html">Userspace API</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../firmware-guide/index.html">Firmware</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../devicetree/index.html">Firmware and Devicetree</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../arch/index.html">CPU architectures</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../staging/index.html">Unsorted documentation</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../translations/index.html">Translations</a></li>
</ul>

</div>

<script type="text/javascript"> <!--
  var sbar = document.getElementsByClassName("sphinxsidebar")[0];
  let currents = document.getElementsByClassName("current")
  if (currents.length) {
    sbar.scrollTop = currents[currents.length - 1].offsetTop;
  }
  --> </script>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../../../_sources/RCU/Design/Requirements/Requirements.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
        </div>
      </div>
      <div class="documentwrapper">
        <div class="bodywrapper">
          

          <div class="body" role="main">
            
  



<section id="a-tour-through-rcu-s-requirements">
<h1>A Tour Through RCU’s Requirements<a class="headerlink" href="#a-tour-through-rcu-s-requirements" title="Link to this heading">¶</a></h1>
<p>Copyright IBM Corporation, 2015</p>
<p>Author: Paul E. McKenney</p>
<p>The initial version of this document appeared in the
<a class="reference external" href="https://lwn.net/">LWN</a> on those articles:
<a class="reference external" href="https://lwn.net/Articles/652156/">part 1</a>,
<a class="reference external" href="https://lwn.net/Articles/652677/">part 2</a>, and
<a class="reference external" href="https://lwn.net/Articles/653326/">part 3</a>.</p>
<section id="introduction">
<h2>Introduction<a class="headerlink" href="#introduction" title="Link to this heading">¶</a></h2>
<p>Read-copy update (RCU) is a synchronization mechanism that is often used
as a replacement for reader-writer locking. RCU is unusual in that
updaters do not block readers, which means that RCU’s read-side
primitives can be exceedingly fast and scalable. In addition, updaters
can make useful forward progress concurrently with readers. However, all
this concurrency between RCU readers and updaters does raise the
question of exactly what RCU readers are doing, which in turn raises the
question of exactly what RCU’s requirements are.</p>
<p>This document therefore summarizes RCU’s requirements, and can be
thought of as an informal, high-level specification for RCU. It is
important to understand that RCU’s specification is primarily empirical
in nature; in fact, I learned about many of these requirements the hard
way. This situation might cause some consternation, however, not only
has this learning process been a lot of fun, but it has also been a
great privilege to work with so many people willing to apply
technologies in interesting new ways.</p>
<p>All that aside, here are the categories of currently known RCU
requirements:</p>
<ol class="arabic simple">
<li><p><a class="reference internal" href="#fundamental-requirements">Fundamental Requirements</a></p></li>
<li><p><a class="reference internal" href="#fundamental-non-requirements">Fundamental Non-Requirements</a></p></li>
<li><p><a class="reference internal" href="#parallelism-facts-of-life">Parallelism Facts of Life</a></p></li>
<li><p><a class="reference internal" href="#quality-of-implementation-requirements">Quality-of-Implementation Requirements</a></p></li>
<li><p><a class="reference internal" href="#linux-kernel-complications">Linux Kernel Complications</a></p></li>
<li><p><a class="reference internal" href="#software-engineering-requirements">Software-Engineering Requirements</a></p></li>
<li><p><a class="reference internal" href="#other-rcu-flavors">Other RCU Flavors</a></p></li>
<li><p><a class="reference internal" href="#possible-future-changes">Possible Future Changes</a></p></li>
</ol>
<p>This is followed by a <a class="reference internal" href="#summary">summary</a>, however, the answers to
each quick quiz immediately follows the quiz. Select the big white space
with your mouse to see the answer.</p>
</section>
<section id="fundamental-requirements">
<h2>Fundamental Requirements<a class="headerlink" href="#fundamental-requirements" title="Link to this heading">¶</a></h2>
<p>RCU’s fundamental requirements are the closest thing RCU has to hard
mathematical requirements. These are:</p>
<ol class="arabic simple">
<li><p><a class="reference internal" href="#grace-period-guarantee">Grace-Period Guarantee</a></p></li>
<li><p><a class="reference internal" href="#publish-subscribe-guarantee">Publish/Subscribe Guarantee</a></p></li>
<li><p><a class="reference internal" href="#memory-barrier-guarantees">Memory-Barrier Guarantees</a></p></li>
<li><p><a class="reference internal" href="#rcu-primitives-guaranteed-to-execute-unconditionally">RCU Primitives Guaranteed to Execute Unconditionally</a></p></li>
<li><p><a class="reference internal" href="#guaranteed-read-to-write-upgrade">Guaranteed Read-to-Write Upgrade</a></p></li>
</ol>
<section id="grace-period-guarantee">
<h3>Grace-Period Guarantee<a class="headerlink" href="#grace-period-guarantee" title="Link to this heading">¶</a></h3>
<p>RCU’s grace-period guarantee is unusual in being premeditated: Jack
Slingwine and I had this guarantee firmly in mind when we started work
on RCU (then called “rclock”) in the early 1990s. That said, the past
two decades of experience with RCU have produced a much more detailed
understanding of this guarantee.</p>
<p>RCU’s grace-period guarantee allows updaters to wait for the completion
of all pre-existing RCU read-side critical sections. An RCU read-side
critical section begins with the marker <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and ends
with the marker <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a>. These markers may be nested, and
RCU treats a nested set as one big RCU read-side critical section.
Production-quality implementations of <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> are extremely lightweight, and in fact have
exactly zero overhead in Linux kernels built for production use with
<code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=n</span></code>.</p>
<p>This guarantee allows ordering to be enforced with extremely low
overhead to readers, for example:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 int x, y;
 2
 3 void thread0(void)
 4 {
 5   rcu_read_lock();
 6   r1 = READ_ONCE(x);
 7   r2 = READ_ONCE(y);
 8   rcu_read_unlock();
 9 }
10
11 void thread1(void)
12 {
13   WRITE_ONCE(x, 1);
14   synchronize_rcu();
15   WRITE_ONCE(y, 1);
16 }
</pre></div>
</div>
</div></blockquote>
<p>Because the <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> on line 14 waits for all pre-existing
readers, any instance of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread0()</span></code> that loads a value of zero from
<code class="docutils literal notranslate"><span class="pre">x</span></code> must complete before <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread1()</span></code> stores to <code class="docutils literal notranslate"><span class="pre">y</span></code>, so that
instance must also load a value of zero from <code class="docutils literal notranslate"><span class="pre">y</span></code>. Similarly, any
instance of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread0()</span></code> that loads a value of one from <code class="docutils literal notranslate"><span class="pre">y</span></code> must have
started after the <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> started, and must therefore also
load a value of one from <code class="docutils literal notranslate"><span class="pre">x</span></code>. Therefore, the outcome:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span>(r1 == 0 &amp;&amp; r2 == 1)
</pre></div>
</div>
</div></blockquote>
<p>cannot happen.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Wait a minute! You said that updaters can make useful forward
progress concurrently with readers, but pre-existing readers will
block <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>!!!
Just who are you trying to fool???</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>First, if updaters do not wish to be blocked by readers, they can use
<a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> or <a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a>, which will be discussed later.
Second, even when using <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>, the other update-side
code does run concurrently with readers, whether pre-existing or not.</p></td>
</tr>
</tbody>
</table>
<p>This scenario resembles one of the first uses of RCU in
<a class="reference external" href="https://en.wikipedia.org/wiki/DYNIX">DYNIX/ptx</a>, which managed a
distributed lock manager’s transition into a state suitable for handling
recovery from node failure, more or less as follows:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 #define STATE_NORMAL        0
 2 #define STATE_WANT_RECOVERY 1
 3 #define STATE_RECOVERING    2
 4 #define STATE_WANT_NORMAL   3
 5
 6 int state = STATE_NORMAL;
 7
 8 void do_something_dlm(void)
 9 {
10   int state_snap;
11
12   rcu_read_lock();
13   state_snap = READ_ONCE(state);
14   if (state_snap == STATE_NORMAL)
15     do_something();
16   else
17     do_something_carefully();
18   rcu_read_unlock();
19 }
20
21 void start_recovery(void)
22 {
23   WRITE_ONCE(state, STATE_WANT_RECOVERY);
24   synchronize_rcu();
25   WRITE_ONCE(state, STATE_RECOVERING);
26   recovery();
27   WRITE_ONCE(state, STATE_WANT_NORMAL);
28   synchronize_rcu();
29   WRITE_ONCE(state, STATE_NORMAL);
30 }
</pre></div>
</div>
</div></blockquote>
<p>The RCU read-side critical section in <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something_dlm()</span></code> works with
the <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> in <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">start_recovery()</span></code> to guarantee that
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something()</span></code> never runs concurrently with <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">recovery()</span></code>, but with
little or no synchronization overhead in <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something_dlm()</span></code>.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Why is the <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> on line 28 needed?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Without that extra grace period, memory reordering could result in
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something_dlm()</span></code> executing <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something()</span></code> concurrently with
the last bits of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">recovery()</span></code>.</p></td>
</tr>
</tbody>
</table>
<p>In order to avoid fatal problems such as deadlocks, an RCU read-side
critical section must not contain calls to <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>.
Similarly, an RCU read-side critical section must not contain anything
that waits, directly or indirectly, on completion of an invocation of
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>.</p>
<p>Although RCU’s grace-period guarantee is useful in and of itself, with
<a class="reference external" href="https://lwn.net/Articles/573497/">quite a few use cases</a>, it would
be good to be able to use RCU to coordinate read-side access to linked
data structures. For this, the grace-period guarantee is not sufficient,
as can be seen in function <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">add_gp_buggy()</span></code> below. We will look at the
reader’s code later, but in the meantime, just think of the reader as
locklessly picking up the <code class="docutils literal notranslate"><span class="pre">gp</span></code> pointer, and, if the value loaded is
non-<code class="docutils literal notranslate"><span class="pre">NULL</span></code>, locklessly accessing the <code class="docutils literal notranslate"><span class="pre">-&gt;a</span></code> and <code class="docutils literal notranslate"><span class="pre">-&gt;b</span></code> fields.</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 bool add_gp_buggy(int a, int b)
 2 {
 3   p = kmalloc(sizeof(*p), GFP_KERNEL);
 4   if (!p)
 5     return -ENOMEM;
 6   spin_lock(&amp;gp_lock);
 7   if (rcu_access_pointer(gp)) {
 8     spin_unlock(&amp;gp_lock);
 9     return false;
10   }
11   p-&gt;a = a;
12   p-&gt;b = a;
13   gp = p; /* ORDERING BUG */
14   spin_unlock(&amp;gp_lock);
15   return true;
16 }
</pre></div>
</div>
</div></blockquote>
<p>The problem is that both the compiler and weakly ordered CPUs are within
their rights to reorder this code as follows:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 bool add_gp_buggy_optimized(int a, int b)
 2 {
 3   p = kmalloc(sizeof(*p), GFP_KERNEL);
 4   if (!p)
 5     return -ENOMEM;
 6   spin_lock(&amp;gp_lock);
 7   if (rcu_access_pointer(gp)) {
 8     spin_unlock(&amp;gp_lock);
 9     return false;
10   }
11   gp = p; /* ORDERING BUG */
12   p-&gt;a = a;
13   p-&gt;b = a;
14   spin_unlock(&amp;gp_lock);
15   return true;
16 }
</pre></div>
</div>
</div></blockquote>
<p>If an RCU reader fetches <code class="docutils literal notranslate"><span class="pre">gp</span></code> just after <code class="docutils literal notranslate"><span class="pre">add_gp_buggy_optimized</span></code>
executes line 11, it will see garbage in the <code class="docutils literal notranslate"><span class="pre">-&gt;a</span></code> and <code class="docutils literal notranslate"><span class="pre">-&gt;b</span></code> fields.
And this is but one of many ways in which compiler and hardware
optimizations could cause trouble. Therefore, we clearly need some way
to prevent the compiler and the CPU from reordering in this manner,
which brings us to the publish-subscribe guarantee discussed in the next
section.</p>
</section>
<section id="publish-subscribe-guarantee">
<h3>Publish/Subscribe Guarantee<a class="headerlink" href="#publish-subscribe-guarantee" title="Link to this heading">¶</a></h3>
<p>RCU’s publish-subscribe guarantee allows data to be inserted into a
linked data structure without disrupting RCU readers. The updater uses
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_assign_pointer" title="rcu_assign_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_assign_pointer()</span></code></a> to insert the new data, and readers use
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> to access data, whether new or old. The following
shows an example of insertion:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 bool add_gp(int a, int b)
 2 {
 3   p = kmalloc(sizeof(*p), GFP_KERNEL);
 4   if (!p)
 5     return -ENOMEM;
 6   spin_lock(&amp;gp_lock);
 7   if (rcu_access_pointer(gp)) {
 8     spin_unlock(&amp;gp_lock);
 9     return false;
10   }
11   p-&gt;a = a;
12   p-&gt;b = a;
13   rcu_assign_pointer(gp, p);
14   spin_unlock(&amp;gp_lock);
15   return true;
16 }
</pre></div>
</div>
</div></blockquote>
<p>The <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_assign_pointer" title="rcu_assign_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_assign_pointer()</span></code></a> on line 13 is conceptually equivalent to a
simple assignment statement, but also guarantees that its assignment
will happen after the two assignments in lines 11 and 12, similar to the
C11 <code class="docutils literal notranslate"><span class="pre">memory_order_release</span></code> store operation. It also prevents any
number of “interesting” compiler optimizations, for example, the use of
<code class="docutils literal notranslate"><span class="pre">gp</span></code> as a scratch location immediately preceding the assignment.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>But <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_assign_pointer" title="rcu_assign_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_assign_pointer()</span></code></a> does nothing to prevent the two
assignments to <code class="docutils literal notranslate"><span class="pre">p-&gt;a</span></code> and <code class="docutils literal notranslate"><span class="pre">p-&gt;b</span></code> from being reordered. Can’t that
also cause problems?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>No, it cannot. The readers cannot see either of these two fields
until the assignment to <code class="docutils literal notranslate"><span class="pre">gp</span></code>, by which time both fields are fully
initialized. So reordering the assignments to <code class="docutils literal notranslate"><span class="pre">p-&gt;a</span></code> and <code class="docutils literal notranslate"><span class="pre">p-&gt;b</span></code>
cannot possibly cause any problems.</p></td>
</tr>
</tbody>
</table>
<p>It is tempting to assume that the reader need not do anything special to
control its accesses to the RCU-protected data, as shown in
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something_gp_buggy()</span></code> below:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 bool do_something_gp_buggy(void)
 2 {
 3   rcu_read_lock();
 4   p = gp;  /* OPTIMIZATIONS GALORE!!! */
 5   if (p) {
 6     do_something(p-&gt;a, p-&gt;b);
 7     rcu_read_unlock();
 8     return true;
 9   }
10   rcu_read_unlock();
11   return false;
12 }
</pre></div>
</div>
</div></blockquote>
<p>However, this temptation must be resisted because there are a
surprisingly large number of ways that the compiler (or weak ordering
CPUs like the DEC Alpha) can trip this code up. For but one example, if
the compiler were short of registers, it might choose to refetch from
<code class="docutils literal notranslate"><span class="pre">gp</span></code> rather than keeping a separate copy in <code class="docutils literal notranslate"><span class="pre">p</span></code> as follows:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 bool do_something_gp_buggy_optimized(void)
 2 {
 3   rcu_read_lock();
 4   if (gp) { /* OPTIMIZATIONS GALORE!!! */
 5     do_something(gp-&gt;a, gp-&gt;b);
 6     rcu_read_unlock();
 7     return true;
 8   }
 9   rcu_read_unlock();
10   return false;
11 }
</pre></div>
</div>
</div></blockquote>
<p>If this function ran concurrently with a series of updates that replaced
the current structure with a new one, the fetches of <code class="docutils literal notranslate"><span class="pre">gp-&gt;a</span></code> and
<code class="docutils literal notranslate"><span class="pre">gp-&gt;b</span></code> might well come from two different structures, which could
cause serious confusion. To prevent this (and much else besides),
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something_gp()</span></code> uses <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> to fetch from <code class="docutils literal notranslate"><span class="pre">gp</span></code>:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 bool do_something_gp(void)
 2 {
 3   rcu_read_lock();
 4   p = rcu_dereference(gp);
 5   if (p) {
 6     do_something(p-&gt;a, p-&gt;b);
 7     rcu_read_unlock();
 8     return true;
 9   }
10   rcu_read_unlock();
11   return false;
12 }
</pre></div>
</div>
</div></blockquote>
<p>The <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> uses volatile casts and (for DEC Alpha) memory
barriers in the Linux kernel. Should a <a class="reference external" href="http://www.rdrop.com/users/paulmck/RCU/consume.2015.07.13a.pdf">high-quality implementation of C11 <code class="docutils literal notranslate"><span class="pre">memory_order_consume</span></code> [PDF]</a>
ever appear, then <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> could be implemented as a
<code class="docutils literal notranslate"><span class="pre">memory_order_consume</span></code> load. Regardless of the exact implementation, a
pointer fetched by <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> may not be used outside of the
outermost RCU read-side critical section containing that
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>, unless protection of the corresponding data
element has been passed from RCU to some other synchronization
mechanism, most commonly locking or reference counting
(see <a class="reference internal" href="../../rcuref.html"><span class="doc">Reference-count design for elements of lists/arrays protected by RCU</span></a>).</p>
<p>In short, updaters use <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_assign_pointer" title="rcu_assign_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_assign_pointer()</span></code></a> and readers use
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>, and these two RCU API elements work together to
ensure that readers have a consistent view of newly added data elements.</p>
<p>Of course, it is also necessary to remove elements from RCU-protected
data structures, for example, using the following process:</p>
<ol class="arabic simple">
<li><p>Remove the data element from the enclosing structure.</p></li>
<li><p>Wait for all pre-existing RCU read-side critical sections to complete
(because only pre-existing readers can possibly have a reference to
the newly removed data element).</p></li>
<li><p>At this point, only the updater has a reference to the newly removed
data element, so it can safely reclaim the data element, for example,
by passing it to <a class="reference internal" href="../../../core-api/mm-api.html#c.kfree" title="kfree"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree()</span></code></a>.</p></li>
</ol>
<p>This process is implemented by <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_synchronous()</span></code>:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 bool remove_gp_synchronous(void)
 2 {
 3   struct foo *p;
 4
 5   spin_lock(&amp;gp_lock);
 6   p = rcu_access_pointer(gp);
 7   if (!p) {
 8     spin_unlock(&amp;gp_lock);
 9     return false;
10   }
11   rcu_assign_pointer(gp, NULL);
12   spin_unlock(&amp;gp_lock);
13   synchronize_rcu();
14   kfree(p);
15   return true;
16 }
</pre></div>
</div>
</div></blockquote>
<p>This function is straightforward, with line 13 waiting for a grace
period before line 14 frees the old data element. This waiting ensures
that readers will reach line 7 of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something_gp()</span></code> before the data
element referenced by <code class="docutils literal notranslate"><span class="pre">p</span></code> is freed. The <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_access_pointer" title="rcu_access_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_access_pointer()</span></code></a> on
line 6 is similar to <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>, except that:</p>
<ol class="arabic simple">
<li><p>The value returned by <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_access_pointer" title="rcu_access_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_access_pointer()</span></code></a> cannot be
dereferenced. If you want to access the value pointed to as well as
the pointer itself, use <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> instead of
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_access_pointer" title="rcu_access_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_access_pointer()</span></code></a>.</p></li>
<li><p>The call to <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_access_pointer" title="rcu_access_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_access_pointer()</span></code></a> need not be protected. In
contrast, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> must either be within an RCU
read-side critical section or in a code segment where the pointer
cannot change, for example, in code protected by the corresponding
update-side lock.</p></li>
</ol>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Without the <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> or the <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_access_pointer" title="rcu_access_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_access_pointer()</span></code></a>,
what destructive optimizations might the compiler make use of?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Let’s start with what happens to <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something_gp()</span></code> if it fails to
use <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>. It could reuse a value formerly fetched
from this same pointer. It could also fetch the pointer from <code class="docutils literal notranslate"><span class="pre">gp</span></code>
in a byte-at-a-time manner, resulting in <em>load tearing</em>, in turn
resulting a bytewise mash-up of two distinct pointer values. It might
even use value-speculation optimizations, where it makes a wrong
guess, but by the time it gets around to checking the value, an
update has changed the pointer to match the wrong guess. Too bad
about any dereferences that returned pre-initialization garbage in
the meantime!
For <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_synchronous()</span></code>, as long as all modifications to
<code class="docutils literal notranslate"><span class="pre">gp</span></code> are carried out while holding <code class="docutils literal notranslate"><span class="pre">gp_lock</span></code>, the above
optimizations are harmless. However, <code class="docutils literal notranslate"><span class="pre">sparse</span></code> will complain if you
define <code class="docutils literal notranslate"><span class="pre">gp</span></code> with <code class="docutils literal notranslate"><span class="pre">__rcu</span></code> and then access it without using either
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_access_pointer" title="rcu_access_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_access_pointer()</span></code></a> or <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>.</p></td>
</tr>
</tbody>
</table>
<p>In short, RCU’s publish-subscribe guarantee is provided by the
combination of <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_assign_pointer" title="rcu_assign_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_assign_pointer()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>. This
guarantee allows data elements to be safely added to RCU-protected
linked data structures without disrupting RCU readers. This guarantee
can be used in combination with the grace-period guarantee to also allow
data elements to be removed from RCU-protected linked data structures,
again without disrupting RCU readers.</p>
<p>This guarantee was only partially premeditated. DYNIX/ptx used an
explicit memory barrier for publication, but had nothing resembling
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> for subscription, nor did it have anything
resembling the dependency-ordering barrier that was later subsumed
into <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> and later still into <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">READ_ONCE()</span></code>. The
need for these operations made itself known quite suddenly at a
late-1990s meeting with the DEC Alpha architects, back in the days when
DEC was still a free-standing company. It took the Alpha architects a
good hour to convince me that any sort of barrier would ever be needed,
and it then took me a good <em>two</em> hours to convince them that their
documentation did not make this point clear. More recent work with the C
and C++ standards committees have provided much education on tricks and
traps from the compiler. In short, compilers were much less tricky in
the early 1990s, but in 2015, don’t even think about omitting
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>!</p>
</section>
<section id="memory-barrier-guarantees">
<h3>Memory-Barrier Guarantees<a class="headerlink" href="#memory-barrier-guarantees" title="Link to this heading">¶</a></h3>
<p>The previous section’s simple linked-data-structure scenario clearly
demonstrates the need for RCU’s stringent memory-ordering guarantees on
systems with more than one CPU:</p>
<ol class="arabic simple">
<li><p>Each CPU that has an RCU read-side critical section that begins
before <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> starts is guaranteed to execute a full
memory barrier between the time that the RCU read-side critical
section ends and the time that <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> returns. Without
this guarantee, a pre-existing RCU read-side critical section might
hold a reference to the newly removed <code class="docutils literal notranslate"><span class="pre">struct</span> <span class="pre">foo</span></code> after the
<a class="reference internal" href="../../../core-api/mm-api.html#c.kfree" title="kfree"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree()</span></code></a> on line 14 of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_synchronous()</span></code>.</p></li>
<li><p>Each CPU that has an RCU read-side critical section that ends after
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> returns is guaranteed to execute a full memory
barrier between the time that <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> begins and the
time that the RCU read-side critical section begins. Without this
guarantee, a later RCU read-side critical section running after the
<a class="reference internal" href="../../../core-api/mm-api.html#c.kfree" title="kfree"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree()</span></code></a> on line 14 of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_synchronous()</span></code> might later run
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">do_something_gp()</span></code> and find the newly deleted <code class="docutils literal notranslate"><span class="pre">struct</span> <span class="pre">foo</span></code>.</p></li>
<li><p>If the task invoking <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> remains on a given CPU,
then that CPU is guaranteed to execute a full memory barrier sometime
during the execution of <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>. This guarantee ensures
that the <a class="reference internal" href="../../../core-api/mm-api.html#c.kfree" title="kfree"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree()</span></code></a> on line 14 of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_synchronous()</span></code> really
does execute after the removal on line 11.</p></li>
<li><p>If the task invoking <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> migrates among a group of
CPUs during that invocation, then each of the CPUs in that group is
guaranteed to execute a full memory barrier sometime during the
execution of <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>. This guarantee also ensures that
the <a class="reference internal" href="../../../core-api/mm-api.html#c.kfree" title="kfree"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree()</span></code></a> on line 14 of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_synchronous()</span></code> really does
execute after the removal on line 11, but also in the case where the
thread executing the <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> migrates in the meantime.</p></li>
</ol>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Given that multiple CPUs can start RCU read-side critical sections at
any time without any ordering whatsoever, how can RCU possibly tell
whether or not a given RCU read-side critical section starts before a
given instance of <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>If RCU cannot tell whether or not a given RCU read-side critical
section starts before a given instance of <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>, then
it must assume that the RCU read-side critical section started first.
In other words, a given instance of <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> can avoid
waiting on a given RCU read-side critical section only if it can
prove that <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> started first.
A related question is “When <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> doesn’t generate any
code, why does it matter how it relates to a grace period?” The
answer is that it is not the relationship of <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a>
itself that is important, but rather the relationship of the code
within the enclosed RCU read-side critical section to the code
preceding and following the grace period. If we take this viewpoint,
then a given RCU read-side critical section begins before a given
grace period when some access preceding the grace period observes the
effect of some access within the critical section, in which case none
of the accesses within the critical section may observe the effects
of any access following the grace period.</p>
<p>As of late 2016, mathematical models of RCU take this viewpoint, for
example, see slides 62 and 63 of the <a class="reference external" href="http://www2.rdrop.com/users/paulmck/scalability/paper/LinuxMM.2016.10.04c.LCE.pdf">2016 LinuxCon
EU</a>
presentation.</p>
</td>
</tr>
</tbody>
</table>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>The first and second guarantees require unbelievably strict ordering!
Are all these memory barriers <em>really</em> required?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Yes, they really are required. To see why the first guarantee is
required, consider the following sequence of events:</p>
<ol class="arabic simple">
<li><p>CPU 1: <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a></p></li>
<li><p>CPU 1: <code class="docutils literal notranslate"><span class="pre">q</span> <span class="pre">=</span> <span class="pre">rcu_dereference(gp);</span> <span class="pre">/*</span> <span class="pre">Very</span> <span class="pre">likely</span> <span class="pre">to</span> <span class="pre">return</span> <span class="pre">p.</span> <span class="pre">*/</span></code></p></li>
<li><p>CPU 0: <code class="docutils literal notranslate"><span class="pre">list_del_rcu(p);</span></code></p></li>
<li><p>CPU 0: <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> starts.</p></li>
<li><p>CPU 1: <code class="docutils literal notranslate"><span class="pre">do_something_with(q-&gt;a);</span></code>
<code class="docutils literal notranslate"><span class="pre">/*</span> <span class="pre">No</span> <span class="pre">smp_mb(),</span> <span class="pre">so</span> <span class="pre">might</span> <span class="pre">happen</span> <span class="pre">after</span> <span class="pre">kfree().</span> <span class="pre">*/</span></code></p></li>
<li><p>CPU 1: <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a></p></li>
<li><p>CPU 0: <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> returns.</p></li>
<li><p>CPU 0: <code class="docutils literal notranslate"><span class="pre">kfree(p);</span></code></p></li>
</ol>
<p>Therefore, there absolutely must be a full memory barrier between the
end of the RCU read-side critical section and the end of the grace
period.</p>
<p>The sequence of events demonstrating the necessity of the second rule
is roughly similar:</p>
<ol class="arabic simple">
<li><p>CPU 0: <code class="docutils literal notranslate"><span class="pre">list_del_rcu(p);</span></code></p></li>
<li><p>CPU 0: <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> starts.</p></li>
<li><p>CPU 1: <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a></p></li>
<li><p>CPU 1: <code class="docutils literal notranslate"><span class="pre">q</span> <span class="pre">=</span> <span class="pre">rcu_dereference(gp);</span></code>
<code class="docutils literal notranslate"><span class="pre">/*</span> <span class="pre">Might</span> <span class="pre">return</span> <span class="pre">p</span> <span class="pre">if</span> <span class="pre">no</span> <span class="pre">memory</span> <span class="pre">barrier.</span> <span class="pre">*/</span></code></p></li>
<li><p>CPU 0: <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> returns.</p></li>
<li><p>CPU 0: <code class="docutils literal notranslate"><span class="pre">kfree(p);</span></code></p></li>
<li><p>CPU 1: <code class="docutils literal notranslate"><span class="pre">do_something_with(q-&gt;a);</span> <span class="pre">/*</span> <span class="pre">Boom!!!</span> <span class="pre">*/</span></code></p></li>
<li><p>CPU 1: <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a></p></li>
</ol>
<p>And similarly, without a memory barrier between the beginning of the
grace period and the beginning of the RCU read-side critical section,
CPU 1 might end up accessing the freelist.</p>
<p>The “as if” rule of course applies, so that any implementation that
acts as if the appropriate memory barriers were in place is a correct
implementation. That said, it is much easier to fool yourself into
believing that you have adhered to the as-if rule than it is to
actually adhere to it!</p>
</td>
</tr>
</tbody>
</table>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>You claim that <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> generate
absolutely no code in some kernel builds. This means that the
compiler might arbitrarily rearrange consecutive RCU read-side
critical sections. Given such rearrangement, if a given RCU read-side
critical section is done, how can you be sure that all prior RCU
read-side critical sections are done? Won’t the compiler
rearrangements make that impossible to determine?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>In cases where <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> generate
absolutely no code, RCU infers quiescent states only at special
locations, for example, within the scheduler. Because calls to
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">schedule()</span></code> had better prevent calling-code accesses to shared
variables from being rearranged across the call to <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">schedule()</span></code>, if
RCU detects the end of a given RCU read-side critical section, it
will necessarily detect the end of all prior RCU read-side critical
sections, no matter how aggressively the compiler scrambles the code.
Again, this all assumes that the compiler cannot scramble code across
calls to the scheduler, out of interrupt handlers, into the idle
loop, into user-mode code, and so on. But if your kernel build allows
that sort of scrambling, you have broken far more than just RCU!</p></td>
</tr>
</tbody>
</table>
<p>Note that these memory-barrier requirements do not replace the
fundamental RCU requirement that a grace period wait for all
pre-existing readers. On the contrary, the memory barriers called out in
this section must operate in such a way as to <em>enforce</em> this fundamental
requirement. Of course, different implementations enforce this
requirement in different ways, but enforce it they must.</p>
</section>
<section id="rcu-primitives-guaranteed-to-execute-unconditionally">
<h3>RCU Primitives Guaranteed to Execute Unconditionally<a class="headerlink" href="#rcu-primitives-guaranteed-to-execute-unconditionally" title="Link to this heading">¶</a></h3>
<p>The common-case RCU primitives are unconditional. They are invoked, they
do their job, and they return, with no possibility of error, and no need
to retry. This is a key RCU design philosophy.</p>
<p>However, this philosophy is pragmatic rather than pigheaded. If someone
comes up with a good justification for a particular conditional RCU
primitive, it might well be implemented and added. After all, this
guarantee was reverse-engineered, not premeditated. The unconditional
nature of the RCU primitives was initially an accident of
implementation, and later experience with synchronization primitives
with conditional primitives caused me to elevate this accident to a
guarantee. Therefore, the justification for adding a conditional
primitive to RCU would need to be based on detailed and compelling use
cases.</p>
</section>
<section id="guaranteed-read-to-write-upgrade">
<h3>Guaranteed Read-to-Write Upgrade<a class="headerlink" href="#guaranteed-read-to-write-upgrade" title="Link to this heading">¶</a></h3>
<p>As far as RCU is concerned, it is always possible to carry out an update
within an RCU read-side critical section. For example, that RCU
read-side critical section might search for a given data element, and
then might acquire the update-side spinlock in order to update that
element, all while remaining in that RCU read-side critical section. Of
course, it is necessary to exit the RCU read-side critical section
before invoking <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>, however, this inconvenience can
be avoided through use of the <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a> API
members described later in this document.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>But how does the upgrade-to-write operation exclude other readers?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>It doesn’t, just like normal RCU updates, which also do not exclude
RCU readers.</p></td>
</tr>
</tbody>
</table>
<p>This guarantee allows lookup code to be shared between read-side and
update-side code, and was premeditated, appearing in the earliest
DYNIX/ptx RCU documentation.</p>
</section>
</section>
<section id="fundamental-non-requirements">
<h2>Fundamental Non-Requirements<a class="headerlink" href="#fundamental-non-requirements" title="Link to this heading">¶</a></h2>
<p>RCU provides extremely lightweight readers, and its read-side
guarantees, though quite useful, are correspondingly lightweight. It is
therefore all too easy to assume that RCU is guaranteeing more than it
really is. Of course, the list of things that RCU does not guarantee is
infinitely long, however, the following sections list a few
non-guarantees that have caused confusion. Except where otherwise noted,
these non-guarantees were premeditated.</p>
<ol class="arabic simple">
<li><p><a class="reference internal" href="#readers-impose-minimal-ordering">Readers Impose Minimal Ordering</a></p></li>
<li><p><a class="reference internal" href="#readers-do-not-exclude-updaters">Readers Do Not Exclude Updaters</a></p></li>
<li><p><a class="reference internal" href="#updaters-only-wait-for-old-readers">Updaters Only Wait For Old Readers</a></p></li>
<li><p><a class="reference internal" href="#grace-periods-don-t-partition-read-side-critical-sections">Grace Periods Don’t Partition Read-Side Critical Sections</a></p></li>
<li><p><a class="reference internal" href="#read-side-critical-sections-don-t-partition-grace-periods">Read-Side Critical Sections Don’t Partition Grace Periods</a></p></li>
</ol>
<section id="readers-impose-minimal-ordering">
<h3>Readers Impose Minimal Ordering<a class="headerlink" href="#readers-impose-minimal-ordering" title="Link to this heading">¶</a></h3>
<p>Reader-side markers such as <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> provide absolutely no ordering guarantees except
through their interaction with the grace-period APIs such as
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>. To see this, consider the following pair of
threads:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 void thread0(void)
 2 {
 3   rcu_read_lock();
 4   WRITE_ONCE(x, 1);
 5   rcu_read_unlock();
 6   rcu_read_lock();
 7   WRITE_ONCE(y, 1);
 8   rcu_read_unlock();
 9 }
10
11 void thread1(void)
12 {
13   rcu_read_lock();
14   r1 = READ_ONCE(y);
15   rcu_read_unlock();
16   rcu_read_lock();
17   r2 = READ_ONCE(x);
18   rcu_read_unlock();
19 }
</pre></div>
</div>
</div></blockquote>
<p>After <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread0()</span></code> and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread1()</span></code> execute concurrently, it is quite
possible to have</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span>(r1 == 1 &amp;&amp; r2 == 0)
</pre></div>
</div>
</div></blockquote>
<p>(that is, <code class="docutils literal notranslate"><span class="pre">y</span></code> appears to have been assigned before <code class="docutils literal notranslate"><span class="pre">x</span></code>), which would
not be possible if <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> had
much in the way of ordering properties. But they do not, so the CPU is
within its rights to do significant reordering. This is by design: Any
significant ordering constraints would slow down these fast-path APIs.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Can’t the compiler also reorder this code?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>No, the volatile casts in <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">READ_ONCE()</span></code> and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">WRITE_ONCE()</span></code>
prevent the compiler from reordering in this particular case.</p></td>
</tr>
</tbody>
</table>
</section>
<section id="readers-do-not-exclude-updaters">
<h3>Readers Do Not Exclude Updaters<a class="headerlink" href="#readers-do-not-exclude-updaters" title="Link to this heading">¶</a></h3>
<p>Neither <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> nor <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> exclude updates.
All they do is to prevent grace periods from ending. The following
example illustrates this:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 void thread0(void)
 2 {
 3   rcu_read_lock();
 4   r1 = READ_ONCE(y);
 5   if (r1) {
 6     do_something_with_nonzero_x();
 7     r2 = READ_ONCE(x);
 8     WARN_ON(!r2); /* BUG!!! */
 9   }
10   rcu_read_unlock();
11 }
12
13 void thread1(void)
14 {
15   spin_lock(&amp;my_lock);
16   WRITE_ONCE(x, 1);
17   WRITE_ONCE(y, 1);
18   spin_unlock(&amp;my_lock);
19 }
</pre></div>
</div>
</div></blockquote>
<p>If the <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread0()</span></code> function’s <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> excluded the
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread1()</span></code> function’s update, the <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">WARN_ON()</span></code> could never fire. But
the fact is that <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> does not exclude much of anything
aside from subsequent grace periods, of which <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread1()</span></code> has none, so
the <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">WARN_ON()</span></code> can and does fire.</p>
</section>
<section id="updaters-only-wait-for-old-readers">
<h3>Updaters Only Wait For Old Readers<a class="headerlink" href="#updaters-only-wait-for-old-readers" title="Link to this heading">¶</a></h3>
<p>It might be tempting to assume that after <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>
completes, there are no readers executing. This temptation must be
avoided because new readers can start immediately after
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> starts, and <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> is under no
obligation to wait for these new readers.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Suppose that <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> did wait until <em>all</em> readers had
completed instead of waiting only on pre-existing readers. For how
long would the updater be able to rely on there being no readers?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>For no time at all. Even if <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> were to wait until
all readers had completed, a new reader might start immediately after
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> completed. Therefore, the code following
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> can <em>never</em> rely on there being no readers.</p></td>
</tr>
</tbody>
</table>
</section>
<section id="grace-periods-don-t-partition-read-side-critical-sections">
<h3>Grace Periods Don’t Partition Read-Side Critical Sections<a class="headerlink" href="#grace-periods-don-t-partition-read-side-critical-sections" title="Link to this heading">¶</a></h3>
<p>It is tempting to assume that if any part of one RCU read-side critical
section precedes a given grace period, and if any part of another RCU
read-side critical section follows that same grace period, then all of
the first RCU read-side critical section must precede all of the second.
However, this just isn’t the case: A single grace period does not
partition the set of RCU read-side critical sections. An example of this
situation can be illustrated as follows, where <code class="docutils literal notranslate"><span class="pre">x</span></code>, <code class="docutils literal notranslate"><span class="pre">y</span></code>, and <code class="docutils literal notranslate"><span class="pre">z</span></code>
are initially all zero:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 void thread0(void)
 2 {
 3   rcu_read_lock();
 4   WRITE_ONCE(a, 1);
 5   WRITE_ONCE(b, 1);
 6   rcu_read_unlock();
 7 }
 8
 9 void thread1(void)
10 {
11   r1 = READ_ONCE(a);
12   synchronize_rcu();
13   WRITE_ONCE(c, 1);
14 }
15
16 void thread2(void)
17 {
18   rcu_read_lock();
19   r2 = READ_ONCE(b);
20   r3 = READ_ONCE(c);
21   rcu_read_unlock();
22 }
</pre></div>
</div>
</div></blockquote>
<p>It turns out that the outcome:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span>(r1 == 1 &amp;&amp; r2 == 0 &amp;&amp; r3 == 1)
</pre></div>
</div>
</div></blockquote>
<p>is entirely possible. The following figure show how this can happen,
with each circled <code class="docutils literal notranslate"><span class="pre">QS</span></code> indicating the point at which RCU recorded a
<em>quiescent state</em> for each thread, that is, a state in which RCU knows
that the thread cannot be in the midst of an RCU read-side critical
section that started before the current grace period:</p>
<figure class="align-default">
<img alt="../../../_images/GPpartitionReaders1.svg" src="../../../_images/GPpartitionReaders1.svg" />
</figure>
<p>If it is necessary to partition RCU read-side critical sections in this
manner, it is necessary to use two grace periods, where the first grace
period is known to end before the second grace period starts:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 void thread0(void)
 2 {
 3   rcu_read_lock();
 4   WRITE_ONCE(a, 1);
 5   WRITE_ONCE(b, 1);
 6   rcu_read_unlock();
 7 }
 8
 9 void thread1(void)
10 {
11   r1 = READ_ONCE(a);
12   synchronize_rcu();
13   WRITE_ONCE(c, 1);
14 }
15
16 void thread2(void)
17 {
18   r2 = READ_ONCE(c);
19   synchronize_rcu();
20   WRITE_ONCE(d, 1);
21 }
22
23 void thread3(void)
24 {
25   rcu_read_lock();
26   r3 = READ_ONCE(b);
27   r4 = READ_ONCE(d);
28   rcu_read_unlock();
29 }
</pre></div>
</div>
</div></blockquote>
<p>Here, if <code class="docutils literal notranslate"><span class="pre">(r1</span> <span class="pre">==</span> <span class="pre">1)</span></code>, then <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread0()</span></code>’s write to <code class="docutils literal notranslate"><span class="pre">b</span></code> must happen
before the end of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread1()</span></code>’s grace period. If in addition
<code class="docutils literal notranslate"><span class="pre">(r4</span> <span class="pre">==</span> <span class="pre">1)</span></code>, then <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread3()</span></code>’s read from <code class="docutils literal notranslate"><span class="pre">b</span></code> must happen after
the beginning of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread2()</span></code>’s grace period. If it is also the case
that <code class="docutils literal notranslate"><span class="pre">(r2</span> <span class="pre">==</span> <span class="pre">1)</span></code>, then the end of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread1()</span></code>’s grace period must
precede the beginning of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">thread2()</span></code>’s grace period. This mean that
the two RCU read-side critical sections cannot overlap, guaranteeing
that <code class="docutils literal notranslate"><span class="pre">(r3</span> <span class="pre">==</span> <span class="pre">1)</span></code>. As a result, the outcome:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span>(r1 == 1 &amp;&amp; r2 == 1 &amp;&amp; r3 == 0 &amp;&amp; r4 == 1)
</pre></div>
</div>
</div></blockquote>
<p>cannot happen.</p>
<p>This non-requirement was also non-premeditated, but became apparent when
studying RCU’s interaction with memory ordering.</p>
</section>
<section id="read-side-critical-sections-don-t-partition-grace-periods">
<h3>Read-Side Critical Sections Don’t Partition Grace Periods<a class="headerlink" href="#read-side-critical-sections-don-t-partition-grace-periods" title="Link to this heading">¶</a></h3>
<p>It is also tempting to assume that if an RCU read-side critical section
happens between a pair of grace periods, then those grace periods cannot
overlap. However, this temptation leads nowhere good, as can be
illustrated by the following, with all variables initially zero:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 void thread0(void)
 2 {
 3   rcu_read_lock();
 4   WRITE_ONCE(a, 1);
 5   WRITE_ONCE(b, 1);
 6   rcu_read_unlock();
 7 }
 8
 9 void thread1(void)
10 {
11   r1 = READ_ONCE(a);
12   synchronize_rcu();
13   WRITE_ONCE(c, 1);
14 }
15
16 void thread2(void)
17 {
18   rcu_read_lock();
19   WRITE_ONCE(d, 1);
20   r2 = READ_ONCE(c);
21   rcu_read_unlock();
22 }
23
24 void thread3(void)
25 {
26   r3 = READ_ONCE(d);
27   synchronize_rcu();
28   WRITE_ONCE(e, 1);
29 }
30
31 void thread4(void)
32 {
33   rcu_read_lock();
34   r4 = READ_ONCE(b);
35   r5 = READ_ONCE(e);
36   rcu_read_unlock();
37 }
</pre></div>
</div>
</div></blockquote>
<p>In this case, the outcome:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span>(r1 == 1 &amp;&amp; r2 == 1 &amp;&amp; r3 == 1 &amp;&amp; r4 == 0 &amp;&amp; r5 == 1)
</pre></div>
</div>
</div></blockquote>
<p>is entirely possible, as illustrated below:</p>
<figure class="align-default">
<img alt="../../../_images/ReadersPartitionGP1.svg" src="../../../_images/ReadersPartitionGP1.svg" />
</figure>
<p>Again, an RCU read-side critical section can overlap almost all of a
given grace period, just so long as it does not overlap the entire grace
period. As a result, an RCU read-side critical section cannot partition
a pair of RCU grace periods.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>How long a sequence of grace periods, each separated by an RCU
read-side critical section, would be required to partition the RCU
read-side critical sections at the beginning and end of the chain?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>In theory, an infinite number. In practice, an unknown number that is
sensitive to both implementation details and timing considerations.
Therefore, even in practice, RCU users must abide by the theoretical
rather than the practical answer.</p></td>
</tr>
</tbody>
</table>
</section>
</section>
<section id="parallelism-facts-of-life">
<h2>Parallelism Facts of Life<a class="headerlink" href="#parallelism-facts-of-life" title="Link to this heading">¶</a></h2>
<p>These parallelism facts of life are by no means specific to RCU, but the
RCU implementation must abide by them. They therefore bear repeating:</p>
<ol class="arabic simple">
<li><p>Any CPU or task may be delayed at any time, and any attempts to avoid
these delays by disabling preemption, interrupts, or whatever are
completely futile. This is most obvious in preemptible user-level
environments and in virtualized environments (where a given guest
OS’s VCPUs can be preempted at any time by the underlying
hypervisor), but can also happen in bare-metal environments due to
ECC errors, NMIs, and other hardware events. Although a delay of more
than about 20 seconds can result in splats, the RCU implementation is
obligated to use algorithms that can tolerate extremely long delays,
but where “extremely long” is not long enough to allow wrap-around
when incrementing a 64-bit counter.</p></li>
<li><p>Both the compiler and the CPU can reorder memory accesses. Where it
matters, RCU must use compiler directives and memory-barrier
instructions to preserve ordering.</p></li>
<li><p>Conflicting writes to memory locations in any given cache line will
result in expensive cache misses. Greater numbers of concurrent
writes and more-frequent concurrent writes will result in more
dramatic slowdowns. RCU is therefore obligated to use algorithms that
have sufficient locality to avoid significant performance and
scalability problems.</p></li>
<li><p>As a rough rule of thumb, only one CPU’s worth of processing may be
carried out under the protection of any given exclusive lock. RCU
must therefore use scalable locking designs.</p></li>
<li><p>Counters are finite, especially on 32-bit systems. RCU’s use of
counters must therefore tolerate counter wrap, or be designed such
that counter wrap would take way more time than a single system is
likely to run. An uptime of ten years is quite possible, a runtime of
a century much less so. As an example of the latter, RCU’s
dyntick-idle nesting counter allows 54 bits for interrupt nesting
level (this counter is 64 bits even on a 32-bit system). Overflowing
this counter requires 2<sup>54</sup> half-interrupts on a given CPU
without that CPU ever going idle. If a half-interrupt happened every
microsecond, it would take 570 years of runtime to overflow this
counter, which is currently believed to be an acceptably long time.</p></li>
<li><p>Linux systems can have thousands of CPUs running a single Linux
kernel in a single shared-memory environment. RCU must therefore pay
close attention to high-end scalability.</p></li>
</ol>
<p>This last parallelism fact of life means that RCU must pay special
attention to the preceding facts of life. The idea that Linux might
scale to systems with thousands of CPUs would have been met with some
skepticism in the 1990s, but these requirements would have otherwise
have been unsurprising, even in the early 1990s.</p>
</section>
<section id="quality-of-implementation-requirements">
<h2>Quality-of-Implementation Requirements<a class="headerlink" href="#quality-of-implementation-requirements" title="Link to this heading">¶</a></h2>
<p>These sections list quality-of-implementation requirements. Although an
RCU implementation that ignores these requirements could still be used,
it would likely be subject to limitations that would make it
inappropriate for industrial-strength production use. Classes of
quality-of-implementation requirements are as follows:</p>
<ol class="arabic simple">
<li><p><a class="reference internal" href="#specialization">Specialization</a></p></li>
<li><p><a class="reference internal" href="#performance-and-scalability">Performance and Scalability</a></p></li>
<li><p><a class="reference internal" href="#forward-progress">Forward Progress</a></p></li>
<li><p><a class="reference internal" href="#composability">Composability</a></p></li>
<li><p><a class="reference internal" href="#corner-cases">Corner Cases</a></p></li>
</ol>
<p>These classes is covered in the following sections.</p>
<section id="specialization">
<h3>Specialization<a class="headerlink" href="#specialization" title="Link to this heading">¶</a></h3>
<p>RCU is and always has been intended primarily for read-mostly
situations, which means that RCU’s read-side primitives are optimized,
often at the expense of its update-side primitives. Experience thus far
is captured by the following list of situations:</p>
<ol class="arabic simple">
<li><p>Read-mostly data, where stale and inconsistent data is not a problem:
RCU works great!</p></li>
<li><p>Read-mostly data, where data must be consistent: RCU works well.</p></li>
<li><p>Read-write data, where data must be consistent: RCU <em>might</em> work OK.
Or not.</p></li>
<li><p>Write-mostly data, where data must be consistent: RCU is very
unlikely to be the right tool for the job, with the following
exceptions, where RCU can provide:</p>
<ol class="loweralpha simple">
<li><p>Existence guarantees for update-friendly mechanisms.</p></li>
<li><p>Wait-free read-side primitives for real-time use.</p></li>
</ol>
</li>
</ol>
<p>This focus on read-mostly situations means that RCU must interoperate
with other synchronization primitives. For example, the <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">add_gp()</span></code> and
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_synchronous()</span></code> examples discussed earlier use RCU to
protect readers and locking to coordinate updaters. However, the need
extends much farther, requiring that a variety of synchronization
primitives be legal within RCU read-side critical sections, including
spinlocks, sequence locks, atomic operations, reference counters, and
memory barriers.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>What about sleeping locks?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>These are forbidden within Linux-kernel RCU read-side critical
sections because it is not legal to place a quiescent state (in this
case, voluntary context switch) within an RCU read-side critical
section. However, sleeping locks may be used within userspace RCU
read-side critical sections, and also within Linux-kernel sleepable
RCU <a class="reference internal" href="#sleepable-rcu">(SRCU)</a> read-side critical sections. In
addition, the -rt patchset turns spinlocks into a sleeping locks so
that the corresponding critical sections can be preempted, which also
means that these sleeplockified spinlocks (but not other sleeping
locks!) may be acquire within -rt-Linux-kernel RCU read-side critical
sections.
Note that it <em>is</em> legal for a normal RCU read-side critical section
to conditionally acquire a sleeping locks (as in
<a class="reference internal" href="../../../kernel-hacking/locking.html#c.mutex_trylock" title="mutex_trylock"><code class="xref c c-func docutils literal notranslate"><span class="pre">mutex_trylock()</span></code></a>), but only as long as it does not loop
indefinitely attempting to conditionally acquire that sleeping locks.
The key point is that things like <a class="reference internal" href="../../../kernel-hacking/locking.html#c.mutex_trylock" title="mutex_trylock"><code class="xref c c-func docutils literal notranslate"><span class="pre">mutex_trylock()</span></code></a> either return
with the mutex held, or return an error indication if the mutex was
not immediately available. Either way, <a class="reference internal" href="../../../kernel-hacking/locking.html#c.mutex_trylock" title="mutex_trylock"><code class="xref c c-func docutils literal notranslate"><span class="pre">mutex_trylock()</span></code></a> returns
immediately without sleeping.</p></td>
</tr>
</tbody>
</table>
<p>It often comes as a surprise that many algorithms do not require a
consistent view of data, but many can function in that mode, with
network routing being the poster child. Internet routing algorithms take
significant time to propagate updates, so that by the time an update
arrives at a given system, that system has been sending network traffic
the wrong way for a considerable length of time. Having a few threads
continue to send traffic the wrong way for a few more milliseconds is
clearly not a problem: In the worst case, TCP retransmissions will
eventually get the data where it needs to go. In general, when tracking
the state of the universe outside of the computer, some level of
inconsistency must be tolerated due to speed-of-light delays if nothing
else.</p>
<p>Furthermore, uncertainty about external state is inherent in many cases.
For example, a pair of veterinarians might use heartbeat to determine
whether or not a given cat was alive. But how long should they wait
after the last heartbeat to decide that the cat is in fact dead? Waiting
less than 400 milliseconds makes no sense because this would mean that a
relaxed cat would be considered to cycle between death and life more
than 100 times per minute. Moreover, just as with human beings, a cat’s
heart might stop for some period of time, so the exact wait period is a
judgment call. One of our pair of veterinarians might wait 30 seconds
before pronouncing the cat dead, while the other might insist on waiting
a full minute. The two veterinarians would then disagree on the state of
the cat during the final 30 seconds of the minute following the last
heartbeat.</p>
<p>Interestingly enough, this same situation applies to hardware. When push
comes to shove, how do we tell whether or not some external server has
failed? We send messages to it periodically, and declare it failed if we
don’t receive a response within a given period of time. Policy decisions
can usually tolerate short periods of inconsistency. The policy was
decided some time ago, and is only now being put into effect, so a few
milliseconds of delay is normally inconsequential.</p>
<p>However, there are algorithms that absolutely must see consistent data.
For example, the translation between a user-level SystemV semaphore ID
to the corresponding in-kernel data structure is protected by RCU, but
it is absolutely forbidden to update a semaphore that has just been
removed. In the Linux kernel, this need for consistency is accommodated
by acquiring spinlocks located in the in-kernel data structure from
within the RCU read-side critical section, and this is indicated by the
green box in the figure above. Many other techniques may be used, and
are in fact used within the Linux kernel.</p>
<p>In short, RCU is not required to maintain consistency, and other
mechanisms may be used in concert with RCU when consistency is required.
RCU’s specialization allows it to do its job extremely well, and its
ability to interoperate with other synchronization mechanisms allows the
right mix of synchronization tools to be used for a given job.</p>
</section>
<section id="performance-and-scalability">
<h3>Performance and Scalability<a class="headerlink" href="#performance-and-scalability" title="Link to this heading">¶</a></h3>
<p>Energy efficiency is a critical component of performance today, and
Linux-kernel RCU implementations must therefore avoid unnecessarily
awakening idle CPUs. I cannot claim that this requirement was
premeditated. In fact, I learned of it during a telephone conversation
in which I was given “frank and open” feedback on the importance of
energy efficiency in battery-powered systems and on specific
energy-efficiency shortcomings of the Linux-kernel RCU implementation.
In my experience, the battery-powered embedded community will consider
any unnecessary wakeups to be extremely unfriendly acts. So much so that
mere Linux-kernel-mailing-list posts are insufficient to vent their ire.</p>
<p>Memory consumption is not particularly important for in most situations,
and has become decreasingly so as memory sizes have expanded and memory
costs have plummeted. However, as I learned from Matt Mackall’s
<a class="reference external" href="http://elinux.org/Linux_Tiny-FAQ">bloatwatch</a> efforts, memory
footprint is critically important on single-CPU systems with
non-preemptible (<code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=n</span></code>) kernels, and thus <a class="reference external" href="https://lore.kernel.org/r/20090113221724.GA15307&#64;linux.vnet.ibm.com">tiny
RCU</a>
was born. Josh Triplett has since taken over the small-memory banner
with his <a class="reference external" href="https://tiny.wiki.kernel.org/">Linux kernel tinification</a>
project, which resulted in <a class="reference internal" href="#sleepable-rcu">SRCU</a> becoming optional
for those kernels not needing it.</p>
<p>The remaining performance requirements are, for the most part,
unsurprising. For example, in keeping with RCU’s read-side
specialization, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> should have negligible overhead
(for example, suppression of a few minor compiler optimizations).
Similarly, in non-preemptible environments, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> should have exactly zero overhead.</p>
<p>In preemptible environments, in the case where the RCU read-side
critical section was not preempted (as will be the case for the
highest-priority real-time process), <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> should have minimal overhead. In particular, they
should not contain atomic read-modify-write operations, memory-barrier
instructions, preemption disabling, interrupt disabling, or backwards
branches. However, in the case where the RCU read-side critical section
was preempted, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> may acquire spinlocks and disable
interrupts. This is why it is better to nest an RCU read-side critical
section within a preempt-disable region than vice versa, at least in
cases where that critical section is short enough to avoid unduly
degrading real-time latencies.</p>
<p>The <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> grace-period-wait primitive is optimized for
throughput. It may therefore incur several milliseconds of latency in
addition to the duration of the longest RCU read-side critical section.
On the other hand, multiple concurrent invocations of
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> are required to use batching optimizations so that
they can be satisfied by a single underlying grace-period-wait
operation. For example, in the Linux kernel, it is not unusual for a
single grace-period-wait operation to serve more than <a class="reference external" href="https://www.usenix.org/conference/2004-usenix-annual-technical-conference/making-rcu-safe-deep-sub-millisecond-response">1,000 separate
invocations</a>
of <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>, thus amortizing the per-invocation overhead
down to nearly zero. However, the grace-period optimization is also
required to avoid measurable degradation of real-time scheduling and
interrupt latencies.</p>
<p>In some cases, the multi-millisecond <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> latencies are
unacceptable. In these cases, <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a> may be
used instead, reducing the grace-period latency down to a few tens of
microseconds on small systems, at least in cases where the RCU read-side
critical sections are short. There are currently no special latency
requirements for <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a> on large systems, but,
consistent with the empirical nature of the RCU specification, that is
subject to change. However, there most definitely are scalability
requirements: A storm of <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a> invocations on
4096 CPUs should at least make reasonable forward progress. In return
for its shorter latencies, <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a> is permitted
to impose modest degradation of real-time latency on non-idle online
CPUs. Here, “modest” means roughly the same latency degradation as a
scheduling-clock interrupt.</p>
<p>There are a number of situations where even
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a>’s reduced grace-period latency is
unacceptable. In these situations, the asynchronous <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> can
be used in place of <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> as follows:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 struct foo {
 2   int a;
 3   int b;
 4   struct rcu_head rh;
 5 };
 6
 7 static void remove_gp_cb(struct rcu_head *rhp)
 8 {
 9   struct foo *p = container_of(rhp, struct foo, rh);
10
11   kfree(p);
12 }
13
14 bool remove_gp_asynchronous(void)
15 {
16   struct foo *p;
17
18   spin_lock(&amp;gp_lock);
19   p = rcu_access_pointer(gp);
20   if (!p) {
21     spin_unlock(&amp;gp_lock);
22     return false;
23   }
24   rcu_assign_pointer(gp, NULL);
25   call_rcu(&amp;p-&gt;rh, remove_gp_cb);
26   spin_unlock(&amp;gp_lock);
27   return true;
28 }
</pre></div>
</div>
</div></blockquote>
<p>A definition of <code class="docutils literal notranslate"><span class="pre">struct</span> <span class="pre">foo</span></code> is finally needed, and appears on
lines 1-5. The function <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_cb()</span></code> is passed to <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>
on line 25, and will be invoked after the end of a subsequent grace
period. This gets the same effect as <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_synchronous()</span></code>, but
without forcing the updater to wait for a grace period to elapse. The
<a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> function may be used in a number of situations where
neither <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> nor <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a> would
be legal, including within preempt-disable code, <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">local_bh_disable()</span></code>
code, interrupt-disable code, and interrupt handlers. However, even
<a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> is illegal within NMI handlers and from idle and offline
CPUs. The callback function (<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_cb()</span></code> in this case) will be
executed within softirq (software interrupt) environment within the
Linux kernel, either within a real softirq handler or under the
protection of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">local_bh_disable()</span></code>. In both the Linux kernel and in
userspace, it is bad practice to write an RCU callback function that
takes too long. Long-running operations should be relegated to separate
threads or (in the Linux kernel) workqueues.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Why does line 19 use <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_access_pointer" title="rcu_access_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_access_pointer()</span></code></a>? After all,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> on line 25 stores into the structure, which would
interact badly with concurrent insertions. Doesn’t this mean that
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> is required?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Presumably the <code class="docutils literal notranslate"><span class="pre">-&gt;gp_lock</span></code> acquired on line 18 excludes any
changes, including any insertions that <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> would
protect against. Therefore, any insertions will be delayed until
after <code class="docutils literal notranslate"><span class="pre">-&gt;gp_lock</span></code> is released on line 25, which in turn means that
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_access_pointer" title="rcu_access_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_access_pointer()</span></code></a> suffices.</p></td>
</tr>
</tbody>
</table>
<p>However, all that <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_cb()</span></code> is doing is invoking <a class="reference internal" href="../../../core-api/mm-api.html#c.kfree" title="kfree"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree()</span></code></a> on
the data element. This is a common idiom, and is supported by
<a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a>, which allows “fire and forget” operation as shown
below:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 struct foo {
 2   int a;
 3   int b;
 4   struct rcu_head rh;
 5 };
 6
 7 bool remove_gp_faf(void)
 8 {
 9   struct foo *p;
10
11   spin_lock(&amp;gp_lock);
12   p = rcu_dereference(gp);
13   if (!p) {
14     spin_unlock(&amp;gp_lock);
15     return false;
16   }
17   rcu_assign_pointer(gp, NULL);
18   kfree_rcu(p, rh);
19   spin_unlock(&amp;gp_lock);
20   return true;
21 }
</pre></div>
</div>
</div></blockquote>
<p>Note that <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">remove_gp_faf()</span></code> simply invokes <a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a> and
proceeds, without any need to pay any further attention to the
subsequent grace period and <a class="reference internal" href="../../../core-api/mm-api.html#c.kfree" title="kfree"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree()</span></code></a>. It is permissible to invoke
<a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a> from the same environments as for <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>.
Interestingly enough, DYNIX/ptx had the equivalents of <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>
and <a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a>, but not <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>. This was due to the
fact that RCU was not heavily used within DYNIX/ptx, so the very few
places that needed something like <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> simply
open-coded it.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Earlier it was claimed that <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a>
allowed updaters to avoid being blocked by readers. But how can that
be correct, given that the invocation of the callback and the freeing
of the memory (respectively) must still wait for a grace period to
elapse?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>We could define things this way, but keep in mind that this sort of
definition would say that updates in garbage-collected languages
cannot complete until the next time the garbage collector runs, which
does not seem at all reasonable. The key point is that in most cases,
an updater using either <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> or <a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a> can proceed
to the next update as soon as it has invoked <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> or
<a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a>, without having to wait for a subsequent grace
period.</p></td>
</tr>
</tbody>
</table>
<p>But what if the updater must wait for the completion of code to be
executed after the end of the grace period, but has other tasks that can
be carried out in the meantime? The polling-style
<a class="reference internal" href="../../../core-api/kernel-api.html#c.get_state_synchronize_rcu" title="get_state_synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">get_state_synchronize_rcu()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.cond_synchronize_rcu" title="cond_synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">cond_synchronize_rcu()</span></code></a> functions
may be used for this purpose, as shown below:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span> 1 bool remove_gp_poll(void)
 2 {
 3   struct foo *p;
 4   unsigned long s;
 5
 6   spin_lock(&amp;gp_lock);
 7   p = rcu_access_pointer(gp);
 8   if (!p) {
 9     spin_unlock(&amp;gp_lock);
10     return false;
11   }
12   rcu_assign_pointer(gp, NULL);
13   spin_unlock(&amp;gp_lock);
14   s = get_state_synchronize_rcu();
15   do_something_while_waiting();
16   cond_synchronize_rcu(s);
17   kfree(p);
18   return true;
19 }
</pre></div>
</div>
</div></blockquote>
<p>On line 14, <a class="reference internal" href="../../../core-api/kernel-api.html#c.get_state_synchronize_rcu" title="get_state_synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">get_state_synchronize_rcu()</span></code></a> obtains a “cookie” from RCU,
then line 15 carries out other tasks, and finally, line 16 returns
immediately if a grace period has elapsed in the meantime, but otherwise
waits as required. The need for <code class="docutils literal notranslate"><span class="pre">get_state_synchronize_rcu</span></code> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.cond_synchronize_rcu" title="cond_synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">cond_synchronize_rcu()</span></code></a> has appeared quite recently, so it is too
early to tell whether they will stand the test of time.</p>
<p>RCU thus provides a range of tools to allow updaters to strike the
required tradeoff between latency, flexibility and CPU overhead.</p>
</section>
<section id="forward-progress">
<h3>Forward Progress<a class="headerlink" href="#forward-progress" title="Link to this heading">¶</a></h3>
<p>In theory, delaying grace-period completion and callback invocation is
harmless. In practice, not only are memory sizes finite but also
callbacks sometimes do wakeups, and sufficiently deferred wakeups can be
difficult to distinguish from system hangs. Therefore, RCU must provide
a number of mechanisms to promote forward progress.</p>
<p>These mechanisms are not foolproof, nor can they be. For one simple
example, an infinite loop in an RCU read-side critical section must by
definition prevent later grace periods from ever completing. For a more
involved example, consider a 64-CPU system built with
<code class="docutils literal notranslate"><span class="pre">CONFIG_RCU_NOCB_CPU=y</span></code> and booted with <code class="docutils literal notranslate"><span class="pre">rcu_nocbs=1-63</span></code>, where
CPUs 1 through 63 spin in tight loops that invoke <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>. Even
if these tight loops also contain calls to <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">cond_resched()</span></code> (thus
allowing grace periods to complete), CPU 0 simply will not be able to
invoke callbacks as fast as the other 63 CPUs can register them, at
least not until the system runs out of memory. In both of these
examples, the Spiderman principle applies: With great power comes great
responsibility. However, short of this level of abuse, RCU is required
to ensure timely completion of grace periods and timely invocation of
callbacks.</p>
<p>RCU takes the following steps to encourage timely completion of grace
periods:</p>
<ol class="arabic simple">
<li><p>If a grace period fails to complete within 100 milliseconds, RCU
causes future invocations of <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">cond_resched()</span></code> on the holdout CPUs
to provide an RCU quiescent state. RCU also causes those CPUs’
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">need_resched()</span></code> invocations to return <code class="docutils literal notranslate"><span class="pre">true</span></code>, but only after the
corresponding CPU’s next scheduling-clock.</p></li>
<li><p>CPUs mentioned in the <code class="docutils literal notranslate"><span class="pre">nohz_full</span></code> kernel boot parameter can run
indefinitely in the kernel without scheduling-clock interrupts, which
defeats the above <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">need_resched()</span></code> strategem. RCU will therefore
invoke <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">resched_cpu()</span></code> on any <code class="docutils literal notranslate"><span class="pre">nohz_full</span></code> CPUs still holding out
after 109 milliseconds.</p></li>
<li><p>In kernels built with <code class="docutils literal notranslate"><span class="pre">CONFIG_RCU_BOOST=y</span></code>, if a given task that
has been preempted within an RCU read-side critical section is
holding out for more than 500 milliseconds, RCU will resort to
priority boosting.</p></li>
<li><p>If a CPU is still holding out 10 seconds into the grace period, RCU
will invoke <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">resched_cpu()</span></code> on it regardless of its <code class="docutils literal notranslate"><span class="pre">nohz_full</span></code>
state.</p></li>
</ol>
<p>The above values are defaults for systems running with <code class="docutils literal notranslate"><span class="pre">HZ=1000</span></code>. They
will vary as the value of <code class="docutils literal notranslate"><span class="pre">HZ</span></code> varies, and can also be changed using
the relevant Kconfig options and kernel boot parameters. RCU currently
does not do much sanity checking of these parameters, so please use
caution when changing them. Note that these forward-progress measures
are provided only for RCU, not for <a class="reference internal" href="#sleepable-rcu">SRCU</a> or <a class="reference internal" href="#tasks-rcu">Tasks
RCU</a>.</p>
<p>RCU takes the following steps in <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> to encourage timely
invocation of callbacks when any given non-<code class="docutils literal notranslate"><span class="pre">rcu_nocbs</span></code> CPU has
10,000 callbacks, or has 10,000 more callbacks than it had the last time
encouragement was provided:</p>
<ol class="arabic simple">
<li><p>Starts a grace period, if one is not already in progress.</p></li>
<li><p>Forces immediate checking for quiescent states, rather than waiting
for three milliseconds to have elapsed since the beginning of the
grace period.</p></li>
<li><p>Immediately tags the CPU’s callbacks with their grace period
completion numbers, rather than waiting for the <code class="docutils literal notranslate"><span class="pre">RCU_SOFTIRQ</span></code>
handler to get around to it.</p></li>
<li><p>Lifts callback-execution batch limits, which speeds up callback
invocation at the expense of degrading realtime response.</p></li>
</ol>
<p>Again, these are default values when running at <code class="docutils literal notranslate"><span class="pre">HZ=1000</span></code>, and can be
overridden. Again, these forward-progress measures are provided only for
RCU, not for <a class="reference internal" href="#sleepable-rcu">SRCU</a> or <a class="reference internal" href="#tasks-rcu">Tasks
RCU</a>. Even for RCU, callback-invocation forward
progress for <code class="docutils literal notranslate"><span class="pre">rcu_nocbs</span></code> CPUs is much less well-developed, in part
because workloads benefiting from <code class="docutils literal notranslate"><span class="pre">rcu_nocbs</span></code> CPUs tend to invoke
<a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> relatively infrequently. If workloads emerge that need
both <code class="docutils literal notranslate"><span class="pre">rcu_nocbs</span></code> CPUs and high <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> invocation rates, then
additional forward-progress work will be required.</p>
</section>
<section id="composability">
<h3>Composability<a class="headerlink" href="#composability" title="Link to this heading">¶</a></h3>
<p>Composability has received much attention in recent years, perhaps in
part due to the collision of multicore hardware with object-oriented
techniques designed in single-threaded environments for single-threaded
use. And in theory, RCU read-side critical sections may be composed, and
in fact may be nested arbitrarily deeply. In practice, as with all
real-world implementations of composable constructs, there are
limitations.</p>
<p>Implementations of RCU for which <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> generate no code, such as Linux-kernel RCU when
<code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=n</span></code>, can be nested arbitrarily deeply. After all, there
is no overhead. Except that if all these instances of
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> are visible to the
compiler, compilation will eventually fail due to exhausting memory,
mass storage, or user patience, whichever comes first. If the nesting is
not visible to the compiler, as is the case with mutually recursive
functions each in its own translation unit, stack overflow will result.
If the nesting takes the form of loops, perhaps in the guise of tail
recursion, either the control variable will overflow or (in the Linux
kernel) you will get an RCU CPU stall warning. Nevertheless, this class
of RCU implementations is one of the most composable constructs in
existence.</p>
<p>RCU implementations that explicitly track nesting depth are limited by
the nesting-depth counter. For example, the Linux kernel’s preemptible
RCU limits nesting to <code class="docutils literal notranslate"><span class="pre">INT_MAX</span></code>. This should suffice for almost all
practical purposes. That said, a consecutive pair of RCU read-side
critical sections between which there is an operation that waits for a
grace period cannot be enclosed in another RCU read-side critical
section. This is because it is not legal to wait for a grace period
within an RCU read-side critical section: To do so would result either
in deadlock or in RCU implicitly splitting the enclosing RCU read-side
critical section, neither of which is conducive to a long-lived and
prosperous kernel.</p>
<p>It is worth noting that RCU is not alone in limiting composability. For
example, many transactional-memory implementations prohibit composing a
pair of transactions separated by an irrevocable operation (for example,
a network receive operation). For another example, lock-based critical
sections can be composed surprisingly freely, but only if deadlock is
avoided.</p>
<p>In short, although RCU read-side critical sections are highly
composable, care is required in some situations, just as is the case for
any other composable synchronization mechanism.</p>
</section>
<section id="corner-cases">
<h3>Corner Cases<a class="headerlink" href="#corner-cases" title="Link to this heading">¶</a></h3>
<p>A given RCU workload might have an endless and intense stream of RCU
read-side critical sections, perhaps even so intense that there was
never a point in time during which there was not at least one RCU
read-side critical section in flight. RCU cannot allow this situation to
block grace periods: As long as all the RCU read-side critical sections
are finite, grace periods must also be finite.</p>
<p>That said, preemptible RCU implementations could potentially result in
RCU read-side critical sections being preempted for long durations,
which has the effect of creating a long-duration RCU read-side critical
section. This situation can arise only in heavily loaded systems, but
systems using real-time priorities are of course more vulnerable.
Therefore, RCU priority boosting is provided to help deal with this
case. That said, the exact requirements on RCU priority boosting will
likely evolve as more experience accumulates.</p>
<p>Other workloads might have very high update rates. Although one can
argue that such workloads should instead use something other than RCU,
the fact remains that RCU must handle such workloads gracefully. This
requirement is another factor driving batching of grace periods, but it
is also the driving force behind the checks for large numbers of queued
RCU callbacks in the <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> code path. Finally, high update
rates should not delay RCU read-side critical sections, although some
small read-side delays can occur when using
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a>, courtesy of this function’s use of
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">smp_call_function_single()</span></code>.</p>
<p>Although all three of these corner cases were understood in the early
1990s, a simple user-level test consisting of <code class="docutils literal notranslate"><span class="pre">close(open(path))</span></code> in a
tight loop in the early 2000s suddenly provided a much deeper
appreciation of the high-update-rate corner case. This test also
motivated addition of some RCU code to react to high update rates, for
example, if a given CPU finds itself with more than 10,000 RCU callbacks
queued, it will cause RCU to take evasive action by more aggressively
starting grace periods and more aggressively forcing completion of
grace-period processing. This evasive action causes the grace period to
complete more quickly, but at the cost of restricting RCU’s batching
optimizations, thus increasing the CPU overhead incurred by that grace
period.</p>
</section>
</section>
<section id="software-engineering-requirements">
<h2>Software-Engineering Requirements<a class="headerlink" href="#software-engineering-requirements" title="Link to this heading">¶</a></h2>
<p>Between Murphy’s Law and “To err is human”, it is necessary to guard
against mishaps and misuse:</p>
<ol class="arabic">
<li><p>It is all too easy to forget to use <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> everywhere
that it is needed, so kernels built with <code class="docutils literal notranslate"><span class="pre">CONFIG_PROVE_RCU=y</span></code> will
splat if <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a> is used outside of an RCU read-side
critical section. Update-side code can use
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference_protected" title="rcu_dereference_protected"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference_protected()</span></code></a>, which takes a <a class="reference external" href="https://lwn.net/Articles/371986/">lockdep
expression</a> to indicate what is
providing the protection. If the indicated protection is not
provided, a lockdep splat is emitted.
Code shared between readers and updaters can use
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference_check" title="rcu_dereference_check"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference_check()</span></code></a>, which also takes a lockdep expression,
and emits a lockdep splat if neither <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> nor the
indicated protection is in place. In addition,
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_dereference_raw()</span></code> is used in those (hopefully rare) cases
where the required protection cannot be easily described. Finally,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock_held" title="rcu_read_lock_held"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock_held()</span></code></a> is provided to allow a function to verify
that it has been invoked within an RCU read-side critical section. I
was made aware of this set of requirements shortly after Thomas
Gleixner audited a number of RCU uses.</p></li>
<li><p>A given function might wish to check for RCU-related preconditions
upon entry, before using any other RCU API. The
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_lockdep_assert()</span></code> does this job, asserting the expression in
kernels having lockdep enabled and doing nothing otherwise.</p></li>
<li><p>It is also easy to forget to use <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_assign_pointer" title="rcu_assign_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_assign_pointer()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>, perhaps (incorrectly) substituting a simple
assignment. To catch this sort of error, a given RCU-protected
pointer may be tagged with <code class="docutils literal notranslate"><span class="pre">__rcu</span></code>, after which sparse will
complain about simple-assignment accesses to that pointer. Arnd
Bergmann made me aware of this requirement, and also supplied the
needed <a class="reference external" href="https://lwn.net/Articles/376011/">patch series</a>.</p></li>
<li><p>Kernels built with <code class="docutils literal notranslate"><span class="pre">CONFIG_DEBUG_OBJECTS_RCU_HEAD=y</span></code> will splat if
a data element is passed to <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> twice in a row, without a
grace period in between. (This error is similar to a double free.)
The corresponding <code class="docutils literal notranslate"><span class="pre">rcu_head</span></code> structures that are dynamically
allocated are automatically tracked, but <code class="docutils literal notranslate"><span class="pre">rcu_head</span></code> structures
allocated on the stack must be initialized with
<a class="reference internal" href="../../../core-api/kernel-api.html#c.init_rcu_head_on_stack" title="init_rcu_head_on_stack"><code class="xref c c-func docutils literal notranslate"><span class="pre">init_rcu_head_on_stack()</span></code></a> and cleaned up with
<a class="reference internal" href="../../../core-api/kernel-api.html#c.destroy_rcu_head_on_stack" title="destroy_rcu_head_on_stack"><code class="xref c c-func docutils literal notranslate"><span class="pre">destroy_rcu_head_on_stack()</span></code></a>. Similarly, statically allocated
non-stack <code class="docutils literal notranslate"><span class="pre">rcu_head</span></code> structures must be initialized with
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">init_rcu_head()</span></code> and cleaned up with <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">destroy_rcu_head()</span></code>.
Mathieu Desnoyers made me aware of this requirement, and also
supplied the needed
<a class="reference external" href="https://lore.kernel.org/r/20100319013024.GA28456&#64;Krystal">patch</a>.</p></li>
<li><p>An infinite loop in an RCU read-side critical section will eventually
trigger an RCU CPU stall warning splat, with the duration of
“eventually” being controlled by the <code class="docutils literal notranslate"><span class="pre">RCU_CPU_STALL_TIMEOUT</span></code>
<code class="docutils literal notranslate"><span class="pre">Kconfig</span></code> option, or, alternatively, by the
<code class="docutils literal notranslate"><span class="pre">rcupdate.rcu_cpu_stall_timeout</span></code> boot/sysfs parameter. However, RCU
is not obligated to produce this splat unless there is a grace period
waiting on that particular RCU read-side critical section.</p>
<p>Some extreme workloads might intentionally delay RCU grace periods,
and systems running those workloads can be booted with
<code class="docutils literal notranslate"><span class="pre">rcupdate.rcu_cpu_stall_suppress</span></code> to suppress the splats. This
kernel parameter may also be set via <code class="docutils literal notranslate"><span class="pre">sysfs</span></code>. Furthermore, RCU CPU
stall warnings are counter-productive during sysrq dumps and during
panics. RCU therefore supplies the <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_sysrq_start()</span></code> and
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_sysrq_end()</span></code> API members to be called before and after long
sysrq dumps. RCU also supplies the <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_panic()</span></code> notifier that is
automatically invoked at the beginning of a panic to suppress further
RCU CPU stall warnings.</p>
<p>This requirement made itself known in the early 1990s, pretty much
the first time that it was necessary to debug a CPU stall. That said,
the initial implementation in DYNIX/ptx was quite generic in
comparison with that of Linux.</p>
</li>
<li><p>Although it would be very good to detect pointers leaking out of RCU
read-side critical sections, there is currently no good way of doing
this. One complication is the need to distinguish between pointers
leaking and pointers that have been handed off from RCU to some other
synchronization mechanism, for example, reference counting.</p></li>
<li><p>In kernels built with <code class="docutils literal notranslate"><span class="pre">CONFIG_RCU_TRACE=y</span></code>, RCU-related information
is provided via event tracing.</p></li>
<li><p>Open-coded use of <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_assign_pointer" title="rcu_assign_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_assign_pointer()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>
to create typical linked data structures can be surprisingly
error-prone. Therefore, RCU-protected <a class="reference external" href="https://lwn.net/Articles/609973/#RCU%20List%20APIs">linked
lists</a> and,
more recently, RCU-protected <a class="reference external" href="https://lwn.net/Articles/612100/">hash
tables</a> are available. Many
other special-purpose RCU-protected data structures are available in
the Linux kernel and the userspace RCU library.</p></li>
<li><p>Some linked structures are created at compile time, but still require
<code class="docutils literal notranslate"><span class="pre">__rcu</span></code> checking. The <a class="reference internal" href="../../../core-api/kernel-api.html#c.RCU_POINTER_INITIALIZER" title="RCU_POINTER_INITIALIZER"><code class="xref c c-func docutils literal notranslate"><span class="pre">RCU_POINTER_INITIALIZER()</span></code></a> macro serves
this purpose.</p></li>
<li><p>It is not necessary to use <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_assign_pointer" title="rcu_assign_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_assign_pointer()</span></code></a> when creating
linked structures that are to be published via a single external
pointer. The <a class="reference internal" href="../../../core-api/kernel-api.html#c.RCU_INIT_POINTER" title="RCU_INIT_POINTER"><code class="xref c c-func docutils literal notranslate"><span class="pre">RCU_INIT_POINTER()</span></code></a> macro is provided for this task.</p></li>
</ol>
<p>This not a hard-and-fast list: RCU’s diagnostic capabilities will
continue to be guided by the number and type of usage bugs found in
real-world RCU usage.</p>
</section>
<section id="linux-kernel-complications">
<h2>Linux Kernel Complications<a class="headerlink" href="#linux-kernel-complications" title="Link to this heading">¶</a></h2>
<p>The Linux kernel provides an interesting environment for all kinds of
software, including RCU. Some of the relevant points of interest are as
follows:</p>
<ol class="arabic simple">
<li><p><a class="reference internal" href="#configuration">Configuration</a></p></li>
<li><p><a class="reference internal" href="#firmware-interface">Firmware Interface</a></p></li>
<li><p><a class="reference internal" href="#early-boot">Early Boot</a></p></li>
<li><p><a class="reference internal" href="#interrupts-and-nmis">Interrupts and NMIs</a></p></li>
<li><p><a class="reference internal" href="#loadable-modules">Loadable Modules</a></p></li>
<li><p><a class="reference internal" href="#hotplug-cpu">Hotplug CPU</a></p></li>
<li><p><a class="reference internal" href="#scheduler-and-rcu">Scheduler and RCU</a></p></li>
<li><p><a class="reference internal" href="#tracing-and-rcu">Tracing and RCU</a></p></li>
<li><p><a class="reference internal" href="#accesses-to-user-memory-and-rcu">Accesses to User Memory and RCU</a></p></li>
<li><p><a class="reference internal" href="#energy-efficiency">Energy Efficiency</a></p></li>
<li><p><a class="reference internal" href="#scheduling-clock-interrupts-and-rcu">Scheduling-Clock Interrupts and RCU</a></p></li>
<li><p><a class="reference internal" href="#memory-efficiency">Memory Efficiency</a></p></li>
<li><p><a class="reference internal" href="#performance-scalability-response-time-and-reliability">Performance, Scalability, Response Time, and Reliability</a></p></li>
</ol>
<p>This list is probably incomplete, but it does give a feel for the most
notable Linux-kernel complications. Each of the following sections
covers one of the above topics.</p>
<section id="configuration">
<h3>Configuration<a class="headerlink" href="#configuration" title="Link to this heading">¶</a></h3>
<p>RCU’s goal is automatic configuration, so that almost nobody needs to
worry about RCU’s <code class="docutils literal notranslate"><span class="pre">Kconfig</span></code> options. And for almost all users, RCU
does in fact work well “out of the box.”</p>
<p>However, there are specialized use cases that are handled by kernel boot
parameters and <code class="docutils literal notranslate"><span class="pre">Kconfig</span></code> options. Unfortunately, the <code class="docutils literal notranslate"><span class="pre">Kconfig</span></code>
system will explicitly ask users about new <code class="docutils literal notranslate"><span class="pre">Kconfig</span></code> options, which
requires almost all of them be hidden behind a <code class="docutils literal notranslate"><span class="pre">CONFIG_RCU_EXPERT</span></code>
<code class="docutils literal notranslate"><span class="pre">Kconfig</span></code> option.</p>
<p>This all should be quite obvious, but the fact remains that Linus
Torvalds recently had to
<a class="reference external" href="https://lore.kernel.org/r/CA+55aFy4wcCwaL4okTs8wXhGZ5h-ibecy_Meg9C4MNQrUnwMcg&#64;mail.gmail.com">remind</a>
me of this requirement.</p>
</section>
<section id="firmware-interface">
<h3>Firmware Interface<a class="headerlink" href="#firmware-interface" title="Link to this heading">¶</a></h3>
<p>In many cases, kernel obtains information about the system from the
firmware, and sometimes things are lost in translation. Or the
translation is accurate, but the original message is bogus.</p>
<p>For example, some systems’ firmware overreports the number of CPUs,
sometimes by a large factor. If RCU naively believed the firmware, as it
used to do, it would create too many per-CPU kthreads. Although the
resulting system will still run correctly, the extra kthreads needlessly
consume memory and can cause confusion when they show up in <code class="docutils literal notranslate"><span class="pre">ps</span></code>
listings.</p>
<p>RCU must therefore wait for a given CPU to actually come online before
it can allow itself to believe that the CPU actually exists. The
resulting “ghost CPUs” (which are never going to come online) cause a
number of <a class="reference external" href="https://paulmck.livejournal.com/37494.html">interesting
complications</a>.</p>
</section>
<section id="early-boot">
<h3>Early Boot<a class="headerlink" href="#early-boot" title="Link to this heading">¶</a></h3>
<p>The Linux kernel’s boot sequence is an interesting process, and RCU is
used early, even before <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_init()</span></code> is invoked. In fact, a number of
RCU’s primitives can be used as soon as the initial task’s
<code class="docutils literal notranslate"><span class="pre">task_struct</span></code> is available and the boot CPU’s per-CPU variables are
set up. The read-side primitives (<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference" title="rcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference()</span></code></a>, and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_access_pointer" title="rcu_access_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_access_pointer()</span></code></a>) will operate normally very early on, as will
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_assign_pointer" title="rcu_assign_pointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_assign_pointer()</span></code></a>.</p>
<p>Although <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> may be invoked at any time during boot,
callbacks are not guaranteed to be invoked until after all of RCU’s
kthreads have been spawned, which occurs at <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">early_initcall()</span></code> time.
This delay in callback invocation is due to the fact that RCU does not
invoke callbacks until it is fully initialized, and this full
initialization cannot occur until after the scheduler has initialized
itself to the point where RCU can spawn and run its kthreads. In theory,
it would be possible to invoke callbacks earlier, however, this is not a
panacea because there would be severe restrictions on what operations
those callbacks could invoke.</p>
<p>Perhaps surprisingly, <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a>, will operate normally during very early
boot, the reason being that there is only one CPU and preemption is
disabled. This means that the call <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> (or friends)
itself is a quiescent state and thus a grace period, so the early-boot
implementation can be a no-op.</p>
<p>However, once the scheduler has spawned its first kthread, this early
boot trick fails for <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> (as well as for
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a>) in <code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=y</span></code> kernels. The
reason is that an RCU read-side critical section might be preempted,
which means that a subsequent <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> really does have to
wait for something, as opposed to simply returning immediately.
Unfortunately, <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> can’t do this until all of its
kthreads are spawned, which doesn’t happen until some time during
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">early_initcalls()</span></code> time. But this is no excuse: RCU is nevertheless
required to correctly handle synchronous grace periods during this time
period. Once all of its kthreads are up and running, RCU starts running
normally.</p>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>How can RCU possibly handle grace periods before all of its kthreads
have been spawned???</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Very carefully!
During the “dead zone” between the time that the scheduler spawns the
first task and the time that all of RCU’s kthreads have been spawned,
all synchronous grace periods are handled by the expedited
grace-period mechanism. At runtime, this expedited mechanism relies
on workqueues, but during the dead zone the requesting task itself
drives the desired expedited grace period. Because dead-zone
execution takes place within task context, everything works. Once the
dead zone ends, expedited grace periods go back to using workqueues,
as is required to avoid problems that would otherwise occur when a
user task received a POSIX signal while driving an expedited grace
period.</p>
<p>And yes, this does mean that it is unhelpful to send POSIX signals to
random tasks between the time that the scheduler spawns its first
kthread and the time that RCU’s kthreads have all been spawned. If
there ever turns out to be a good reason for sending POSIX signals
during that time, appropriate adjustments will be made. (If it turns
out that POSIX signals are sent during this time for no good reason,
other adjustments will be made, appropriate or otherwise.)</p>
</td>
</tr>
</tbody>
</table>
<p>I learned of these boot-time requirements as a result of a series of
system hangs.</p>
</section>
<section id="interrupts-and-nmis">
<h3>Interrupts and NMIs<a class="headerlink" href="#interrupts-and-nmis" title="Link to this heading">¶</a></h3>
<p>The Linux kernel has interrupts, and RCU read-side critical sections are
legal within interrupt handlers and within interrupt-disabled regions of
code, as are invocations of <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>.</p>
<p>Some Linux-kernel architectures can enter an interrupt handler from
non-idle process context, and then just never leave it, instead
stealthily transitioning back to process context. This trick is
sometimes used to invoke system calls from inside the kernel. These
“half-interrupts” mean that RCU has to be very careful about how it
counts interrupt nesting levels. I learned of this requirement the hard
way during a rewrite of RCU’s dyntick-idle code.</p>
<p>The Linux kernel has non-maskable interrupts (NMIs), and RCU read-side
critical sections are legal within NMI handlers. Thankfully, RCU
update-side primitives, including <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>, are prohibited within
NMI handlers.</p>
<p>The name notwithstanding, some Linux-kernel architectures can have
nested NMIs, which RCU must handle correctly. Andy Lutomirski <a class="reference external" href="https://lore.kernel.org/r/CALCETrXLq1y7e_dKFPgou-FKHB6Pu-r8+t-6Ds+8=va7anBWDA&#64;mail.gmail.com">surprised
me</a>
with this requirement; he also kindly surprised me with <a class="reference external" href="https://lore.kernel.org/r/CALCETrXSY9JpW3uE6H8WYk81sg56qasA2aqmjMPsq5dOtzso=g&#64;mail.gmail.com">an
algorithm</a>
that meets this requirement.</p>
<p>Furthermore, NMI handlers can be interrupted by what appear to RCU to be
normal interrupts. One way that this can happen is for code that
directly invokes <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">ct_irq_enter()</span></code> and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">ct_irq_exit()</span></code> to be called
from an NMI handler. This astonishing fact of life prompted the current
code structure, which has <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">ct_irq_enter()</span></code> invoking
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">ct_nmi_enter()</span></code> and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">ct_irq_exit()</span></code> invoking <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">ct_nmi_exit()</span></code>.
And yes, I also learned of this requirement the hard way.</p>
</section>
<section id="loadable-modules">
<h3>Loadable Modules<a class="headerlink" href="#loadable-modules" title="Link to this heading">¶</a></h3>
<p>The Linux kernel has loadable modules, and these modules can also be
unloaded. After a given module has been unloaded, any attempt to call
one of its functions results in a segmentation fault. The module-unload
functions must therefore cancel any delayed calls to loadable-module
functions, for example, any outstanding <a class="reference internal" href="../../../driver-api/basics.html#c.mod_timer" title="mod_timer"><code class="xref c c-func docutils literal notranslate"><span class="pre">mod_timer()</span></code></a> must be dealt
with via <a class="reference internal" href="../../../driver-api/basics.html#c.timer_shutdown_sync" title="timer_shutdown_sync"><code class="xref c c-func docutils literal notranslate"><span class="pre">timer_shutdown_sync()</span></code></a> or similar.</p>
<p>Unfortunately, there is no way to cancel an RCU callback; once you
invoke <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>, the callback function is eventually going to be
invoked, unless the system goes down first. Because it is normally
considered socially irresponsible to crash the system in response to a
module unload request, we need some other way to deal with in-flight RCU
callbacks.</p>
<p>RCU therefore provides <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a>, which waits until all
in-flight RCU callbacks have been invoked. If a module uses
<a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>, its exit function should therefore prevent any future
invocation of <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>, then invoke <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a>. In theory,
the underlying module-unload code could invoke <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a>
unconditionally, but in practice this would incur unacceptable
latencies.</p>
<p>Nikita Danilov noted this requirement for an analogous
filesystem-unmount situation, and Dipankar Sarma incorporated
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> into RCU. The need for <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> for module
unloading became apparent later.</p>
<div class="admonition important">
<p class="admonition-title">Important</p>
<p>The <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> function is not, repeat,
<em>not</em>, obligated to wait for a grace period. It is instead only required
to wait for RCU callbacks that have already been posted. Therefore, if
there are no RCU callbacks posted anywhere in the system,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> is within its rights to return immediately. Even if
there are callbacks posted, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> does not necessarily need
to wait for a grace period.</p>
</div>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Wait a minute! Each RCU callbacks must wait for a grace period to
complete, and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> must wait for each pre-existing
callback to be invoked. Doesn’t <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> therefore need to
wait for a full grace period if there is even one callback posted
anywhere in the system?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Absolutely not!!!
Yes, each RCU callbacks must wait for a grace period to complete, but
it might well be partly (or even completely) finished waiting by the
time <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> is invoked. In that case, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a>
need only wait for the remaining portion of the grace period to
elapse. So even if there are quite a few callbacks posted,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> might well return quite quickly.</p>
<p>So if you need to wait for a grace period as well as for all
pre-existing callbacks, you will need to invoke both
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a>. If latency is a concern,
you can always use workqueues to invoke them concurrently.</p>
</td>
</tr>
</tbody>
</table>
</section>
<section id="hotplug-cpu">
<h3>Hotplug CPU<a class="headerlink" href="#hotplug-cpu" title="Link to this heading">¶</a></h3>
<p>The Linux kernel supports CPU hotplug, which means that CPUs can come
and go. It is of course illegal to use any RCU API member from an
offline CPU, with the exception of <a class="reference internal" href="#sleepable-rcu">SRCU</a> read-side
critical sections. This requirement was present from day one in
DYNIX/ptx, but on the other hand, the Linux kernel’s CPU-hotplug
implementation is “interesting.”</p>
<p>The Linux-kernel CPU-hotplug implementation has notifiers that are used
to allow the various kernel subsystems (including RCU) to respond
appropriately to a given CPU-hotplug operation. Most RCU operations may
be invoked from CPU-hotplug notifiers, including even synchronous
grace-period operations such as (<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a>).  However, these synchronous operations
do block and therefore cannot be invoked from notifiers that execute via
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">stop_machine()</span></code>, specifically those between the <code class="docutils literal notranslate"><span class="pre">CPUHP_AP_OFFLINE</span></code>
and <code class="docutils literal notranslate"><span class="pre">CPUHP_AP_ONLINE</span></code> states.</p>
<p>In addition, all-callback-wait operations such as <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> may
not be invoked from any CPU-hotplug notifier.  This restriction is due
to the fact that there are phases of CPU-hotplug operations where the
outgoing CPU’s callbacks will not be invoked until after the CPU-hotplug
operation ends, which could also result in deadlock. Furthermore,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> blocks CPU-hotplug operations during its execution,
which results in another type of deadlock when invoked from a CPU-hotplug
notifier.</p>
<p>Finally, RCU must avoid deadlocks due to interaction between hotplug,
timers and grace period processing. It does so by maintaining its own set
of books that duplicate the centrally maintained <code class="docutils literal notranslate"><span class="pre">cpu_online_mask</span></code>,
and also by reporting quiescent states explicitly when a CPU goes
offline.  This explicit reporting of quiescent states avoids any need
for the force-quiescent-state loop (FQS) to report quiescent states for
offline CPUs.  However, as a debugging measure, the FQS loop does splat
if offline CPUs block an RCU grace period for too long.</p>
<p>An offline CPU’s quiescent state will be reported either:</p>
<ol class="arabic simple">
<li><p>As the CPU goes offline using RCU’s hotplug notifier (<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcutree_report_cpu_dead()</span></code>).</p></li>
<li><p>When grace period initialization (<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_gp_init()</span></code>) detects a
race either with CPU offlining or with a task unblocking on a leaf
<code class="docutils literal notranslate"><span class="pre">rcu_node</span></code> structure whose CPUs are all offline.</p></li>
</ol>
<p>The CPU-online path (<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcutree_report_cpu_starting()</span></code>) should never need to report
a quiescent state for an offline CPU.  However, as a debugging measure,
it does emit a warning if a quiescent state was not already reported
for that CPU.</p>
<p>During the checking/modification of RCU’s hotplug bookkeeping, the
corresponding CPU’s leaf node lock is held. This avoids race conditions
between RCU’s hotplug notifier hooks, the grace period initialization
code, and the FQS loop, all of which refer to or modify this bookkeeping.</p>
<p>Note that grace period initialization (<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_gp_init()</span></code>) must carefully sequence
CPU hotplug scanning with grace period state changes. For example, the
following race could occur in <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_gp_init()</span></code> if <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_seq_start()</span></code> were to happen
after the CPU hotplug scanning:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>CPU0 (rcu_gp_init)                   CPU1                          CPU2
---------------------                ----                          ----
// Hotplug scan first (WRONG ORDER)
rcu_for_each_leaf_node(rnp) {
    rnp-&gt;qsmaskinit = rnp-&gt;qsmaskinitnext;
}
                                     rcutree_report_cpu_starting()
                                         rnp-&gt;qsmaskinitnext |= mask;
                                     rcu_read_lock()
                                     r0 = *X;
                                                                   r1 = *X;
                                                                   X = NULL;
                                                                   cookie = get_state_synchronize_rcu();
                                                                   // cookie = 8 (future GP)
rcu_seq_start(&amp;rcu_state.gp_seq);
// gp_seq = 5

// CPU1 now invisible to this GP!
rcu_for_each_node_breadth_first() {
    rnp-&gt;qsmask = rnp-&gt;qsmaskinit;
    // CPU1 not included!
}

// GP completes without CPU1
rcu_seq_end(&amp;rcu_state.gp_seq);
// gp_seq = 8
                                                                   poll_state_synchronize_rcu(cookie);
                                                                   // Returns true!
                                                                   kfree(r1);
                                     r2 = *r0; // USE-AFTER-FREE!
</pre></div>
</div>
<p>By incrementing <code class="docutils literal notranslate"><span class="pre">gp_seq</span></code> first, CPU1’s RCU read-side critical section
is guaranteed to not be missed by CPU2.</p>
<section id="concurrent-quiescent-state-reporting-for-offline-cpus">
<h4>Concurrent Quiescent State Reporting for Offline CPUs<a class="headerlink" href="#concurrent-quiescent-state-reporting-for-offline-cpus" title="Link to this heading">¶</a></h4>
<p>RCU must ensure that CPUs going offline report quiescent states to avoid
blocking grace periods. This requires careful synchronization to handle
race conditions</p>
</section>
<section id="race-condition-causing-offline-cpu-to-hang-gp">
<h4>Race condition causing Offline CPU to hang GP<a class="headerlink" href="#race-condition-causing-offline-cpu-to-hang-gp" title="Link to this heading">¶</a></h4>
<p>A race between CPU offlining and new GP initialization (<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">gp_init()</span></code>) may occur
because <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_report_qs_rnp()</span></code> in <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcutree_report_cpu_dead()</span></code> must temporarily
release the <code class="docutils literal notranslate"><span class="pre">rcu_node</span></code> lock to wake the RCU grace-period kthread:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>CPU1 (going offline)                 CPU0 (GP kthread)
--------------------                 -----------------
rcutree_report_cpu_dead()
  rcu_report_qs_rnp()
    // Must release rnp-&gt;lock to wake GP kthread
    raw_spin_unlock_irqrestore_rcu_node()
                                     // Wakes up and starts new GP
                                     rcu_gp_init()
                                       // First loop:
                                       copies qsmaskinitnext-&gt;qsmaskinit
                                       // CPU1 still in qsmaskinitnext!

                                       // Second loop:
                                       rnp-&gt;qsmask = rnp-&gt;qsmaskinit
                                       mask = rnp-&gt;qsmask &amp; ~rnp-&gt;qsmaskinitnext
                                       // mask is 0! CPU1 still in both masks
    // Reacquire lock (but too late)
  rnp-&gt;qsmaskinitnext &amp;= ~mask       // Finally clears bit
</pre></div>
</div>
<p>Without <code class="docutils literal notranslate"><span class="pre">ofl_lock</span></code>, the new grace period includes the offline CPU and waits
forever for its quiescent state causing a GP hang.</p>
</section>
<section id="a-solution-with-ofl-lock">
<h4>A solution with ofl_lock<a class="headerlink" href="#a-solution-with-ofl-lock" title="Link to this heading">¶</a></h4>
<p>The <code class="docutils literal notranslate"><span class="pre">ofl_lock</span></code> (offline lock) prevents <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_gp_init()</span></code> from running during
the vulnerable window when <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_report_qs_rnp()</span></code> has released <code class="docutils literal notranslate"><span class="pre">rnp-&gt;lock</span></code>:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>CPU0 (rcu_gp_init)                   CPU1 (rcutree_report_cpu_dead)
------------------                   ------------------------------
rcu_for_each_leaf_node(rnp) {
    arch_spin_lock(&amp;ofl_lock) -----&gt; arch_spin_lock(&amp;ofl_lock) [BLOCKED]

    // Safe: CPU1 can&#39;t interfere
    rnp-&gt;qsmaskinit = rnp-&gt;qsmaskinitnext

    arch_spin_unlock(&amp;ofl_lock) ---&gt; // Now CPU1 can proceed
}                                    // But snapshot already taken
</pre></div>
</div>
</section>
<section id="another-race-causing-gp-hangs-in-rcu-gpu-init-reporting-qs-for-now-offline-cpus">
<h4>Another race causing GP hangs in rcu_gpu_init(): Reporting QS for Now-offline CPUs<a class="headerlink" href="#another-race-causing-gp-hangs-in-rcu-gpu-init-reporting-qs-for-now-offline-cpus" title="Link to this heading">¶</a></h4>
<p>After the first loop takes an atomic snapshot of online CPUs, as shown above,
the second loop in <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_gp_init()</span></code> detects CPUs that went offline between
releasing <code class="docutils literal notranslate"><span class="pre">ofl_lock</span></code> and acquiring the per-node <code class="docutils literal notranslate"><span class="pre">rnp-&gt;lock</span></code>.
This detection is crucial because:</p>
<ol class="arabic simple">
<li><p>The CPU might have gone offline after the snapshot but before the second loop</p></li>
<li><p>The offline CPU cannot report its own QS if it’s already dead</p></li>
<li><p>Without this detection, the grace period would wait forever for CPUs that
are now offline.</p></li>
</ol>
<p>The second loop performs this detection safely:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>rcu_for_each_node_breadth_first(rnp) {
    raw_spin_lock_irqsave_rcu_node(rnp, flags);
    rnp-&gt;qsmask = rnp-&gt;qsmaskinit;  // Apply the snapshot

    // Detect CPUs offline after snapshot
    mask = rnp-&gt;qsmask &amp; ~rnp-&gt;qsmaskinitnext;

    if (mask &amp;&amp; rcu_is_leaf_node(rnp))
        rcu_report_qs_rnp(mask, ...)  // Report QS for offline CPUs
}
</pre></div>
</div>
<p>This approach ensures atomicity: quiescent state reporting for offline CPUs
happens either in <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_gp_init()</span></code> (second loop) or in <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcutree_report_cpu_dead()</span></code>,
never both and never neither. The <code class="docutils literal notranslate"><span class="pre">rnp-&gt;lock</span></code> held throughout the sequence
prevents races - <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcutree_report_cpu_dead()</span></code> also acquires this lock when
clearing <code class="docutils literal notranslate"><span class="pre">qsmaskinitnext</span></code>, ensuring mutual exclusion.</p>
</section>
</section>
<section id="scheduler-and-rcu">
<h3>Scheduler and RCU<a class="headerlink" href="#scheduler-and-rcu" title="Link to this heading">¶</a></h3>
<p>RCU makes use of kthreads, and it is necessary to avoid excessive CPU-time
accumulation by these kthreads. This requirement was no surprise, but
RCU’s violation of it when running context-switch-heavy workloads when
built with <code class="docutils literal notranslate"><span class="pre">CONFIG_NO_HZ_FULL=y</span></code> <a class="reference external" href="http://www.rdrop.com/users/paulmck/scalability/paper/BareMetal.2015.01.15b.pdf">did come as a surprise
[PDF]</a>.
RCU has made good progress towards meeting this requirement, even for
context-switch-heavy <code class="docutils literal notranslate"><span class="pre">CONFIG_NO_HZ_FULL=y</span></code> workloads, but there is
room for further improvement.</p>
<p>There is no longer any prohibition against holding any of
scheduler’s runqueue or priority-inheritance spinlocks across an
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a>, even if interrupts and preemption were enabled
somewhere within the corresponding RCU read-side critical section.
Therefore, it is now perfectly legal to execute <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a>
with preemption enabled, acquire one of the scheduler locks, and hold
that lock across the matching <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a>.</p>
<p>Similarly, the RCU flavor consolidation has removed the need for negative
nesting.  The fact that interrupt-disabled regions of code act as RCU
read-side critical sections implicitly avoids earlier issues that used
to result in destructive recursion via interrupt handler’s use of RCU.</p>
</section>
<section id="tracing-and-rcu">
<h3>Tracing and RCU<a class="headerlink" href="#tracing-and-rcu" title="Link to this heading">¶</a></h3>
<p>It is possible to use tracing on RCU code, but tracing itself uses RCU.
For this reason, <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_dereference_raw_check()</span></code> is provided for use
by tracing, which avoids the destructive recursion that could otherwise
ensue. This API is also used by virtualization in some architectures,
where RCU readers execute in environments in which tracing cannot be
used. The tracing folks both located the requirement and provided the
needed fix, so this surprise requirement was relatively painless.</p>
</section>
<section id="accesses-to-user-memory-and-rcu">
<h3>Accesses to User Memory and RCU<a class="headerlink" href="#accesses-to-user-memory-and-rcu" title="Link to this heading">¶</a></h3>
<p>The kernel needs to access user-space memory, for example, to access data
referenced by system-call parameters.  The <a class="reference internal" href="../../../core-api/mm-api.html#c.get_user" title="get_user"><code class="xref c c-func docutils literal notranslate"><span class="pre">get_user()</span></code></a> macro does this job.</p>
<p>However, user-space memory might well be paged out, which means that
<a class="reference internal" href="../../../core-api/mm-api.html#c.get_user" title="get_user"><code class="xref c c-func docutils literal notranslate"><span class="pre">get_user()</span></code></a> might well page-fault and thus block while waiting for the
resulting I/O to complete.  It would be a very bad thing for the compiler to
reorder a <a class="reference internal" href="../../../core-api/mm-api.html#c.get_user" title="get_user"><code class="xref c c-func docutils literal notranslate"><span class="pre">get_user()</span></code></a> invocation into an RCU read-side critical section.</p>
<p>For example, suppose that the source code looked like this:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span>1 rcu_read_lock();
2 p = rcu_dereference(gp);
3 v = p-&gt;value;
4 rcu_read_unlock();
5 get_user(user_v, user_p);
6 do_something_with(v, user_v);
</pre></div>
</div>
</div></blockquote>
<p>The compiler must not be permitted to transform this source code into
the following:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span>1 rcu_read_lock();
2 p = rcu_dereference(gp);
3 get_user(user_v, user_p); // BUG: POSSIBLE PAGE FAULT!!!
4 v = p-&gt;value;
5 rcu_read_unlock();
6 do_something_with(v, user_v);
</pre></div>
</div>
</div></blockquote>
<p>If the compiler did make this transformation in a <code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=n</span></code> kernel
build, and if <a class="reference internal" href="../../../core-api/mm-api.html#c.get_user" title="get_user"><code class="xref c c-func docutils literal notranslate"><span class="pre">get_user()</span></code></a> did page fault, the result would be a quiescent
state in the middle of an RCU read-side critical section.  This misplaced
quiescent state could result in line 4 being a use-after-free access,
which could be bad for your kernel’s actuarial statistics.  Similar examples
can be constructed with the call to <a class="reference internal" href="../../../core-api/mm-api.html#c.get_user" title="get_user"><code class="xref c c-func docutils literal notranslate"><span class="pre">get_user()</span></code></a> preceding the
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a>.</p>
<p>Unfortunately, <a class="reference internal" href="../../../core-api/mm-api.html#c.get_user" title="get_user"><code class="xref c c-func docutils literal notranslate"><span class="pre">get_user()</span></code></a> doesn’t have any particular ordering properties,
and in some architectures the underlying <code class="docutils literal notranslate"><span class="pre">asm</span></code> isn’t even marked
<code class="docutils literal notranslate"><span class="pre">volatile</span></code>.  And even if it was marked <code class="docutils literal notranslate"><span class="pre">volatile</span></code>, the above access to
<code class="docutils literal notranslate"><span class="pre">p-&gt;value</span></code> is not volatile, so the compiler would not have any reason to keep
those two accesses in order.</p>
<p>Therefore, the Linux-kernel definitions of <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> must act as compiler barriers, at least for outermost
instances of <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a> within a nested set
of RCU read-side critical sections.</p>
</section>
<section id="energy-efficiency">
<h3>Energy Efficiency<a class="headerlink" href="#energy-efficiency" title="Link to this heading">¶</a></h3>
<p>Interrupting idle CPUs is considered socially unacceptable, especially
by people with battery-powered embedded systems. RCU therefore conserves
energy by detecting which CPUs are idle, including tracking CPUs that
have been interrupted from idle. This is a large part of the
energy-efficiency requirement, so I learned of this via an irate phone
call.</p>
<p>Because RCU avoids interrupting idle CPUs, it is illegal to execute an
RCU read-side critical section on an idle CPU. (Kernels built with
<code class="docutils literal notranslate"><span class="pre">CONFIG_PROVE_RCU=y</span></code> will splat if you try it.)</p>
<p>It is similarly socially unacceptable to interrupt an <code class="docutils literal notranslate"><span class="pre">nohz_full</span></code> CPU
running in userspace. RCU must therefore track <code class="docutils literal notranslate"><span class="pre">nohz_full</span></code> userspace
execution. RCU must therefore be able to sample state at two points in
time, and be able to determine whether or not some other CPU spent any
time idle and/or executing in userspace.</p>
<p>These energy-efficiency requirements have proven quite difficult to
understand and to meet, for example, there have been more than five
clean-sheet rewrites of RCU’s energy-efficiency code, the last of which
was finally able to demonstrate <a class="reference external" href="http://www.rdrop.com/users/paulmck/realtime/paper/AMPenergy.2013.04.19a.pdf">real energy savings running on real
hardware
[PDF]</a>.
As noted earlier, I learned of many of these requirements via angry
phone calls: Flaming me on the Linux-kernel mailing list was apparently
not sufficient to fully vent their ire at RCU’s energy-efficiency bugs!</p>
</section>
<section id="scheduling-clock-interrupts-and-rcu">
<h3>Scheduling-Clock Interrupts and RCU<a class="headerlink" href="#scheduling-clock-interrupts-and-rcu" title="Link to this heading">¶</a></h3>
<p>The kernel transitions between in-kernel non-idle execution, userspace
execution, and the idle loop. Depending on kernel configuration, RCU
handles these states differently:</p>
<table class="docutils align-default">
<thead>
<tr class="row-odd"><th class="head"><p><code class="docutils literal notranslate"><span class="pre">HZ</span></code> Kconfig</p></th>
<th class="head"><p>In-Kernel</p></th>
<th class="head"><p>Usermode</p></th>
<th class="head"><p>Idle</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">HZ_PERIODIC</span></code></p></td>
<td><p>Can rely on
scheduling-clock
interrupt.</p></td>
<td><p>Can rely on
scheduling-clock
interrupt and
its detection
of interrupt
from usermode.</p></td>
<td><p>Can rely on
RCU’s
dyntick-idle
detection.</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">NO_HZ_IDLE</span></code></p></td>
<td><p>Can rely on
scheduling-clock
interrupt.</p></td>
<td><p>Can rely on
scheduling-clock
interrupt and
its detection
of interrupt
from usermode.</p></td>
<td><p>Can rely on
RCU’s
dyntick-idle
detection.</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">NO_HZ_FULL</span></code></p></td>
<td><p>Can only
sometimes rely
on
scheduling-clock
interrupt. In
other cases, it
is necessary to
bound kernel
execution times
and/or use
IPIs.</p></td>
<td><p>Can rely on
RCU’s
dyntick-idle
detection.</p></td>
<td><p>Can rely on
RCU’s
dyntick-idle
detection.</p></td>
</tr>
</tbody>
</table>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Why can’t <code class="docutils literal notranslate"><span class="pre">NO_HZ_FULL</span></code> in-kernel execution rely on the
scheduling-clock interrupt, just like <code class="docutils literal notranslate"><span class="pre">HZ_PERIODIC</span></code> and
<code class="docutils literal notranslate"><span class="pre">NO_HZ_IDLE</span></code> do?</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>Because, as a performance optimization, <code class="docutils literal notranslate"><span class="pre">NO_HZ_FULL</span></code> does not
necessarily re-enable the scheduling-clock interrupt on entry to each
and every system call.</p></td>
</tr>
</tbody>
</table>
<p>However, RCU must be reliably informed as to whether any given CPU is
currently in the idle loop, and, for <code class="docutils literal notranslate"><span class="pre">NO_HZ_FULL</span></code>, also whether that
CPU is executing in usermode, as discussed
<a class="reference internal" href="#energy-efficiency">earlier</a>. It also requires that the
scheduling-clock interrupt be enabled when RCU needs it to be:</p>
<ol class="arabic simple">
<li><p>If a CPU is either idle or executing in usermode, and RCU believes it
is non-idle, the scheduling-clock tick had better be running.
Otherwise, you will get RCU CPU stall warnings. Or at best, very long
(11-second) grace periods, with a pointless IPI waking the CPU from
time to time.</p></li>
<li><p>If a CPU is in a portion of the kernel that executes RCU read-side
critical sections, and RCU believes this CPU to be idle, you will get
random memory corruption. <strong>DON’T DO THIS!!!</strong>
This is one reason to test with lockdep, which will complain about
this sort of thing.</p></li>
<li><p>If a CPU is in a portion of the kernel that is absolutely positively
no-joking guaranteed to never execute any RCU read-side critical
sections, and RCU believes this CPU to be idle, no problem. This
sort of thing is used by some architectures for light-weight
exception handlers, which can then avoid the overhead of
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">ct_irq_enter()</span></code> and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">ct_irq_exit()</span></code> at exception entry and
exit, respectively. Some go further and avoid the entireties of
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">irq_enter()</span></code> and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">irq_exit()</span></code>.
Just make very sure you are running some of your tests with
<code class="docutils literal notranslate"><span class="pre">CONFIG_PROVE_RCU=y</span></code>, just in case one of your code paths was in
fact joking about not doing RCU read-side critical sections.</p></li>
<li><p>If a CPU is executing in the kernel with the scheduling-clock
interrupt disabled and RCU believes this CPU to be non-idle, and if
the CPU goes idle (from an RCU perspective) every few jiffies, no
problem. It is usually OK for there to be the occasional gap between
idle periods of up to a second or so.
If the gap grows too long, you get RCU CPU stall warnings.</p></li>
<li><p>If a CPU is either idle or executing in usermode, and RCU believes it
to be idle, of course no problem.</p></li>
<li><p>If a CPU is executing in the kernel, the kernel code path is passing
through quiescent states at a reasonable frequency (preferably about
once per few jiffies, but the occasional excursion to a second or so
is usually OK) and the scheduling-clock interrupt is enabled, of
course no problem.
If the gap between a successive pair of quiescent states grows too
long, you get RCU CPU stall warnings.</p></li>
</ol>
<table class="docutils align-default">
<tbody>
<tr class="row-odd"><td><p><strong>Quick Quiz</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>But what if my driver has a hardware interrupt handler that can run
for many seconds? I cannot invoke <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">schedule()</span></code> from an hardware
interrupt handler, after all!</p></td>
</tr>
<tr class="row-odd"><td><p><strong>Answer</strong>:</p></td>
</tr>
<tr class="row-even"><td><p>One approach is to do <code class="docutils literal notranslate"><span class="pre">ct_irq_exit();ct_irq_enter();</span></code> every so
often. But given that long-running interrupt handlers can cause other
problems, not least for response time, shouldn’t you work to keep
your interrupt handler’s runtime within reasonable bounds?</p></td>
</tr>
</tbody>
</table>
<p>But as long as RCU is properly informed of kernel state transitions
between in-kernel execution, usermode execution, and idle, and as long
as the scheduling-clock interrupt is enabled when RCU needs it to be,
you can rest assured that the bugs you encounter will be in some other
part of RCU or some other part of the kernel!</p>
</section>
<section id="memory-efficiency">
<h3>Memory Efficiency<a class="headerlink" href="#memory-efficiency" title="Link to this heading">¶</a></h3>
<p>Although small-memory non-realtime systems can simply use Tiny RCU, code
size is only one aspect of memory efficiency. Another aspect is the size
of the <code class="docutils literal notranslate"><span class="pre">rcu_head</span></code> structure used by <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a>. Although this structure contains nothing more than a
pair of pointers, it does appear in many RCU-protected data structures,
including some that are size critical. The <code class="docutils literal notranslate"><span class="pre">page</span></code> structure is a case
in point, as evidenced by the many occurrences of the <code class="docutils literal notranslate"><span class="pre">union</span></code> keyword
within that structure.</p>
<p>This need for memory efficiency is one reason that RCU uses hand-crafted
singly linked lists to track the <code class="docutils literal notranslate"><span class="pre">rcu_head</span></code> structures that are
waiting for a grace period to elapse. It is also the reason why
<code class="docutils literal notranslate"><span class="pre">rcu_head</span></code> structures do not contain debug information, such as fields
tracking the file and line of the <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> or <a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a> that
posted them. Although this information might appear in debug-only kernel
builds at some point, in the meantime, the <code class="docutils literal notranslate"><span class="pre">-&gt;func</span></code> field will often
provide the needed debug information.</p>
<p>However, in some cases, the need for memory efficiency leads to even
more extreme measures. Returning to the <code class="docutils literal notranslate"><span class="pre">page</span></code> structure, the
<code class="docutils literal notranslate"><span class="pre">rcu_head</span></code> field shares storage with a great many other structures
that are used at various points in the corresponding page’s lifetime. In
order to correctly resolve certain <a class="reference external" href="https://lore.kernel.org/r/1439976106-137226-1-git-send-email-kirill.shutemov&#64;linux.intel.com">race
conditions</a>,
the Linux kernel’s memory-management subsystem needs a particular bit to
remain zero during all phases of grace-period processing, and that bit
happens to map to the bottom bit of the <code class="docutils literal notranslate"><span class="pre">rcu_head</span></code> structure’s
<code class="docutils literal notranslate"><span class="pre">-&gt;next</span></code> field. RCU makes this guarantee as long as <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> is
used to post the callback, as opposed to <a class="reference internal" href="../../../core-api/kernel-api.html#c.kfree_rcu" title="kfree_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">kfree_rcu()</span></code></a> or some future
“lazy” variant of <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> that might one day be created for
energy-efficiency purposes.</p>
<p>That said, there are limits. RCU requires that the <code class="docutils literal notranslate"><span class="pre">rcu_head</span></code>
structure be aligned to a two-byte boundary, and passing a misaligned
<code class="docutils literal notranslate"><span class="pre">rcu_head</span></code> structure to one of the <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> family of functions
will result in a splat. It is therefore necessary to exercise caution
when packing structures containing fields of type <code class="docutils literal notranslate"><span class="pre">rcu_head</span></code>. Why not
a four-byte or even eight-byte alignment requirement? Because the m68k
architecture provides only two-byte alignment, and thus acts as
alignment’s least common denominator.</p>
<p>The reason for reserving the bottom bit of pointers to <code class="docutils literal notranslate"><span class="pre">rcu_head</span></code>
structures is to leave the door open to “lazy” callbacks whose
invocations can safely be deferred. Deferring invocation could
potentially have energy-efficiency benefits, but only if the rate of
non-lazy callbacks decreases significantly for some important workload.
In the meantime, reserving the bottom bit keeps this option open in case
it one day becomes useful.</p>
</section>
<section id="performance-scalability-response-time-and-reliability">
<h3>Performance, Scalability, Response Time, and Reliability<a class="headerlink" href="#performance-scalability-response-time-and-reliability" title="Link to this heading">¶</a></h3>
<p>Expanding on the <a class="reference internal" href="#performance-and-scalability">earlier
discussion</a>, RCU is used heavily by
hot code paths in performance-critical portions of the Linux kernel’s
networking, security, virtualization, and scheduling code paths. RCU
must therefore use efficient implementations, especially in its
read-side primitives. To that end, it would be good if preemptible RCU’s
implementation of <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> could be inlined, however, doing
this requires resolving <code class="docutils literal notranslate"><span class="pre">#include</span></code> issues with the <code class="docutils literal notranslate"><span class="pre">task_struct</span></code>
structure.</p>
<p>The Linux kernel supports hardware configurations with up to 4096 CPUs,
which means that RCU must be extremely scalable. Algorithms that involve
frequent acquisitions of global locks or frequent atomic operations on
global variables simply cannot be tolerated within the RCU
implementation. RCU therefore makes heavy use of a combining tree based
on the <code class="docutils literal notranslate"><span class="pre">rcu_node</span></code> structure. RCU is required to tolerate all CPUs
continuously invoking any combination of RCU’s runtime primitives with
minimal per-operation overhead. In fact, in many cases, increasing load
must <em>decrease</em> the per-operation overhead, witness the batching
optimizations for <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a>, and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a>. As a general
rule, RCU must cheerfully accept whatever the rest of the Linux kernel
decides to throw at it.</p>
<p>The Linux kernel is used for real-time workloads, especially in
conjunction with the <a class="reference external" href="https://wiki.linuxfoundation.org/realtime/">-rt
patchset</a>. The
real-time-latency response requirements are such that the traditional
approach of disabling preemption across RCU read-side critical sections
is inappropriate. Kernels built with <code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=y</span></code> therefore use
an RCU implementation that allows RCU read-side critical sections to be
preempted. This requirement made its presence known after users made it
clear that an earlier <a class="reference external" href="https://lwn.net/Articles/107930/">real-time
patch</a> did not meet their needs, in
conjunction with some <a class="reference external" href="https://lore.kernel.org/r/20050318002026.GA2693&#64;us.ibm.com">RCU
issues</a>
encountered by a very early version of the -rt patchset.</p>
<p>In addition, RCU must make do with a sub-100-microsecond real-time
latency budget. In fact, on smaller systems with the -rt patchset, the
Linux kernel provides sub-20-microsecond real-time latencies for the
whole kernel, including RCU. RCU’s scalability and latency must
therefore be sufficient for these sorts of configurations. To my
surprise, the sub-100-microsecond real-time latency budget <a class="reference external" href="http://www.rdrop.com/users/paulmck/realtime/paper/bigrt.2013.01.31a.LCA.pdf">applies to
even the largest systems
[PDF]</a>,
up to and including systems with 4096 CPUs. This real-time requirement
motivated the grace-period kthread, which also simplified handling of a
number of race conditions.</p>
<p>RCU must avoid degrading real-time response for CPU-bound threads,
whether executing in usermode (which is one use case for
<code class="docutils literal notranslate"><span class="pre">CONFIG_NO_HZ_FULL=y</span></code>) or in the kernel. That said, CPU-bound loops in
the kernel must execute <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">cond_resched()</span></code> at least once per few tens of
milliseconds in order to avoid receiving an IPI from RCU.</p>
<p>Finally, RCU’s status as a synchronization primitive means that any RCU
failure can result in arbitrary memory corruption that can be extremely
difficult to debug. This means that RCU must be extremely reliable,
which in practice also means that RCU must have an aggressive
stress-test suite. This stress-test suite is called <code class="docutils literal notranslate"><span class="pre">rcutorture</span></code>.</p>
<p>Although the need for <code class="docutils literal notranslate"><span class="pre">rcutorture</span></code> was no surprise, the current
immense popularity of the Linux kernel is posing interesting—and perhaps
unprecedented—validation challenges. To see this, keep in mind that
there are well over one billion instances of the Linux kernel running
today, given Android smartphones, Linux-powered televisions, and
servers. This number can be expected to increase sharply with the advent
of the celebrated Internet of Things.</p>
<p>Suppose that RCU contains a race condition that manifests on average
once per million years of runtime. This bug will be occurring about
three times per <em>day</em> across the installed base. RCU could simply hide
behind hardware error rates, given that no one should really expect
their smartphone to last for a million years. However, anyone taking too
much comfort from this thought should consider the fact that in most
jurisdictions, a successful multi-year test of a given mechanism, which
might include a Linux kernel, suffices for a number of types of
safety-critical certifications. In fact, rumor has it that the Linux
kernel is already being used in production for safety-critical
applications. I don’t know about you, but I would feel quite bad if a
bug in RCU killed someone. Which might explain my recent focus on
validation and verification.</p>
</section>
</section>
<section id="other-rcu-flavors">
<h2>Other RCU Flavors<a class="headerlink" href="#other-rcu-flavors" title="Link to this heading">¶</a></h2>
<p>One of the more surprising things about RCU is that there are now no
fewer than five <em>flavors</em>, or API families. In addition, the primary
flavor that has been the sole focus up to this point has two different
implementations, non-preemptible and preemptible. The other four flavors
are listed below, with requirements for each described in a separate
section.</p>
<ol class="arabic simple">
<li><p><a class="reference internal" href="#bottom-half-flavor-historical">Bottom-Half Flavor (Historical)</a></p></li>
<li><p><a class="reference internal" href="#sched-flavor-historical">Sched Flavor (Historical)</a></p></li>
<li><p><a class="reference internal" href="#sleepable-rcu">Sleepable RCU</a></p></li>
<li><p><a class="reference internal" href="#tasks-rcu">Tasks RCU</a></p></li>
<li><p><a class="reference internal" href="#tasks-trace-rcu">Tasks Trace RCU</a></p></li>
</ol>
<section id="bottom-half-flavor-historical">
<h3>Bottom-Half Flavor (Historical)<a class="headerlink" href="#bottom-half-flavor-historical" title="Link to this heading">¶</a></h3>
<p>The RCU-bh flavor of RCU has since been expressed in terms of the other
RCU flavors as part of a consolidation of the three flavors into a
single flavor. The read-side API remains, and continues to disable
softirq and to be accounted for by lockdep. Much of the material in this
section is therefore strictly historical in nature.</p>
<p>The softirq-disable (AKA “bottom-half”, hence the “_bh” abbreviations)
flavor of RCU, or <em>RCU-bh</em>, was developed by Dipankar Sarma to provide a
flavor of RCU that could withstand the network-based denial-of-service
attacks researched by Robert Olsson. These attacks placed so much
networking load on the system that some of the CPUs never exited softirq
execution, which in turn prevented those CPUs from ever executing a
context switch, which, in the RCU implementation of that time, prevented
grace periods from ever ending. The result was an out-of-memory
condition and a system hang.</p>
<p>The solution was the creation of RCU-bh, which does
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">local_bh_disable()</span></code> across its read-side critical sections, and which
uses the transition from one type of softirq processing to another as a
quiescent state in addition to context switch, idle, user mode, and
offline. This means that RCU-bh grace periods can complete even when
some of the CPUs execute in softirq indefinitely, thus allowing
algorithms based on RCU-bh to withstand network-based denial-of-service
attacks.</p>
<p>Because <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock_bh" title="rcu_read_lock_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock_bh()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_bh" title="rcu_read_unlock_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_bh()</span></code></a> disable and
re-enable softirq handlers, any attempt to start a softirq handlers
during the RCU-bh read-side critical section will be deferred. In this
case, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_bh" title="rcu_read_unlock_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_bh()</span></code></a> will invoke softirq processing, which can
take considerable time. One can of course argue that this softirq
overhead should be associated with the code following the RCU-bh
read-side critical section rather than <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_bh" title="rcu_read_unlock_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_bh()</span></code></a>, but the
fact is that most profiling tools cannot be expected to make this sort
of fine distinction. For example, suppose that a three-millisecond-long
RCU-bh read-side critical section executes during a time of heavy
networking load. There will very likely be an attempt to invoke at least
one softirq handler during that three milliseconds, but any such
invocation will be delayed until the time of the
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_bh" title="rcu_read_unlock_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_bh()</span></code></a>. This can of course make it appear at first
glance as if <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_bh" title="rcu_read_unlock_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_bh()</span></code></a> was executing very slowly.</p>
<p>The <a class="reference external" href="https://lwn.net/Articles/609973/#RCU%20Per-Flavor%20API%20Table">RCU-bh
API</a>
includes <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock_bh" title="rcu_read_lock_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock_bh()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_bh" title="rcu_read_unlock_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_bh()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference_bh" title="rcu_dereference_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference_bh()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference_bh_check" title="rcu_dereference_bh_check"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference_bh_check()</span></code></a>, and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock_bh_held" title="rcu_read_lock_bh_held"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock_bh_held()</span></code></a>. However, the
old RCU-bh update-side APIs are now gone, replaced by <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>, and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a>.  In addition,
anything that disables bottom halves also marks an RCU-bh read-side
critical section, including <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">local_bh_disable()</span></code> and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">local_bh_enable()</span></code>,
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">local_irq_save()</span></code> and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">local_irq_restore()</span></code>, and so on.</p>
</section>
<section id="sched-flavor-historical">
<h3>Sched Flavor (Historical)<a class="headerlink" href="#sched-flavor-historical" title="Link to this heading">¶</a></h3>
<p>The RCU-sched flavor of RCU has since been expressed in terms of the
other RCU flavors as part of a consolidation of the three flavors into a
single flavor. The read-side API remains, and continues to disable
preemption and to be accounted for by lockdep. Much of the material in
this section is therefore strictly historical in nature.</p>
<p>Before preemptible RCU, waiting for an RCU grace period had the side
effect of also waiting for all pre-existing interrupt and NMI handlers.
However, there are legitimate preemptible-RCU implementations that do
not have this property, given that any point in the code outside of an
RCU read-side critical section can be a quiescent state. Therefore,
<em>RCU-sched</em> was created, which follows “classic” RCU in that an
RCU-sched grace period waits for pre-existing interrupt and NMI
handlers. In kernels built with <code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=n</span></code>, the RCU and
RCU-sched APIs have identical implementations, while kernels built with
<code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=y</span></code> provide a separate implementation for each.</p>
<p>Note well that in <code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=y</span></code> kernels,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock_sched" title="rcu_read_lock_sched"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock_sched()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_sched" title="rcu_read_unlock_sched"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_sched()</span></code></a> disable and
re-enable preemption, respectively. This means that if there was a
preemption attempt during the RCU-sched read-side critical section,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_sched" title="rcu_read_unlock_sched"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_sched()</span></code></a> will enter the scheduler, with all the
latency and overhead entailed. Just as with <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_bh" title="rcu_read_unlock_bh"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_bh()</span></code></a>,
this can make it look as if <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_sched" title="rcu_read_unlock_sched"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_sched()</span></code></a> was executing
very slowly. However, the highest-priority task won’t be preempted, so
that task will enjoy low-overhead <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_sched" title="rcu_read_unlock_sched"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_sched()</span></code></a>
invocations.</p>
<p>The <a class="reference external" href="https://lwn.net/Articles/609973/#RCU%20Per-Flavor%20API%20Table">RCU-sched
API</a>
includes <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock_sched" title="rcu_read_lock_sched"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock_sched()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_sched" title="rcu_read_unlock_sched"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_sched()</span></code></a>,
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_read_lock_sched_notrace()</span></code>, <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_read_unlock_sched_notrace()</span></code>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference_sched" title="rcu_dereference_sched"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference_sched()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_dereference_sched_check" title="rcu_dereference_sched_check"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_dereference_sched_check()</span></code></a>, and
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_read_lock_sched_held()</span></code>.  However, the old RCU-sched update-side APIs
are now gone, replaced by <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_expedited" title="synchronize_rcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_expedited()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>, and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a>.  In addition, anything that disables
preemption also marks an RCU-sched read-side critical section,
including <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">preempt_disable()</span></code> and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">preempt_enable()</span></code>, <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">local_irq_save()</span></code>
and <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">local_irq_restore()</span></code>, and so on.</p>
</section>
<section id="sleepable-rcu">
<h3>Sleepable RCU<a class="headerlink" href="#sleepable-rcu" title="Link to this heading">¶</a></h3>
<p>For well over a decade, someone saying “I need to block within an RCU
read-side critical section” was a reliable indication that this someone
did not understand RCU. After all, if you are always blocking in an RCU
read-side critical section, you can probably afford to use a
higher-overhead synchronization mechanism. However, that changed with
the advent of the Linux kernel’s notifiers, whose RCU read-side critical
sections almost never sleep, but sometimes need to. This resulted in the
introduction of <a class="reference external" href="https://lwn.net/Articles/202847/">sleepable RCU</a>, or
<em>SRCU</em>.</p>
<p>SRCU allows different domains to be defined, with each such domain
defined by an instance of an <code class="docutils literal notranslate"><span class="pre">srcu_struct</span></code> structure. A pointer to
this structure must be passed in to each SRCU function, for example,
<code class="docutils literal notranslate"><span class="pre">synchronize_srcu(&amp;ss)</span></code>, where <code class="docutils literal notranslate"><span class="pre">ss</span></code> is the <code class="docutils literal notranslate"><span class="pre">srcu_struct</span></code>
structure. The key benefit of these domains is that a slow SRCU reader
in one domain does not delay an SRCU grace period in some other domain.
That said, one consequence of these domains is that read-side code must
pass a “cookie” from <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_lock" title="srcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_lock()</span></code></a> to <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_unlock" title="srcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_unlock()</span></code></a>, for
example, as follows:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span>1 int idx;
2
3 idx = srcu_read_lock(&amp;ss);
4 do_something();
5 srcu_read_unlock(&amp;ss, idx);
</pre></div>
</div>
</div></blockquote>
<p>As noted above, it is legal to block within SRCU read-side critical
sections, however, with great power comes great responsibility. If you
block forever in one of a given domain’s SRCU read-side critical
sections, then that domain’s grace periods will also be blocked forever.
Of course, one good way to block forever is to deadlock, which can
happen if any operation in a given domain’s SRCU read-side critical
section can wait, either directly or indirectly, for that domain’s grace
period to elapse. For example, this results in a self-deadlock:</p>
<blockquote>
<div><div class="highlight-none notranslate"><div class="highlight"><pre><span></span>1 int idx;
2
3 idx = srcu_read_lock(&amp;ss);
4 do_something();
5 synchronize_srcu(&amp;ss);
6 srcu_read_unlock(&amp;ss, idx);
</pre></div>
</div>
</div></blockquote>
<p>However, if line 5 acquired a mutex that was held across a
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_srcu" title="synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_srcu()</span></code></a> for domain <code class="docutils literal notranslate"><span class="pre">ss</span></code>, deadlock would still be
possible. Furthermore, if line 5 acquired a mutex that was held across a
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_srcu" title="synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_srcu()</span></code></a> for some other domain <code class="docutils literal notranslate"><span class="pre">ss1</span></code>, and if an
<code class="docutils literal notranslate"><span class="pre">ss1</span></code>-domain SRCU read-side critical section acquired another mutex
that was held across as <code class="docutils literal notranslate"><span class="pre">ss</span></code>-domain <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_srcu" title="synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_srcu()</span></code></a>, deadlock
would again be possible. Such a deadlock cycle could extend across an
arbitrarily large number of different SRCU domains. Again, with great
power comes great responsibility.</p>
<p>Unlike the other RCU flavors, SRCU read-side critical sections can run
on idle and even offline CPUs. This ability requires that
<a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_lock" title="srcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_lock()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_unlock" title="srcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_unlock()</span></code></a> contain memory barriers,
which means that SRCU readers will run a bit slower than would RCU
readers. It also motivates the <a class="reference internal" href="../../../core-api/kernel-api.html#c.smp_mb__after_srcu_read_unlock" title="smp_mb__after_srcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">smp_mb__after_srcu_read_unlock()</span></code></a> API,
which, in combination with <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_unlock" title="srcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_unlock()</span></code></a>, guarantees a full
memory barrier.</p>
<p>Also unlike other RCU flavors, <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_srcu" title="synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_srcu()</span></code></a> may <strong>not</strong> be
invoked from CPU-hotplug notifiers, due to the fact that SRCU grace
periods make use of timers and the possibility of timers being
temporarily “stranded” on the outgoing CPU. This stranding of timers
means that timers posted to the outgoing CPU will not fire until late in
the CPU-hotplug process. The problem is that if a notifier is waiting on
an SRCU grace period, that grace period is waiting on a timer, and that
timer is stranded on the outgoing CPU, then the notifier will never be
awakened, in other words, deadlock has occurred. This same situation of
course also prohibits <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_barrier" title="srcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_barrier()</span></code></a> from being invoked from
CPU-hotplug notifiers.</p>
<p>SRCU also differs from other RCU flavors in that SRCU’s expedited and
non-expedited grace periods are implemented by the same mechanism. This
means that in the current SRCU implementation, expediting a future grace
period has the side effect of expediting all prior grace periods that
have not yet completed. (But please note that this is a property of the
current implementation, not necessarily of future implementations.) In
addition, if SRCU has been idle for longer than the interval specified
by the <code class="docutils literal notranslate"><span class="pre">srcutree.exp_holdoff</span></code> kernel boot parameter (25 microseconds
by default), and if a <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_srcu" title="synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_srcu()</span></code></a> invocation ends this idle
period, that invocation will be automatically expedited.</p>
<p>As of v4.12, SRCU’s callbacks are maintained per-CPU, eliminating a
locking bottleneck present in prior kernel versions. Although this will
allow users to put much heavier stress on <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_srcu" title="call_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_srcu()</span></code></a>, it is
important to note that SRCU does not yet take any special steps to deal
with callback flooding. So if you are posting (say) 10,000 SRCU
callbacks per second per CPU, you are probably totally OK, but if you
intend to post (say) 1,000,000 SRCU callbacks per second per CPU, please
run some tests first. SRCU just might need a few adjustment to deal with
that sort of load. Of course, your mileage may vary based on the speed
of your CPUs and the size of your memory.</p>
<p>The <a class="reference external" href="https://lwn.net/Articles/609973/#RCU%20Per-Flavor%20API%20Table">SRCU
API</a>
includes <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_lock" title="srcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_lock()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_unlock" title="srcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_unlock()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_dereference" title="srcu_dereference"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_dereference()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_dereference_check" title="srcu_dereference_check"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_dereference_check()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_srcu" title="synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_srcu()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_srcu_expedited" title="synchronize_srcu_expedited"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_srcu_expedited()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.call_srcu" title="call_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_srcu()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_barrier" title="srcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_barrier()</span></code></a>, and <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_lock_held" title="srcu_read_lock_held"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_lock_held()</span></code></a>. It
also includes <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">DEFINE_SRCU()</span></code>, <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">DEFINE_STATIC_SRCU()</span></code>, and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.init_srcu_struct" title="init_srcu_struct"><code class="xref c c-func docutils literal notranslate"><span class="pre">init_srcu_struct()</span></code></a> APIs for defining and initializing
<code class="docutils literal notranslate"><span class="pre">srcu_struct</span></code> structures.</p>
<p>More recently, the SRCU API has added polling interfaces:</p>
<ol class="arabic simple">
<li><p><a class="reference internal" href="../../../core-api/kernel-api.html#c.start_poll_synchronize_srcu" title="start_poll_synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">start_poll_synchronize_srcu()</span></code></a> returns a cookie identifying
the completion of a future SRCU grace period and ensures
that this grace period will be started.</p></li>
<li><p><a class="reference internal" href="../../../core-api/kernel-api.html#c.poll_state_synchronize_srcu" title="poll_state_synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">poll_state_synchronize_srcu()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">true</span></code> iff the
specified cookie corresponds to an already-completed
SRCU grace period.</p></li>
<li><p><a class="reference internal" href="../../../core-api/kernel-api.html#c.get_state_synchronize_srcu" title="get_state_synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">get_state_synchronize_srcu()</span></code></a> returns a cookie just like
<a class="reference internal" href="../../../core-api/kernel-api.html#c.start_poll_synchronize_srcu" title="start_poll_synchronize_srcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">start_poll_synchronize_srcu()</span></code></a> does, but differs in that
it does nothing to ensure that any future SRCU grace period
will be started.</p></li>
</ol>
<p>These functions are used to avoid unnecessary SRCU grace periods in
certain types of buffer-cache algorithms having multi-stage age-out
mechanisms.  The idea is that by the time the block has aged completely
from the cache, an SRCU grace period will be very likely to have elapsed.</p>
</section>
<section id="tasks-rcu">
<h3>Tasks RCU<a class="headerlink" href="#tasks-rcu" title="Link to this heading">¶</a></h3>
<p>Some forms of tracing use “trampolines” to handle the binary rewriting
required to install different types of probes. It would be good to be
able to free old trampolines, which sounds like a job for some form of
RCU. However, because it is necessary to be able to install a trace
anywhere in the code, it is not possible to use read-side markers such
as <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock" title="rcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a>. In addition, it does
not work to have these markers in the trampoline itself, because there
would need to be instructions following <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a>. Although
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> would guarantee that execution reached the
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock" title="rcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock()</span></code></a>, it would not be able to guarantee that execution
had completely left the trampoline. Worse yet, in some situations
the trampoline’s protection must extend a few instructions <em>prior</em> to
execution reaching the trampoline.  For example, these few instructions
might calculate the address of the trampoline, so that entering the
trampoline would be pre-ordained a surprisingly long time before execution
actually reached the trampoline itself.</p>
<p>The solution, in the form of <a class="reference external" href="https://lwn.net/Articles/607117/">Tasks
RCU</a>, is to have implicit read-side
critical sections that are delimited by voluntary context switches, that
is, calls to <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">schedule()</span></code>, <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">cond_resched()</span></code>, and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_tasks" title="synchronize_rcu_tasks"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_tasks()</span></code></a>. In addition, transitions to and from
userspace execution also delimit tasks-RCU read-side critical sections.
Idle tasks are ignored by Tasks RCU, and Tasks Rude RCU may be used to
interact with them.</p>
<p>Note well that involuntary context switches are <em>not</em> Tasks-RCU quiescent
states.  After all, in preemptible kernels, a task executing code in a
trampoline might be preempted.  In this case, the Tasks-RCU grace period
clearly cannot end until that task resumes and its execution leaves that
trampoline.  This means, among other things, that <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">cond_resched()</span></code> does
not provide a Tasks RCU quiescent state.  (Instead, use <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_softirq_qs" title="rcu_softirq_qs"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_softirq_qs()</span></code></a>
from softirq or <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_tasks_classic_qs()</span></code> otherwise.)</p>
<p>The tasks-RCU API is quite compact, consisting only of
<a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu_tasks" title="call_rcu_tasks"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu_tasks()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_tasks" title="synchronize_rcu_tasks"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_tasks()</span></code></a>, and
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier_tasks" title="rcu_barrier_tasks"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier_tasks()</span></code></a>. In <code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=n</span></code> kernels, trampolines
cannot be preempted, so these APIs map to <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a>, and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a>, respectively. In
<code class="docutils literal notranslate"><span class="pre">CONFIG_PREEMPTION=y</span></code> kernels, trampolines can be preempted, and these
three APIs are therefore implemented by separate functions that check
for voluntary context switches.</p>
</section>
<section id="tasks-rude-rcu">
<h3>Tasks Rude RCU<a class="headerlink" href="#tasks-rude-rcu" title="Link to this heading">¶</a></h3>
<p>Some forms of tracing need to wait for all preemption-disabled regions
of code running on any online CPU, including those executed when RCU is
not watching.  This means that <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu" title="synchronize_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu()</span></code></a> is insufficient, and
Tasks Rude RCU must be used instead.  This flavor of RCU does its work by
forcing a workqueue to be scheduled on each online CPU, hence the “Rude”
moniker.  And this operation is considered to be quite rude by real-time
workloads that don’t want their <code class="docutils literal notranslate"><span class="pre">nohz_full</span></code> CPUs receiving IPIs and
by battery-powered systems that don’t want their idle CPUs to be awakened.</p>
<p>Once kernel entry/exit and deep-idle functions have been properly tagged
<code class="docutils literal notranslate"><span class="pre">noinstr</span></code>, Tasks RCU can start paying attention to idle tasks (except
those that are idle from RCU’s perspective) and then Tasks Rude RCU can
be removed from the kernel.</p>
<p>The tasks-rude-RCU API is also reader-marking-free and thus quite compact,
consisting solely of <a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_tasks_rude" title="synchronize_rcu_tasks_rude"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_tasks_rude()</span></code></a>.</p>
</section>
<section id="tasks-trace-rcu">
<h3>Tasks Trace RCU<a class="headerlink" href="#tasks-trace-rcu" title="Link to this heading">¶</a></h3>
<p>Some forms of tracing need to sleep in readers, but cannot tolerate
SRCU’s read-side overhead, which includes a full memory barrier in both
<a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_lock" title="srcu_read_lock"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_lock()</span></code></a> and <a class="reference internal" href="../../../core-api/kernel-api.html#c.srcu_read_unlock" title="srcu_read_unlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">srcu_read_unlock()</span></code></a>.  This need is handled by a
Tasks Trace RCU that uses scheduler locking and IPIs to synchronize with
readers.  Real-time systems that cannot tolerate IPIs may build their
kernels with <code class="docutils literal notranslate"><span class="pre">CONFIG_TASKS_TRACE_RCU_READ_MB=y</span></code>, which avoids the IPIs at
the expense of adding full memory barriers to the read-side primitives.</p>
<p>The tasks-trace-RCU API is also reasonably compact,
consisting of <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_lock_trace" title="rcu_read_lock_trace"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_lock_trace()</span></code></a>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_read_unlock_trace" title="rcu_read_unlock_trace"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_read_unlock_trace()</span></code></a>,
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rcu_read_lock_trace_held()</span></code>, <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu_tasks_trace" title="call_rcu_tasks_trace"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu_tasks_trace()</span></code></a>,
<a class="reference internal" href="../../../core-api/kernel-api.html#c.synchronize_rcu_tasks_trace" title="synchronize_rcu_tasks_trace"><code class="xref c c-func docutils literal notranslate"><span class="pre">synchronize_rcu_tasks_trace()</span></code></a>, and <a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier_tasks_trace" title="rcu_barrier_tasks_trace"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier_tasks_trace()</span></code></a>.</p>
</section>
</section>
<section id="possible-future-changes">
<h2>Possible Future Changes<a class="headerlink" href="#possible-future-changes" title="Link to this heading">¶</a></h2>
<p>One of the tricks that RCU uses to attain update-side scalability is to
increase grace-period latency with increasing numbers of CPUs. If this
becomes a serious problem, it will be necessary to rework the
grace-period state machine so as to avoid the need for the additional
latency.</p>
<p>RCU disables CPU hotplug in a few places, perhaps most notably in the
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> operations. If there is a strong reason to use
<a class="reference internal" href="../../../core-api/kernel-api.html#c.rcu_barrier" title="rcu_barrier"><code class="xref c c-func docutils literal notranslate"><span class="pre">rcu_barrier()</span></code></a> in CPU-hotplug notifiers, it will be necessary to
avoid disabling CPU hotplug. This would introduce some complexity, so
there had better be a <em>very</em> good reason.</p>
<p>The tradeoff between grace-period latency on the one hand and
interruptions of other CPUs on the other hand may need to be
re-examined. The desire is of course for zero grace-period latency as
well as zero interprocessor interrupts undertaken during an expedited
grace period operation. While this ideal is unlikely to be achievable,
it is quite possible that further improvements can be made.</p>
<p>The multiprocessor implementations of RCU use a combining tree that
groups CPUs so as to reduce lock contention and increase cache locality.
However, this combining tree does not spread its memory across NUMA
nodes nor does it align the CPU groups with hardware features such as
sockets or cores. Such spreading and alignment is currently believed to
be unnecessary because the hotpath read-side primitives do not access
the combining tree, nor does <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> in the common case. If you
believe that your architecture needs such spreading and alignment, then
your architecture should also benefit from the
<code class="docutils literal notranslate"><span class="pre">rcutree.rcu_fanout_leaf</span></code> boot parameter, which can be set to the
number of CPUs in a socket, NUMA node, or whatever. If the number of
CPUs is too large, use a fraction of the number of CPUs. If the number
of CPUs is a large prime number, well, that certainly is an
“interesting” architectural choice! More flexible arrangements might be
considered, but only if <code class="docutils literal notranslate"><span class="pre">rcutree.rcu_fanout_leaf</span></code> has proven
inadequate, and only if the inadequacy has been demonstrated by a
carefully run and realistic system-level workload.</p>
<p>Please note that arrangements that require RCU to remap CPU numbers will
require extremely good demonstration of need and full exploration of
alternatives.</p>
<p>RCU’s various kthreads are reasonably recent additions. It is quite
likely that adjustments will be required to more gracefully handle
extreme loads. It might also be necessary to be able to relate CPU
utilization by RCU’s kthreads and softirq handlers to the code that
instigated this CPU utilization. For example, RCU callback overhead
might be charged back to the originating <a class="reference internal" href="../../../core-api/kernel-api.html#c.call_rcu" title="call_rcu"><code class="xref c c-func docutils literal notranslate"><span class="pre">call_rcu()</span></code></a> instance, though
probably not in production kernels.</p>
<p>Additional work may be required to provide reasonable forward-progress
guarantees under heavy load for grace periods and for callback
invocation.</p>
</section>
<section id="summary">
<h2>Summary<a class="headerlink" href="#summary" title="Link to this heading">¶</a></h2>
<p>This document has presented more than two decade’s worth of RCU
requirements. Given that the requirements keep changing, this will not
be the last word on this subject, but at least it serves to get an
important subset of the requirements set forth.</p>
</section>
<section id="acknowledgments">
<h2>Acknowledgments<a class="headerlink" href="#acknowledgments" title="Link to this heading">¶</a></h2>
<p>I am grateful to Steven Rostedt, Lai Jiangshan, Ingo Molnar, Oleg
Nesterov, Borislav Petkov, Peter Zijlstra, Boqun Feng, and Andy
Lutomirski for their help in rendering this article human readable, and
to Michelle Rankin for her support of this effort. Other contributions
are acknowledged in the Linux kernel’s git archive.</p>
</section>
</section>


          </div>
          
        </div>
      </div>
    <div class="clearer"></div>
  </div>
    <div class="footer">
      &#169;The kernel development community.
      
      |
      Powered by <a href="https://www.sphinx-doc.org/">Sphinx 8.1.3</a>
      &amp; <a href="https://alabaster.readthedocs.io">Alabaster 0.7.16</a>
      
      |
      <a href="../../../_sources/RCU/Design/Requirements/Requirements.rst.txt"
          rel="nofollow">Page source</a>
    </div>

    

    
  </body>
</html>

Filemanager

Name Type Size Permission Actions
Requirements.html File 242.6 KB 0644
Filemanager