Quellcodebibliothek Statistik Leitseite products/sources/formale Sprachen/C/Linux/Documentation/RCU/Design/Requirements/   (Open Source Betriebssystem Version 6.17.9©)  Datei vom 24.10.2025 mit Größe 137 kB image not shown  

Quelle  Requirements.rst   Sprache: unbekannt

 
=================================
A Tour Through RCU's Requirements
=================================

Copyright IBM Corporation, 2015

Author: Paul E. McKenney

The initial version of this document appeared in the
`LWN <https://lwn.net/>`_ on those articles:
`part 1 <https://lwn.net/Articles/652156/>`_,
`part 2 <https://lwn.net/Articles/652677/>`_, and
`part 3 <https://lwn.net/Articles/653326/>`_.

Introduction
------------

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.

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.

All that aside, here are the categories of currently known RCU
requirements:

#. `Fundamental Requirements`_
#. `Fundamental Non-Requirements`_
#. `Parallelism Facts of Life`_
#. `Quality-of-Implementation Requirements`_
#. `Linux Kernel Complications`_
#. `Software-Engineering Requirements`_
#. `Other RCU Flavors`_
#. `Possible Future Changes`_

This is followed by a summary_, however, the answers to
each quick quiz immediately follows the quiz. Select the big white space
with your mouse to see the answer.

Fundamental Requirements
------------------------

RCU's fundamental requirements are the closest thing RCU has to hard
mathematical requirements. These are:

#. `Grace-Period Guarantee`_
#. `Publish/Subscribe Guarantee`_
#. `Memory-Barrier Guarantees`_
#. `RCU Primitives Guaranteed to Execute Unconditionally`_
#. `Guaranteed Read-to-Write Upgrade`_

Grace-Period Guarantee
~~~~~~~~~~~~~~~~~~~~~~

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.

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 rcu_read_lock() and ends
with the marker rcu_read_unlock(). These markers may be nested, and
RCU treats a nested set as one big RCU read-side critical section.
Production-quality implementations of rcu_read_lock() and
rcu_read_unlock() are extremely lightweight, and in fact have
exactly zero overhead in Linux kernels built for production use with
``CONFIG_PREEMPTION=n``.

This guarantee allows ordering to be enforced with extremely low
overhead to readers, for example:

   ::

       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 }

Because the synchronize_rcu() on line 14 waits for all pre-existing
readers, any instance of thread0() that loads a value of zero from
``x`` must complete before thread1() stores to ``y``, so that
instance must also load a value of zero from ``y``. Similarly, any
instance of thread0() that loads a value of one from ``y`` must have
started after the synchronize_rcu() started, and must therefore also
load a value of one from ``x``. Therefore, the outcome:

   ::

      (r1 == 0 && r2 == 1)

cannot happen.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Wait a minute! You said that updaters can make useful forward         |
| progress concurrently with readers, but pre-existing readers will     |
| block synchronize_rcu()!!!                                            |
| Just who are you trying to fool???                                    |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| First, if updaters do not wish to be blocked by readers, they can use |
| call_rcu() or kfree_rcu(), which will be discussed later.             |
| Second, even when using synchronize_rcu(), the other update-side      |
| code does run concurrently with readers, whether pre-existing or not. |
+-----------------------------------------------------------------------+

This scenario resembles one of the first uses of RCU in
`DYNIX/ptx <https://en.wikipedia.org/wiki/DYNIX>`__, which managed a
distributed lock manager's transition into a state suitable for handling
recovery from node failure, more or less as follows:

   ::

       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 }

The RCU read-side critical section in do_something_dlm() works with
the synchronize_rcu() in start_recovery() to guarantee that
do_something() never runs concurrently with recovery(), but with
little or no synchronization overhead in do_something_dlm().

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Why is the synchronize_rcu() on line 28 needed?                       |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| Without that extra grace period, memory reordering could result in    |
| do_something_dlm() executing do_something() concurrently with         |
| the last bits of recovery().                                          |
+-----------------------------------------------------------------------+

