blob: 2e319d1b9ef28c0d9c19505306063cfc6bc9f595 [file] [log] [blame]
Paul E. McKenney1c127572008-11-13 18:11:52 -08001RCU and Unloadable Modules
2
3[Originally published in LWN Jan. 14, 2007: http://lwn.net/Articles/217484/]
4
5RCU (read-copy update) is a synchronization mechanism that can be thought
6of as a replacement for read-writer locking (among other things), but with
7very low-overhead readers that are immune to deadlock, priority inversion,
8and unbounded latency. RCU read-side critical sections are delimited
9by rcu_read_lock() and rcu_read_unlock(), which, in non-CONFIG_PREEMPT
10kernels, generate no code whatsoever.
11
12This means that RCU writers are unaware of the presence of concurrent
13readers, so that RCU updates to shared data must be undertaken quite
14carefully, leaving an old version of the data structure in place until all
15pre-existing readers have finished. These old versions are needed because
16such readers might hold a reference to them. RCU updates can therefore be
17rather expensive, and RCU is thus best suited for read-mostly situations.
18
19How can an RCU writer possibly determine when all readers are finished,
20given that readers might well leave absolutely no trace of their
21presence? There is a synchronize_rcu() primitive that blocks until all
22pre-existing readers have completed. An updater wishing to delete an
23element p from a linked list might do the following, while holding an
24appropriate lock, of course:
25
26 list_del_rcu(p);
27 synchronize_rcu();
28 kfree(p);
29
30But the above code cannot be used in IRQ context -- the call_rcu()
31primitive must be used instead. This primitive takes a pointer to an
32rcu_head struct placed within the RCU-protected data structure and
33another pointer to a function that may be invoked later to free that
34structure. Code to delete an element p from the linked list from IRQ
35context might then be as follows:
36
37 list_del_rcu(p);
38 call_rcu(&p->rcu, p_callback);
39
40Since call_rcu() never blocks, this code can safely be used from within
41IRQ context. The function p_callback() might be defined as follows:
42
43 static void p_callback(struct rcu_head *rp)
44 {
45 struct pstruct *p = container_of(rp, struct pstruct, rcu);
46
47 kfree(p);
48 }
49
50
51Unloading Modules That Use call_rcu()
52
53But what if p_callback is defined in an unloadable module?
54
55If we unload the module while some RCU callbacks are pending,
56the CPUs executing these callbacks are going to be severely
57disappointed when they are later invoked, as fancifully depicted at
58http://lwn.net/images/ns/kernel/rcu-drop.jpg.
59
60We could try placing a synchronize_rcu() in the module-exit code path,
61but this is not sufficient. Although synchronize_rcu() does wait for a
62grace period to elapse, it does not wait for the callbacks to complete.
63
64One might be tempted to try several back-to-back synchronize_rcu()
65calls, but this is still not guaranteed to work. If there is a very
66heavy RCU-callback load, then some of the callbacks might be deferred
67in order to allow other processing to proceed. Such deferral is required
68in realtime kernels in order to avoid excessive scheduling latencies.
69
70
71rcu_barrier()
72
73We instead need the rcu_barrier() primitive. This primitive is similar
74to synchronize_rcu(), but instead of waiting solely for a grace
75period to elapse, it also waits for all outstanding RCU callbacks to
76complete. Pseudo-code using rcu_barrier() is as follows:
77
78 1. Prevent any new RCU callbacks from being posted.
79 2. Execute rcu_barrier().
80 3. Allow the module to be unloaded.
81
Paul E. McKenney3f944ad2013-03-04 17:55:49 -080082There are also rcu_barrier_bh(), rcu_barrier_sched(), and srcu_barrier()
83functions for the other flavors of RCU, and you of course must match
84the flavor of rcu_barrier() with that of call_rcu(). If your module
85uses multiple flavors of call_rcu(), then it must also use multiple
86flavors of rcu_barrier() when unloading that module. For example, if
87it uses call_rcu_bh(), call_srcu() on srcu_struct_1, and call_srcu() on
88srcu_struct_2(), then the following three lines of code will be required
89when unloading:
90
91 1 rcu_barrier_bh();
92 2 srcu_barrier(&srcu_struct_1);
93 3 srcu_barrier(&srcu_struct_2);
94
95The rcutorture module makes use of rcu_barrier() in its exit function
Paul E. McKenney1c127572008-11-13 18:11:52 -080096as follows:
97
98 1 static void
99 2 rcu_torture_cleanup(void)
100 3 {
101 4 int i;
102 5
103 6 fullstop = 1;
104 7 if (shuffler_task != NULL) {
105 8 VERBOSE_PRINTK_STRING("Stopping rcu_torture_shuffle task");
106 9 kthread_stop(shuffler_task);
10710 }
10811 shuffler_task = NULL;
10912
11013 if (writer_task != NULL) {
11114 VERBOSE_PRINTK_STRING("Stopping rcu_torture_writer task");
11215 kthread_stop(writer_task);
11316 }
11417 writer_task = NULL;
11518
11619 if (reader_tasks != NULL) {
11720 for (i = 0; i < nrealreaders; i++) {
11821 if (reader_tasks[i] != NULL) {
11922 VERBOSE_PRINTK_STRING(
12023 "Stopping rcu_torture_reader task");
12124 kthread_stop(reader_tasks[i]);
12225 }
12326 reader_tasks[i] = NULL;
12427 }
12528 kfree(reader_tasks);
12629 reader_tasks = NULL;
12730 }
12831 rcu_torture_current = NULL;
12932
13033 if (fakewriter_tasks != NULL) {
13134 for (i = 0; i < nfakewriters; i++) {
13235 if (fakewriter_tasks[i] != NULL) {
13336 VERBOSE_PRINTK_STRING(
13437 "Stopping rcu_torture_fakewriter task");
13538 kthread_stop(fakewriter_tasks[i]);
13639 }
13740 fakewriter_tasks[i] = NULL;
13841 }
13942 kfree(fakewriter_tasks);
14043 fakewriter_tasks = NULL;
14144 }
14245
14346 if (stats_task != NULL) {
14447 VERBOSE_PRINTK_STRING("Stopping rcu_torture_stats task");
14548 kthread_stop(stats_task);
14649 }
14750 stats_task = NULL;
14851
14952 /* Wait for all RCU callbacks to fire. */
15053 rcu_barrier();
15154
15255 rcu_torture_stats_print(); /* -After- the stats thread is stopped! */
15356
15457 if (cur_ops->cleanup != NULL)
15558 cur_ops->cleanup();
15659 if (atomic_read(&n_rcu_torture_error))
15760 rcu_torture_print_module_parms("End of test: FAILURE");
15861 else
15962 rcu_torture_print_module_parms("End of test: SUCCESS");
16063 }
161
162Line 6 sets a global variable that prevents any RCU callbacks from
163re-posting themselves. This will not be necessary in most cases, since
164RCU callbacks rarely include calls to call_rcu(). However, the rcutorture
165module is an exception to this rule, and therefore needs to set this
166global variable.
167
168Lines 7-50 stop all the kernel tasks associated with the rcutorture
169module. Therefore, once execution reaches line 53, no more rcutorture
170RCU callbacks will be posted. The rcu_barrier() call on line 53 waits
171for any pre-existing callbacks to complete.
172
173Then lines 55-62 print status and do operation-specific cleanup, and
174then return, permitting the module-unload operation to be completed.
175
Paul E. McKenney74d874e2012-05-07 13:43:30 -0700176Quick Quiz #1: Is there any other situation where rcu_barrier() might
Paul E. McKenney1c127572008-11-13 18:11:52 -0800177 be required?
178
179Your module might have additional complications. For example, if your
180module invokes call_rcu() from timers, you will need to first cancel all
181the timers, and only then invoke rcu_barrier() to wait for any remaining
182RCU callbacks to complete.
183
Paul E. McKenney240ebbf2009-06-25 09:08:18 -0700184Of course, if you module uses call_rcu_bh(), you will need to invoke
185rcu_barrier_bh() before unloading. Similarly, if your module uses
186call_rcu_sched(), you will need to invoke rcu_barrier_sched() before
187unloading. If your module uses call_rcu(), call_rcu_bh(), -and-
188call_rcu_sched(), then you will need to invoke each of rcu_barrier(),
189rcu_barrier_bh(), and rcu_barrier_sched().
190
Paul E. McKenney1c127572008-11-13 18:11:52 -0800191
192Implementing rcu_barrier()
193
194Dipankar Sarma's implementation of rcu_barrier() makes use of the fact
195that RCU callbacks are never reordered once queued on one of the per-CPU
196queues. His implementation queues an RCU callback on each of the per-CPU
197callback queues, and then waits until they have all started executing, at
198which point, all earlier RCU callbacks are guaranteed to have completed.
199
200The original code for rcu_barrier() was as follows:
201
202 1 void rcu_barrier(void)
203 2 {
204 3 BUG_ON(in_interrupt());
205 4 /* Take cpucontrol mutex to protect against CPU hotplug */
206 5 mutex_lock(&rcu_barrier_mutex);
207 6 init_completion(&rcu_barrier_completion);
208 7 atomic_set(&rcu_barrier_cpu_count, 0);
209 8 on_each_cpu(rcu_barrier_func, NULL, 0, 1);
210 9 wait_for_completion(&rcu_barrier_completion);
21110 mutex_unlock(&rcu_barrier_mutex);
21211 }
213
214Line 3 verifies that the caller is in process context, and lines 5 and 10
215use rcu_barrier_mutex to ensure that only one rcu_barrier() is using the
216global completion and counters at a time, which are initialized on lines
2176 and 7. Line 8 causes each CPU to invoke rcu_barrier_func(), which is
218shown below. Note that the final "1" in on_each_cpu()'s argument list
219ensures that all the calls to rcu_barrier_func() will have completed
220before on_each_cpu() returns. Line 9 then waits for the completion.
221
222This code was rewritten in 2008 to support rcu_barrier_bh() and
223rcu_barrier_sched() in addition to the original rcu_barrier().
224
225The rcu_barrier_func() runs on each CPU, where it invokes call_rcu()
226to post an RCU callback, as follows:
227
228 1 static void rcu_barrier_func(void *notused)
229 2 {
230 3 int cpu = smp_processor_id();
231 4 struct rcu_data *rdp = &per_cpu(rcu_data, cpu);
232 5 struct rcu_head *head;
233 6
234 7 head = &rdp->barrier;
235 8 atomic_inc(&rcu_barrier_cpu_count);
236 9 call_rcu(head, rcu_barrier_callback);
23710 }
238
239Lines 3 and 4 locate RCU's internal per-CPU rcu_data structure,
240which contains the struct rcu_head that needed for the later call to
241call_rcu(). Line 7 picks up a pointer to this struct rcu_head, and line
2428 increments a global counter. This counter will later be decremented
243by the callback. Line 9 then registers the rcu_barrier_callback() on
244the current CPU's queue.
245
246The rcu_barrier_callback() function simply atomically decrements the
247rcu_barrier_cpu_count variable and finalizes the completion when it
248reaches zero, as follows:
249
250 1 static void rcu_barrier_callback(struct rcu_head *notused)
251 2 {
252 3 if (atomic_dec_and_test(&rcu_barrier_cpu_count))
253 4 complete(&rcu_barrier_completion);
254 5 }
255
Paul E. McKenney74d874e2012-05-07 13:43:30 -0700256Quick Quiz #2: What happens if CPU 0's rcu_barrier_func() executes
Paul E. McKenney1c127572008-11-13 18:11:52 -0800257 immediately (thus incrementing rcu_barrier_cpu_count to the
258 value one), but the other CPU's rcu_barrier_func() invocations
259 are delayed for a full grace period? Couldn't this result in
260 rcu_barrier() returning prematurely?
261
262
263rcu_barrier() Summary
264
265The rcu_barrier() primitive has seen relatively little use, since most
266code using RCU is in the core kernel rather than in modules. However, if
267you are using RCU from an unloadable module, you need to use rcu_barrier()
268so that your module may be safely unloaded.
269
270
271Answers to Quick Quizzes
272
Paul E. McKenney74d874e2012-05-07 13:43:30 -0700273Quick Quiz #1: Is there any other situation where rcu_barrier() might
Paul E. McKenney1c127572008-11-13 18:11:52 -0800274 be required?
275
276Answer: Interestingly enough, rcu_barrier() was not originally
277 implemented for module unloading. Nikita Danilov was using
278 RCU in a filesystem, which resulted in a similar situation at
279 filesystem-unmount time. Dipankar Sarma coded up rcu_barrier()
280 in response, so that Nikita could invoke it during the
281 filesystem-unmount process.
282
283 Much later, yours truly hit the RCU module-unload problem when
284 implementing rcutorture, and found that rcu_barrier() solves
285 this problem as well.
286
Paul E. McKenney74d874e2012-05-07 13:43:30 -0700287Quick Quiz #2: What happens if CPU 0's rcu_barrier_func() executes
Paul E. McKenney1c127572008-11-13 18:11:52 -0800288 immediately (thus incrementing rcu_barrier_cpu_count to the
289 value one), but the other CPU's rcu_barrier_func() invocations
290 are delayed for a full grace period? Couldn't this result in
291 rcu_barrier() returning prematurely?
292
293Answer: This cannot happen. The reason is that on_each_cpu() has its last
294 argument, the wait flag, set to "1". This flag is passed through
295 to smp_call_function() and further to smp_call_function_on_cpu(),
296 causing this latter to spin until the cross-CPU invocation of
297 rcu_barrier_func() has completed. This by itself would prevent
298 a grace period from completing on non-CONFIG_PREEMPT kernels,
299 since each CPU must undergo a context switch (or other quiescent
300 state) before the grace period can complete. However, this is
301 of no use in CONFIG_PREEMPT kernels.
302
303 Therefore, on_each_cpu() disables preemption across its call
304 to smp_call_function() and also across the local call to
305 rcu_barrier_func(). This prevents the local CPU from context
306 switching, again preventing grace periods from completing. This
307 means that all CPUs have executed rcu_barrier_func() before
308 the first rcu_barrier_callback() can possibly execute, in turn
309 preventing rcu_barrier_cpu_count from prematurely reaching zero.
310
311 Currently, -rt implementations of RCU keep but a single global
312 queue for RCU callbacks, and thus do not suffer from this
313 problem. However, when the -rt RCU eventually does have per-CPU
314 callback queues, things will have to change. One simple change
315 is to add an rcu_read_lock() before line 8 of rcu_barrier()
316 and an rcu_read_unlock() after line 8 of this same function. If
317 you can think of a better change, please let me know!