Back to home page

OSCL-LXR

 
 

    


0001 .. _rcu_barrier:
0002 
0003 RCU and Unloadable Modules
0004 ==========================
0005 
0006 [Originally published in LWN Jan. 14, 2007: http://lwn.net/Articles/217484/]
0007 
0008 RCU (read-copy update) is a synchronization mechanism that can be thought
0009 of as a replacement for read-writer locking (among other things), but with
0010 very low-overhead readers that are immune to deadlock, priority inversion,
0011 and unbounded latency. RCU read-side critical sections are delimited
0012 by rcu_read_lock() and rcu_read_unlock(), which, in non-CONFIG_PREEMPTION
0013 kernels, generate no code whatsoever.
0014 
0015 This means that RCU writers are unaware of the presence of concurrent
0016 readers, so that RCU updates to shared data must be undertaken quite
0017 carefully, leaving an old version of the data structure in place until all
0018 pre-existing readers have finished. These old versions are needed because
0019 such readers might hold a reference to them. RCU updates can therefore be
0020 rather expensive, and RCU is thus best suited for read-mostly situations.
0021 
0022 How can an RCU writer possibly determine when all readers are finished,
0023 given that readers might well leave absolutely no trace of their
0024 presence? There is a synchronize_rcu() primitive that blocks until all
0025 pre-existing readers have completed. An updater wishing to delete an
0026 element p from a linked list might do the following, while holding an
0027 appropriate lock, of course::
0028 
0029         list_del_rcu(p);
0030         synchronize_rcu();
0031         kfree(p);
0032 
0033 But the above code cannot be used in IRQ context -- the call_rcu()
0034 primitive must be used instead. This primitive takes a pointer to an
0035 rcu_head struct placed within the RCU-protected data structure and
0036 another pointer to a function that may be invoked later to free that
0037 structure. Code to delete an element p from the linked list from IRQ
0038 context might then be as follows::
0039 
0040         list_del_rcu(p);
0041         call_rcu(&p->rcu, p_callback);
0042 
0043 Since call_rcu() never blocks, this code can safely be used from within
0044 IRQ context. The function p_callback() might be defined as follows::
0045 
0046         static void p_callback(struct rcu_head *rp)
0047         {
0048                 struct pstruct *p = container_of(rp, struct pstruct, rcu);
0049 
0050                 kfree(p);
0051         }
0052 
0053 
0054 Unloading Modules That Use call_rcu()
0055 -------------------------------------
0056 
0057 But what if p_callback is defined in an unloadable module?
0058 
0059 If we unload the module while some RCU callbacks are pending,
0060 the CPUs executing these callbacks are going to be severely
0061 disappointed when they are later invoked, as fancifully depicted at
0062 http://lwn.net/images/ns/kernel/rcu-drop.jpg.
0063 
0064 We could try placing a synchronize_rcu() in the module-exit code path,
0065 but this is not sufficient. Although synchronize_rcu() does wait for a
0066 grace period to elapse, it does not wait for the callbacks to complete.
0067 
0068 One might be tempted to try several back-to-back synchronize_rcu()
0069 calls, but this is still not guaranteed to work. If there is a very
0070 heavy RCU-callback load, then some of the callbacks might be deferred
0071 in order to allow other processing to proceed. Such deferral is required
0072 in realtime kernels in order to avoid excessive scheduling latencies.
0073 
0074 
0075 rcu_barrier()
0076 -------------
0077 
0078 We instead need the rcu_barrier() primitive.  Rather than waiting for
0079 a grace period to elapse, rcu_barrier() waits for all outstanding RCU
0080 callbacks to complete.  Please note that rcu_barrier() does **not** imply
0081 synchronize_rcu(), in particular, if there are no RCU callbacks queued
0082 anywhere, rcu_barrier() is within its rights to return immediately,
0083 without waiting for a grace period to elapse.
0084 
0085 Pseudo-code using rcu_barrier() is as follows:
0086 
0087    1. Prevent any new RCU callbacks from being posted.
0088    2. Execute rcu_barrier().
0089    3. Allow the module to be unloaded.
0090 
0091 There is also an srcu_barrier() function for SRCU, and you of course
0092 must match the flavor of rcu_barrier() with that of call_rcu().  If your
0093 module uses multiple flavors of call_rcu(), then it must also use multiple
0094 flavors of rcu_barrier() when unloading that module.  For example, if
0095 it uses call_rcu(), call_srcu() on srcu_struct_1, and call_srcu() on
0096 srcu_struct_2, then the following three lines of code will be required
0097 when unloading::
0098 
0099  1 rcu_barrier();
0100  2 srcu_barrier(&srcu_struct_1);
0101  3 srcu_barrier(&srcu_struct_2);
0102 
0103 The rcutorture module makes use of rcu_barrier() in its exit function
0104 as follows::
0105 
0106  1  static void
0107  2  rcu_torture_cleanup(void)
0108  3  {
0109  4    int i;
0110  5
0111  6    fullstop = 1;
0112  7    if (shuffler_task != NULL) {
0113  8     VERBOSE_PRINTK_STRING("Stopping rcu_torture_shuffle task");
0114  9     kthread_stop(shuffler_task);
0115  10   }
0116  11   shuffler_task = NULL;
0117  12
0118  13   if (writer_task != NULL) {
0119  14     VERBOSE_PRINTK_STRING("Stopping rcu_torture_writer task");
0120  15     kthread_stop(writer_task);
0121  16   }
0122  17   writer_task = NULL;
0123  18
0124  19   if (reader_tasks != NULL) {
0125  20     for (i = 0; i < nrealreaders; i++) {
0126  21       if (reader_tasks[i] != NULL) {
0127  22         VERBOSE_PRINTK_STRING(
0128  23           "Stopping rcu_torture_reader task");
0129  24         kthread_stop(reader_tasks[i]);
0130  25       }
0131  26       reader_tasks[i] = NULL;
0132  27     }
0133  28     kfree(reader_tasks);
0134  29     reader_tasks = NULL;
0135  30   }
0136  31   rcu_torture_current = NULL;
0137  32
0138  33   if (fakewriter_tasks != NULL) {
0139  34     for (i = 0; i < nfakewriters; i++) {
0140  35       if (fakewriter_tasks[i] != NULL) {
0141  36         VERBOSE_PRINTK_STRING(
0142  37           "Stopping rcu_torture_fakewriter task");
0143  38         kthread_stop(fakewriter_tasks[i]);
0144  39       }
0145  40       fakewriter_tasks[i] = NULL;
0146  41     }
0147  42     kfree(fakewriter_tasks);
0148  43     fakewriter_tasks = NULL;
0149  44   }
0150  45
0151  46   if (stats_task != NULL) {
0152  47     VERBOSE_PRINTK_STRING("Stopping rcu_torture_stats task");
0153  48     kthread_stop(stats_task);
0154  49   }
0155  50   stats_task = NULL;
0156  51
0157  52   /* Wait for all RCU callbacks to fire. */
0158  53   rcu_barrier();
0159  54
0160  55   rcu_torture_stats_print(); /* -After- the stats thread is stopped! */
0161  56
0162  57   if (cur_ops->cleanup != NULL)
0163  58     cur_ops->cleanup();
0164  59   if (atomic_read(&n_rcu_torture_error))
0165  60     rcu_torture_print_module_parms("End of test: FAILURE");
0166  61   else
0167  62     rcu_torture_print_module_parms("End of test: SUCCESS");
0168  63 }
0169 
0170 Line 6 sets a global variable that prevents any RCU callbacks from
0171 re-posting themselves. This will not be necessary in most cases, since
0172 RCU callbacks rarely include calls to call_rcu(). However, the rcutorture
0173 module is an exception to this rule, and therefore needs to set this
0174 global variable.
0175 
0176 Lines 7-50 stop all the kernel tasks associated with the rcutorture
0177 module. Therefore, once execution reaches line 53, no more rcutorture
0178 RCU callbacks will be posted. The rcu_barrier() call on line 53 waits
0179 for any pre-existing callbacks to complete.
0180 
0181 Then lines 55-62 print status and do operation-specific cleanup, and
0182 then return, permitting the module-unload operation to be completed.
0183 
0184 .. _rcubarrier_quiz_1:
0185 
0186 Quick Quiz #1:
0187         Is there any other situation where rcu_barrier() might
0188         be required?
0189 
0190 :ref:`Answer to Quick Quiz #1 <answer_rcubarrier_quiz_1>`
0191 
0192 Your module might have additional complications. For example, if your
0193 module invokes call_rcu() from timers, you will need to first cancel all
0194 the timers, and only then invoke rcu_barrier() to wait for any remaining
0195 RCU callbacks to complete.
0196 
0197 Of course, if you module uses call_rcu(), you will need to invoke
0198 rcu_barrier() before unloading.  Similarly, if your module uses
0199 call_srcu(), you will need to invoke srcu_barrier() before unloading,
0200 and on the same srcu_struct structure.  If your module uses call_rcu()
0201 **and** call_srcu(), then you will need to invoke rcu_barrier() **and**
0202 srcu_barrier().
0203 
0204 
0205 Implementing rcu_barrier()
0206 --------------------------
0207 
0208 Dipankar Sarma's implementation of rcu_barrier() makes use of the fact
0209 that RCU callbacks are never reordered once queued on one of the per-CPU
0210 queues. His implementation queues an RCU callback on each of the per-CPU
0211 callback queues, and then waits until they have all started executing, at
0212 which point, all earlier RCU callbacks are guaranteed to have completed.
0213 
0214 The original code for rcu_barrier() was as follows::
0215 
0216  1  void rcu_barrier(void)
0217  2  {
0218  3    BUG_ON(in_interrupt());
0219  4    /* Take cpucontrol mutex to protect against CPU hotplug */
0220  5    mutex_lock(&rcu_barrier_mutex);
0221  6    init_completion(&rcu_barrier_completion);
0222  7    atomic_set(&rcu_barrier_cpu_count, 0);
0223  8    on_each_cpu(rcu_barrier_func, NULL, 0, 1);
0224  9    wait_for_completion(&rcu_barrier_completion);
0225  10   mutex_unlock(&rcu_barrier_mutex);
0226  11 }
0227 
0228 Line 3 verifies that the caller is in process context, and lines 5 and 10
0229 use rcu_barrier_mutex to ensure that only one rcu_barrier() is using the
0230 global completion and counters at a time, which are initialized on lines
0231 6 and 7. Line 8 causes each CPU to invoke rcu_barrier_func(), which is
0232 shown below. Note that the final "1" in on_each_cpu()'s argument list
0233 ensures that all the calls to rcu_barrier_func() will have completed
0234 before on_each_cpu() returns. Line 9 then waits for the completion.
0235 
0236 This code was rewritten in 2008 and several times thereafter, but this
0237 still gives the general idea.
0238 
0239 The rcu_barrier_func() runs on each CPU, where it invokes call_rcu()
0240 to post an RCU callback, as follows::
0241 
0242  1  static void rcu_barrier_func(void *notused)
0243  2  {
0244  3    int cpu = smp_processor_id();
0245  4    struct rcu_data *rdp = &per_cpu(rcu_data, cpu);
0246  5    struct rcu_head *head;
0247  6
0248  7    head = &rdp->barrier;
0249  8    atomic_inc(&rcu_barrier_cpu_count);
0250  9    call_rcu(head, rcu_barrier_callback);
0251  10 }
0252 
0253 Lines 3 and 4 locate RCU's internal per-CPU rcu_data structure,
0254 which contains the struct rcu_head that needed for the later call to
0255 call_rcu(). Line 7 picks up a pointer to this struct rcu_head, and line
0256 8 increments a global counter. This counter will later be decremented
0257 by the callback. Line 9 then registers the rcu_barrier_callback() on
0258 the current CPU's queue.
0259 
0260 The rcu_barrier_callback() function simply atomically decrements the
0261 rcu_barrier_cpu_count variable and finalizes the completion when it
0262 reaches zero, as follows::
0263 
0264  1 static void rcu_barrier_callback(struct rcu_head *notused)
0265  2 {
0266  3   if (atomic_dec_and_test(&rcu_barrier_cpu_count))
0267  4     complete(&rcu_barrier_completion);
0268  5 }
0269 
0270 .. _rcubarrier_quiz_2:
0271 
0272 Quick Quiz #2:
0273         What happens if CPU 0's rcu_barrier_func() executes
0274         immediately (thus incrementing rcu_barrier_cpu_count to the
0275         value one), but the other CPU's rcu_barrier_func() invocations
0276         are delayed for a full grace period? Couldn't this result in
0277         rcu_barrier() returning prematurely?
0278 
0279 :ref:`Answer to Quick Quiz #2 <answer_rcubarrier_quiz_2>`
0280 
0281 The current rcu_barrier() implementation is more complex, due to the need
0282 to avoid disturbing idle CPUs (especially on battery-powered systems)
0283 and the need to minimally disturb non-idle CPUs in real-time systems.
0284 However, the code above illustrates the concepts.
0285 
0286 
0287 rcu_barrier() Summary
0288 ---------------------
0289 
0290 The rcu_barrier() primitive has seen relatively little use, since most
0291 code using RCU is in the core kernel rather than in modules. However, if
0292 you are using RCU from an unloadable module, you need to use rcu_barrier()
0293 so that your module may be safely unloaded.
0294 
0295 
0296 Answers to Quick Quizzes
0297 ------------------------
0298 
0299 .. _answer_rcubarrier_quiz_1:
0300 
0301 Quick Quiz #1:
0302         Is there any other situation where rcu_barrier() might
0303         be required?
0304 
0305 Answer: Interestingly enough, rcu_barrier() was not originally
0306         implemented for module unloading. Nikita Danilov was using
0307         RCU in a filesystem, which resulted in a similar situation at
0308         filesystem-unmount time. Dipankar Sarma coded up rcu_barrier()
0309         in response, so that Nikita could invoke it during the
0310         filesystem-unmount process.
0311 
0312         Much later, yours truly hit the RCU module-unload problem when
0313         implementing rcutorture, and found that rcu_barrier() solves
0314         this problem as well.
0315 
0316 :ref:`Back to Quick Quiz #1 <rcubarrier_quiz_1>`
0317 
0318 .. _answer_rcubarrier_quiz_2:
0319 
0320 Quick Quiz #2:
0321         What happens if CPU 0's rcu_barrier_func() executes
0322         immediately (thus incrementing rcu_barrier_cpu_count to the
0323         value one), but the other CPU's rcu_barrier_func() invocations
0324         are delayed for a full grace period? Couldn't this result in
0325         rcu_barrier() returning prematurely?
0326 
0327 Answer: This cannot happen. The reason is that on_each_cpu() has its last
0328         argument, the wait flag, set to "1". This flag is passed through
0329         to smp_call_function() and further to smp_call_function_on_cpu(),
0330         causing this latter to spin until the cross-CPU invocation of
0331         rcu_barrier_func() has completed. This by itself would prevent
0332         a grace period from completing on non-CONFIG_PREEMPTION kernels,
0333         since each CPU must undergo a context switch (or other quiescent
0334         state) before the grace period can complete. However, this is
0335         of no use in CONFIG_PREEMPTION kernels.
0336 
0337         Therefore, on_each_cpu() disables preemption across its call
0338         to smp_call_function() and also across the local call to
0339         rcu_barrier_func(). This prevents the local CPU from context
0340         switching, again preventing grace periods from completing. This
0341         means that all CPUs have executed rcu_barrier_func() before
0342         the first rcu_barrier_callback() can possibly execute, in turn
0343         preventing rcu_barrier_cpu_count from prematurely reaching zero.
0344 
0345         Currently, -rt implementations of RCU keep but a single global
0346         queue for RCU callbacks, and thus do not suffer from this
0347         problem. However, when the -rt RCU eventually does have per-CPU
0348         callback queues, things will have to change. One simple change
0349         is to add an rcu_read_lock() before line 8 of rcu_barrier()
0350         and an rcu_read_unlock() after line 8 of this same function. If
0351         you can think of a better change, please let me know!
0352 
0353 :ref:`Back to Quick Quiz #2 <rcubarrier_quiz_2>`