In order to avoid fatal problems such as deadlocks, an RCU read-side
critical section must not contain calls to synchronize_rcu().
Similarly, an RCU read-side critical section must not contain anything
that waits, directly or indirectly, on completion of an invocation of
synchronize_rcu().

Although RCU's grace-period guarantee is useful in and of itself, with
`quite a few use cases <https://lwn.net/Articles/573497/>`__, 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 add_gp_buggy() below. We will look at the
reader's code later, but in the meantime, just think of the reader as
locklessly picking up the ``gp`` pointer, and, if the value loaded is
non-\ ``NULL``, locklessly accessing the ``->a`` and ``->b`` fields.

   ::

       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(&gp_lock);
       7   if (rcu_access_pointer(gp)) {
       8     spin_unlock(&gp_lock);
       9     return false;
      10   }
      11   p->a = a;
      12   p->b = a;
      13   gp = p; /* ORDERING BUG */
      14   spin_unlock(&gp_lock);
      15   return true;
      16 }

The problem is that both the compiler and weakly ordered CPUs are within
their rights to reorder this code as follows:

   ::

       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(&gp_lock);
       7   if (rcu_access_pointer(gp)) {
       8     spin_unlock(&gp_lock);
       9     return false;
      10   }
      11   gp = p; /* ORDERING BUG */
      12   p->a = a;
      13   p->b = a;
      14   spin_unlock(&gp_lock);
      15   return true;
      16 }

If an RCU reader fetches ``gp`` just after ``add_gp_buggy_optimized``
executes line 11, it will see garbage in the ``->a`` and ``->b`` 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.

Publish/Subscribe Guarantee
~~~~~~~~~~~~~~~~~~~~~~~~~~~

RCU's publish-subscribe guarantee allows data to be inserted into a
linked data structure without disrupting RCU readers. The updater uses
rcu_assign_pointer() to insert the new data, and readers use
rcu_dereference() to access data, whether new or old. The following
shows an example of insertion:

   ::

       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(&gp_lock);
       7   if (rcu_access_pointer(gp)) {
       8     spin_unlock(&gp_lock);
       9     return false;
      10   }
      11   p->a = a;
      12   p->b = a;
      13   rcu_assign_pointer(gp, p);
      14   spin_unlock(&gp_lock);
      15   return true;
      16 }

The rcu_assign_pointer() 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 ``memory_order_release`` store operation. It also prevents any
number of “interesting” compiler optimizations, for example, the use of
``gp`` as a scratch location immediately preceding the assignment.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| But rcu_assign_pointer() does nothing to prevent the two              |
| assignments to ``p->a`` and ``p->b`` from being reordered. Can't that |
| also cause problems?                                                  |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| No, it cannot. The readers cannot see either of these two fields      |
| until the assignment to ``gp``, by which time both fields are fully   |
| initialized. So reordering the assignments to ``p->a`` and ``p->b``   |
| cannot possibly cause any problems.                                   |
+-----------------------------------------------------------------------+

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
do_something_gp_buggy() below:

   ::

       1 bool do_something_gp_buggy(void)
       2 {
       3   rcu_read_lock();
       4   p = gp;  /* OPTIMIZATIONS GALORE!!! */
       5   if (p) {
       6     do_something(p->a, p->b);
       7     rcu_read_unlock();
       8     return true;
       9   }
      10   rcu_read_unlock();
      11   return false;
      12 }

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
``gp`` rather than keeping a separate copy in ``p`` as follows:

   ::

       1 bool do_something_gp_buggy_optimized(void)
       2 {
       3   rcu_read_lock();
       4   if (gp) { /* OPTIMIZATIONS GALORE!!! */
       5     do_something(gp->a, gp->b);
       6     rcu_read_unlock();
       7     return true;
       8   }
       9   rcu_read_unlock();
      10   return false;
      11 }

If this function ran concurrently with a series of updates that replaced
the current structure with a new one, the fetches of ``gp->a`` and
``gp->b`` might well come from two different structures, which could
cause serious confusion. To prevent this (and much else besides),
do_something_gp() uses rcu_dereference() to fetch from ``gp``:

   ::

       1 bool do_something_gp(void)
       2 {
       3   rcu_read_lock();
       4   p = rcu_dereference(gp);
       5   if (p) {
       6     do_something(p->a, p->b);
       7     rcu_read_unlock();
       8     return true;
       9   }
      10   rcu_read_unlock();
      11   return false;
      12 }

The rcu_dereference() uses volatile casts and (for DEC Alpha) memory
barriers in the Linux kernel. Should a |high-quality implementation of
C11 memory_order_consume [PDF]|_
ever appear, then rcu_dereference() could be implemented as a
``memory_order_consume`` load. Regardless of the exact implementation, a
pointer fetched by rcu_dereference() may not be used outside of the
outermost RCU read-side critical section containing that
rcu_dereference(), unless protection of the corresponding data
element has been passed from RCU to some other synchronization
mechanism, most commonly locking or reference counting
(see ../../rcuref.rst).

.. |high-quality implementation of C11 memory_order_consume [PDF]| replace:: high-quality implementation of C11 ``memory_order_consume`` [PDF]
.. _high-quality implementation of C11 memory_order_consume [PDF]: http://www.rdrop.com/users/paulmck/RCU/consume.2015.07.13a.pdf

In short, updaters use rcu_assign_pointer() and readers use
rcu_dereference(), and these two RCU API elements work together to
ensure that readers have a consistent view of newly added data elements.

Of course, it is also necessary to remove elements from RCU-protected
data structures, for example, using the following process:

#. Remove the data element from the enclosing structure.
#. 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).
#. 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 kfree().

This process is implemented by remove_gp_synchronous():

   ::

       1 bool remove_gp_synchronous(void)
       2 {
       3   struct foo *p;
       4
       5   spin_lock(&gp_lock);
       6   p = rcu_access_pointer(gp);
       7   if (!p) {
       8     spin_unlock(&gp_lock);
       9     return false;
      10   }
      11   rcu_assign_pointer(gp, NULL);
      12   spin_unlock(&gp_lock);
      13   synchronize_rcu();
      14   kfree(p);
      15   return true;
      16 }

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 do_something_gp() before the data
element referenced by ``p`` is freed. The rcu_access_pointer() on
line 6 is similar to rcu_dereference(), except that:

#. The value returned by rcu_access_pointer() cannot be
   dereferenced. If you want to access the value pointed to as well as
   the pointer itself, use rcu_dereference() instead of
   rcu_access_pointer().
#. The call to rcu_access_pointer() need not be protected. In
   contrast, rcu_dereference() 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.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Without the rcu_dereference() or the rcu_access_pointer(),            |
| what destructive optimizations might the compiler make use of?        |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| Let's start with what happens to do_something_gp() if it fails to     |
| use rcu_dereference(). It could reuse a value formerly fetched        |
| from this same pointer. It could also fetch the pointer from ``gp``   |
| in a byte-at-a-time manner, resulting in *load tearing*, 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 remove_gp_synchronous(), as long as all modifications to          |
| ``gp`` are carried out while holding ``gp_lock``, the above           |
| optimizations are harmless. However, ``sparse`` will complain if you  |
| define ``gp`` with ``__rcu`` and then access it without using either  |
| rcu_access_pointer() or rcu_dereference().                            |
+-----------------------------------------------------------------------+

In short, RCU's publish-subscribe guarantee is provided by the
combination of rcu_assign_pointer() and rcu_dereference(). 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.

This guarantee was only partially premeditated. DYNIX/ptx used an
explicit memory barrier for publication, but had nothing resembling
rcu_dereference() for subscription, nor did it have anything
resembling the dependency-ordering barrier that was later subsumed
into rcu_dereference() and later still into READ_ONCE(). 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 *two* 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
rcu_dereference()!

Memory-Barrier Guarantees
~~~~~~~~~~~~~~~~~~~~~~~~~

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:

#. Each CPU that has an RCU read-side critical section that begins
   before synchronize_rcu() starts is guaranteed to execute a full
   memory barrier between the time that the RCU read-side critical
   section ends and the time that synchronize_rcu() returns. Without
   this guarantee, a pre-existing RCU read-side critical section might
   hold a reference to the newly removed ``struct foo`` after the
   kfree() on line 14 of remove_gp_synchronous().
#. Each CPU that has an RCU read-side critical section that ends after
   synchronize_rcu() returns is guaranteed to execute a full memory
   barrier between the time that synchronize_rcu() 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
   kfree() on line 14 of remove_gp_synchronous() might later run
   do_something_gp() and find the newly deleted ``struct foo``.
#. If the task invoking synchronize_rcu() remains on a given CPU,
   then that CPU is guaranteed to execute a full memory barrier sometime
   during the execution of synchronize_rcu(). This guarantee ensures
   that the kfree() on line 14 of remove_gp_synchronous() really
   does execute after the removal on line 11.
#. If the task invoking synchronize_rcu() 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 synchronize_rcu(). This guarantee also ensures that
   the kfree() on line 14 of remove_gp_synchronous() really does
   execute after the removal on line 11, but also in the case where the
   thread executing the synchronize_rcu() migrates in the meantime.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| 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 synchronize_rcu()?                                  |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| If RCU cannot tell whether or not a given RCU read-side critical      |
| section starts before a given instance of synchronize_rcu(), then     |
| it must assume that the RCU read-side critical section started first. |
| In other words, a given instance of synchronize_rcu() can avoid       |
| waiting on a given RCU read-side critical section only if it can      |
| prove that synchronize_rcu() started first.                           |
| A related question is “When rcu_read_lock() 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 rcu_read_lock()          |
| 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.                             |
|                                                                       |
| As of late 2016, mathematical models of RCU take this viewpoint, for  |
| example, see slides 62 and 63 of the `2016 LinuxCon                   |
| EU <http://www2.rdrop.com/users/paulmck/scalability/paper/LinuxMM.201 |
| 6.10.04c.LCE.pdf>`__                                                  |
| presentation.                                                         |
+-----------------------------------------------------------------------+

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| The first and second guarantees require unbelievably strict ordering! |
| Are all these memory barriers *really* required?                      |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| Yes, they really are required. To see why the first guarantee is      |
| required, consider the following sequence of events:                  |
|                                                                       |
| #. CPU 1: rcu_read_lock()                                             |
| #. CPU 1: ``q = rcu_dereference(gp); /* Very likely to return p. */`` |
| #. CPU 0: ``list_del_rcu(p);``                                        |
| #. CPU 0: synchronize_rcu() starts.                                   |
| #. CPU 1: ``do_something_with(q->a);``                                |
|    ``/* No smp_mb(), so might happen after kfree(). */``              |
| #. CPU 1: rcu_read_unlock()                                           |
| #. CPU 0: synchronize_rcu() returns.                                  |
| #. CPU 0: ``kfree(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.                                                               |
|                                                                       |
| The sequence of events demonstrating the necessity of the second rule |
| is roughly similar:                                                   |
|                                                                       |
| #. CPU 0: ``list_del_rcu(p);``                                        |
| #. CPU 0: synchronize_rcu() starts.                                   |
| #. CPU 1: rcu_read_lock()                                             |
| #. CPU 1: ``q = rcu_dereference(gp);``                                |
|    ``/* Might return p if no memory barrier. */``                     |
| #. CPU 0: synchronize_rcu() returns.                                  |
| #. CPU 0: ``kfree(p);``                                               |
| #. CPU 1: ``do_something_with(q->a); /* Boom!!! */``                  |
| #. CPU 1: rcu_read_unlock()                                           |
|                                                                       |
| 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.                            |
|                                                                       |
| 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!                                                |
+-----------------------------------------------------------------------+

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| You claim that rcu_read_lock() and rcu_read_unlock() 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?                     |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| In cases where rcu_read_lock() and rcu_read_unlock() generate         |
| absolutely no code, RCU infers quiescent states only at special       |
| locations, for example, within the scheduler. Because calls to        |
| schedule() had better prevent calling-code accesses to shared         |
| variables from being rearranged across the call to schedule(), 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!      |
+-----------------------------------------------------------------------+

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 *enforce* this fundamental
requirement. Of course, different implementations enforce this
requirement in different ways, but enforce it they must.

RCU Primitives Guaranteed to Execute Unconditionally
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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.

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.

Guaranteed Read-to-Write Upgrade
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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 synchronize_rcu(), however, this inconvenience can
be avoided through use of the call_rcu() and kfree_rcu() API
members described later in this document.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| But how does the upgrade-to-write operation exclude other readers?    |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| It doesn't, just like normal RCU updates, which also do not exclude   |
| RCU readers.                                                          |
+-----------------------------------------------------------------------+

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.

Fundamental Non-Requirements
----------------------------

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.

#. `Readers Impose Minimal Ordering`_
#. `Readers Do Not Exclude Updaters`_
#. `Updaters Only Wait For Old Readers`_
#. `Grace Periods Don't Partition Read-Side Critical Sections`_
#. `Read-Side Critical Sections Don't Partition Grace Periods`_

Readers Impose Minimal Ordering
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Reader-side markers such as rcu_read_lock() and
rcu_read_unlock() provide absolutely no ordering guarantees except
through their interaction with the grace-period APIs such as
synchronize_rcu(). To see this, consider the following pair of
threads:

   ::

       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 }

After thread0() and thread1() execute concurrently, it is quite
possible to have

   ::

      (r1 == 1 && r2 == 0)

(that is, ``y`` appears to have been assigned before ``x``), which would
not be possible if rcu_read_lock() and rcu_read_unlock() 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.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Can't the compiler also reorder this code?                            |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| No, the volatile casts in READ_ONCE() and WRITE_ONCE()                |
| prevent the compiler from reordering in this particular case.         |
+-----------------------------------------------------------------------+

Readers Do Not Exclude Updaters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Neither rcu_read_lock() nor rcu_read_unlock() exclude updates.
All they do is to prevent grace periods from ending. The following
example illustrates this:

   ::

       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(&my_lock);
      16   WRITE_ONCE(x, 1);
      17   WRITE_ONCE(y, 1);
      18   spin_unlock(&my_lock);
      19 }

If the thread0() function's rcu_read_lock() excluded the
thread1() function's update, the WARN_ON() could never fire. But
the fact is that rcu_read_lock() does not exclude much of anything
aside from subsequent grace periods, of which thread1() has none, so
the WARN_ON() can and does fire.

Updaters Only Wait For Old Readers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It might be tempting to assume that after synchronize_rcu()
completes, there are no readers executing. This temptation must be
avoided because new readers can start immediately after
synchronize_rcu() starts, and synchronize_rcu() is under no
obligation to wait for these new readers.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Suppose that synchronize_rcu() did wait until *all* 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?     |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| For no time at all. Even if synchronize_rcu() were to wait until      |
| all readers had completed, a new reader might start immediately after |
| synchronize_rcu() completed. Therefore, the code following            |
| synchronize_rcu() can *never* rely on there being no readers.         |
+-----------------------------------------------------------------------+

Grace Periods Don't Partition Read-Side Critical Sections
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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 ``x``, ``y``, and ``z``
are initially all zero:

   ::

       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 }

It turns out that the outcome:

   ::

      (r1 == 1 && r2 == 0 && r3 == 1)

is entirely possible. The following figure show how this can happen,
with each circled ``QS`` indicating the point at which RCU recorded a
*quiescent state* 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:

.. kernel-figure:: GPpartitionReaders1.svg

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:

   ::

       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 }

Here, if ``(r1 == 1)``, then thread0()'s write to ``b`` must happen
before the end of thread1()'s grace period. If in addition
``(r4 == 1)``, then thread3()'s read from ``b`` must happen after
the beginning of thread2()'s grace period. If it is also the case
that ``(r2 == 1)``, then the end of thread1()'s grace period must
precede the beginning of thread2()'s grace period. This mean that
the two RCU read-side critical sections cannot overlap, guaranteeing
that ``(r3 == 1)``. As a result, the outcome:

   ::

      (r1 == 1 && r2 == 1 && r3 == 0 && r4 == 1)

cannot happen.

This non-requirement was also non-premeditated, but became apparent when
studying RCU's interaction with memory ordering.

Read-Side Critical Sections Don't Partition Grace Periods
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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:

   ::

       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 }

In this case, the outcome:

   ::

      (r1 == 1 && r2 == 1 && r3 == 1 && r4 == 0 && r5 == 1)

is entirely possible, as illustrated below:

.. kernel-figure:: ReadersPartitionGP1.svg

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.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| 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?    |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| 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.                                     |
+-----------------------------------------------------------------------+

Parallelism Facts of Life
-------------------------

These parallelism facts of life are by no means specific to RCU, but the
RCU implementation must abide by them. They therefore bear repeating:

#. 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.
#. 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.
#. 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.
#. 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.
#. 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` 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.
#. 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.

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.

Quality-of-Implementation Requirements
--------------------------------------

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:

#. `Specialization`_
#. `Performance and Scalability`_
#. `Forward Progress`_
#. `Composability`_
#. `Corner Cases`_

These classes is covered in the following sections.

Specialization
~~~~~~~~~~~~~~

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:

#. Read-mostly data, where stale and inconsistent data is not a problem:
   RCU works great!
#. Read-mostly data, where data must be consistent: RCU works well.
#. Read-write data, where data must be consistent: RCU *might* work OK.
   Or not.
#. 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:

   a. Existence guarantees for update-friendly mechanisms.
   b. Wait-free read-side primitives for real-time use.

This focus on read-mostly situations means that RCU must interoperate
with other synchronization primitives. For example, the add_gp() and
remove_gp_synchronous() 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.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| What about sleeping locks?                                            |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| 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 `(SRCU) <Sleepable RCU_>`__ 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 *is* legal for a normal RCU read-side critical section   |
| to conditionally acquire a sleeping locks (as in                      |
| mutex_trylock()), but only as long as it does not loop                |
| indefinitely attempting to conditionally acquire that sleeping locks. |
| The key point is that things like mutex_trylock() either return       |
| with the mutex held, or return an error indication if the mutex was   |
| not immediately available. Either way, mutex_trylock() returns        |
| immediately without sleeping.                                         |
+-----------------------------------------------------------------------+

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.

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.

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.

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.

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.

Performance and Scalability
~~~~~~~~~~~~~~~~~~~~~~~~~~~

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.

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
`bloatwatch <http://elinux.org/Linux_Tiny-FAQ>`__ efforts, memory
footprint is critically important on single-CPU systems with
non-preemptible (``CONFIG_PREEMPTION=n``) kernels, and thus `tiny
RCU <https://lore.kernel.org/r/20090113221724.GA15307@linux.vnet.ibm.com>`__
was born. Josh Triplett has since taken over the small-memory banner
with his `Linux kernel tinification <https://tiny.wiki.kernel.org/>`__
project, which resulted in `SRCU <Sleepable RCU_>`__ becoming optional
for those kernels not needing it.

The remaining performance requirements are, for the most part,
unsurprising. For example, in keeping with RCU's read-side
specialization, rcu_dereference() should have negligible overhead
(for example, suppression of a few minor compiler optimizations).
Similarly, in non-preemptible environments, rcu_read_lock() and
rcu_read_unlock() should have exactly zero overhead.

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), rcu_read_lock() and
rcu_read_unlock() 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, rcu_read_unlock() 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.

The synchronize_rcu() 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
synchronize_rcu() 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 `1,000 separate
invocations <https://www.usenix.org/conference/2004-usenix-annual-technical-conference/making-rcu-safe-deep-sub-millisecond-response>`__
of synchronize_rcu(), 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.

In some cases, the multi-millisecond synchronize_rcu() latencies are
unacceptable. In these cases, synchronize_rcu_expedited() 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 synchronize_rcu_expedited() 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 synchronize_rcu_expedited() invocations on
4096 CPUs should at least make reasonable forward progress. In return
for its shorter latencies, synchronize_rcu_expedited() 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.

There are a number of situations where even
synchronize_rcu_expedited()'s reduced grace-period latency is
unacceptable. In these situations, the asynchronous call_rcu() can
be used in place of synchronize_rcu() as follows:

   ::

       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(&gp_lock);
      19   p = rcu_access_pointer(gp);
      20   if (!p) {
      21     spin_unlock(&gp_lock);
      22     return false;
      23   }
      24   rcu_assign_pointer(gp, NULL);
      25   call_rcu(&p->rh, remove_gp_cb);
      26   spin_unlock(&gp_lock);
      27   return true;
      28 }

A definition of ``struct foo`` is finally needed, and appears on
lines 1-5. The function remove_gp_cb() is passed to call_rcu()
on line 25, and will be invoked after the end of a subsequent grace
period. This gets the same effect as remove_gp_synchronous(), but
without forcing the updater to wait for a grace period to elapse. The
call_rcu() function may be used in a number of situations where
neither synchronize_rcu() nor synchronize_rcu_expedited() would
be legal, including within preempt-disable code, local_bh_disable()
code, interrupt-disable code, and interrupt handlers. However, even
call_rcu() is illegal within NMI handlers and from idle and offline
CPUs. The callback function (remove_gp_cb() 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 local_bh_disable(). 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.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Why does line 19 use rcu_access_pointer()? After all,                 |
| call_rcu() on line 25 stores into the structure, which would          |
| interact badly with concurrent insertions. Doesn't this mean that     |
| rcu_dereference() is required?                                        |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| Presumably the ``->gp_lock`` acquired on line 18 excludes any         |
| changes, including any insertions that rcu_dereference() would        |
| protect against. Therefore, any insertions will be delayed until      |
| after ``->gp_lock`` is released on line 25, which in turn means that  |
| rcu_access_pointer() suffices.                                        |
+-----------------------------------------------------------------------+

However, all that remove_gp_cb() is doing is invoking kfree() on
the data element. This is a common idiom, and is supported by
kfree_rcu(), which allows “fire and forget” operation as shown
below:

   ::

       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(&gp_lock);
      12   p = rcu_dereference(gp);
      13   if (!p) {
      14     spin_unlock(&gp_lock);
      15     return false;
      16   }
      17   rcu_assign_pointer(gp, NULL);
      18   kfree_rcu(p, rh);
      19   spin_unlock(&gp_lock);
      20   return true;
      21 }

Note that remove_gp_faf() simply invokes kfree_rcu() and
proceeds, without any need to pay any further attention to the
subsequent grace period and kfree(). It is permissible to invoke
kfree_rcu() from the same environments as for call_rcu().
Interestingly enough, DYNIX/ptx had the equivalents of call_rcu()
and kfree_rcu(), but not synchronize_rcu(). This was due to the
fact that RCU was not heavily used within DYNIX/ptx, so the very few
places that needed something like synchronize_rcu() simply
open-coded it.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Earlier it was claimed that call_rcu() and kfree_rcu()                |
| 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?                                                               |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| 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 call_rcu() or kfree_rcu() can proceed         |
| to the next update as soon as it has invoked call_rcu() or            |
| kfree_rcu(), without having to wait for a subsequent grace            |
| period.                                                               |
+-----------------------------------------------------------------------+

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
get_state_synchronize_rcu() and cond_synchronize_rcu() functions
may be used for this purpose, as shown below:

   ::

       1 bool remove_gp_poll(void)
       2 {
       3   struct foo *p;
       4   unsigned long s;
       5
       6   spin_lock(&gp_lock);
       7   p = rcu_access_pointer(gp);
       8   if (!p) {
       9     spin_unlock(&gp_lock);
      10     return false;
      11   }
      12   rcu_assign_pointer(gp, NULL);
      13   spin_unlock(&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 }

On line 14, get_state_synchronize_rcu() 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 ``get_state_synchronize_rcu`` and
cond_synchronize_rcu() has appeared quite recently, so it is too
early to tell whether they will stand the test of time.

RCU thus provides a range of tools to allow updaters to strike the
required tradeoff between latency, flexibility and CPU overhead.

Forward Progress
~~~~~~~~~~~~~~~~

--> --------------------

--> maximum size reached

--> --------------------

[ Dauer der Verarbeitung: 0.8 Sekunden  (vorverarbeitet)  ]