rcubarrier.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. RCU and Unloadable Modules
  2. [Originally published in LWN Jan. 14, 2007: http://lwn.net/Articles/217484/]
  3. RCU (read-copy update) is a synchronization mechanism that can be thought
  4. of as a replacement for read-writer locking (among other things), but with
  5. very low-overhead readers that are immune to deadlock, priority inversion,
  6. and unbounded latency. RCU read-side critical sections are delimited
  7. by rcu_read_lock() and rcu_read_unlock(), which, in non-CONFIG_PREEMPT
  8. kernels, generate no code whatsoever.
  9. This means that RCU writers are unaware of the presence of concurrent
  10. readers, so that RCU updates to shared data must be undertaken quite
  11. carefully, leaving an old version of the data structure in place until all
  12. pre-existing readers have finished. These old versions are needed because
  13. such readers might hold a reference to them. RCU updates can therefore be
  14. rather expensive, and RCU is thus best suited for read-mostly situations.
  15. How can an RCU writer possibly determine when all readers are finished,
  16. given that readers might well leave absolutely no trace of their
  17. presence? There is a synchronize_rcu() primitive that blocks until all
  18. pre-existing readers have completed. An updater wishing to delete an
  19. element p from a linked list might do the following, while holding an
  20. appropriate lock, of course:
  21. list_del_rcu(p);
  22. synchronize_rcu();
  23. kfree(p);
  24. But the above code cannot be used in IRQ context -- the call_rcu()
  25. primitive must be used instead. This primitive takes a pointer to an
  26. rcu_head struct placed within the RCU-protected data structure and
  27. another pointer to a function that may be invoked later to free that
  28. structure. Code to delete an element p from the linked list from IRQ
  29. context might then be as follows:
  30. list_del_rcu(p);
  31. call_rcu(&p->rcu, p_callback);
  32. Since call_rcu() never blocks, this code can safely be used from within
  33. IRQ context. The function p_callback() might be defined as follows:
  34. static void p_callback(struct rcu_head *rp)
  35. {
  36. struct pstruct *p = container_of(rp, struct pstruct, rcu);
  37. kfree(p);
  38. }
  39. Unloading Modules That Use call_rcu()
  40. But what if p_callback is defined in an unloadable module?
  41. If we unload the module while some RCU callbacks are pending,
  42. the CPUs executing these callbacks are going to be severely
  43. disappointed when they are later invoked, as fancifully depicted at
  44. http://lwn.net/images/ns/kernel/rcu-drop.jpg.
  45. We could try placing a synchronize_rcu() in the module-exit code path,
  46. but this is not sufficient. Although synchronize_rcu() does wait for a
  47. grace period to elapse, it does not wait for the callbacks to complete.
  48. One might be tempted to try several back-to-back synchronize_rcu()
  49. calls, but this is still not guaranteed to work. If there is a very
  50. heavy RCU-callback load, then some of the callbacks might be deferred
  51. in order to allow other processing to proceed. Such deferral is required
  52. in realtime kernels in order to avoid excessive scheduling latencies.
  53. rcu_barrier()
  54. We instead need the rcu_barrier() primitive. Rather than waiting for
  55. a grace period to elapse, rcu_barrier() waits for all outstanding RCU
  56. callbacks to complete. Please note that rcu_barrier() does -not- imply
  57. synchronize_rcu(), in particular, if there are no RCU callbacks queued
  58. anywhere, rcu_barrier() is within its rights to return immediately,
  59. without waiting for a grace period to elapse.
  60. Pseudo-code using rcu_barrier() is as follows:
  61. 1. Prevent any new RCU callbacks from being posted.
  62. 2. Execute rcu_barrier().
  63. 3. Allow the module to be unloaded.
  64. There are also rcu_barrier_bh(), rcu_barrier_sched(), and srcu_barrier()
  65. functions for the other flavors of RCU, and you of course must match
  66. the flavor of rcu_barrier() with that of call_rcu(). If your module
  67. uses multiple flavors of call_rcu(), then it must also use multiple
  68. flavors of rcu_barrier() when unloading that module. For example, if
  69. it uses call_rcu_bh(), call_srcu() on srcu_struct_1, and call_srcu() on
  70. srcu_struct_2(), then the following three lines of code will be required
  71. when unloading:
  72. 1 rcu_barrier_bh();
  73. 2 srcu_barrier(&srcu_struct_1);
  74. 3 srcu_barrier(&srcu_struct_2);
  75. The rcutorture module makes use of rcu_barrier() in its exit function
  76. as follows:
  77. 1 static void
  78. 2 rcu_torture_cleanup(void)
  79. 3 {
  80. 4 int i;
  81. 5
  82. 6 fullstop = 1;
  83. 7 if (shuffler_task != NULL) {
  84. 8 VERBOSE_PRINTK_STRING("Stopping rcu_torture_shuffle task");
  85. 9 kthread_stop(shuffler_task);
  86. 10 }
  87. 11 shuffler_task = NULL;
  88. 12
  89. 13 if (writer_task != NULL) {
  90. 14 VERBOSE_PRINTK_STRING("Stopping rcu_torture_writer task");
  91. 15 kthread_stop(writer_task);
  92. 16 }
  93. 17 writer_task = NULL;
  94. 18
  95. 19 if (reader_tasks != NULL) {
  96. 20 for (i = 0; i < nrealreaders; i++) {
  97. 21 if (reader_tasks[i] != NULL) {
  98. 22 VERBOSE_PRINTK_STRING(
  99. 23 "Stopping rcu_torture_reader task");
  100. 24 kthread_stop(reader_tasks[i]);
  101. 25 }
  102. 26 reader_tasks[i] = NULL;
  103. 27 }
  104. 28 kfree(reader_tasks);
  105. 29 reader_tasks = NULL;
  106. 30 }
  107. 31 rcu_torture_current = NULL;
  108. 32
  109. 33 if (fakewriter_tasks != NULL) {
  110. 34 for (i = 0; i < nfakewriters; i++) {
  111. 35 if (fakewriter_tasks[i] != NULL) {
  112. 36 VERBOSE_PRINTK_STRING(
  113. 37 "Stopping rcu_torture_fakewriter task");
  114. 38 kthread_stop(fakewriter_tasks[i]);
  115. 39 }
  116. 40 fakewriter_tasks[i] = NULL;
  117. 41 }
  118. 42 kfree(fakewriter_tasks);
  119. 43 fakewriter_tasks = NULL;
  120. 44 }
  121. 45
  122. 46 if (stats_task != NULL) {
  123. 47 VERBOSE_PRINTK_STRING("Stopping rcu_torture_stats task");
  124. 48 kthread_stop(stats_task);
  125. 49 }
  126. 50 stats_task = NULL;
  127. 51
  128. 52 /* Wait for all RCU callbacks to fire. */
  129. 53 rcu_barrier();
  130. 54
  131. 55 rcu_torture_stats_print(); /* -After- the stats thread is stopped! */
  132. 56
  133. 57 if (cur_ops->cleanup != NULL)
  134. 58 cur_ops->cleanup();
  135. 59 if (atomic_read(&n_rcu_torture_error))
  136. 60 rcu_torture_print_module_parms("End of test: FAILURE");
  137. 61 else
  138. 62 rcu_torture_print_module_parms("End of test: SUCCESS");
  139. 63 }
  140. Line 6 sets a global variable that prevents any RCU callbacks from
  141. re-posting themselves. This will not be necessary in most cases, since
  142. RCU callbacks rarely include calls to call_rcu(). However, the rcutorture
  143. module is an exception to this rule, and therefore needs to set this
  144. global variable.
  145. Lines 7-50 stop all the kernel tasks associated with the rcutorture
  146. module. Therefore, once execution reaches line 53, no more rcutorture
  147. RCU callbacks will be posted. The rcu_barrier() call on line 53 waits
  148. for any pre-existing callbacks to complete.
  149. Then lines 55-62 print status and do operation-specific cleanup, and
  150. then return, permitting the module-unload operation to be completed.
  151. Quick Quiz #1: Is there any other situation where rcu_barrier() might
  152. be required?
  153. Your module might have additional complications. For example, if your
  154. module invokes call_rcu() from timers, you will need to first cancel all
  155. the timers, and only then invoke rcu_barrier() to wait for any remaining
  156. RCU callbacks to complete.
  157. Of course, if you module uses call_rcu_bh(), you will need to invoke
  158. rcu_barrier_bh() before unloading. Similarly, if your module uses
  159. call_rcu_sched(), you will need to invoke rcu_barrier_sched() before
  160. unloading. If your module uses call_rcu(), call_rcu_bh(), -and-
  161. call_rcu_sched(), then you will need to invoke each of rcu_barrier(),
  162. rcu_barrier_bh(), and rcu_barrier_sched().
  163. Implementing rcu_barrier()
  164. Dipankar Sarma's implementation of rcu_barrier() makes use of the fact
  165. that RCU callbacks are never reordered once queued on one of the per-CPU
  166. queues. His implementation queues an RCU callback on each of the per-CPU
  167. callback queues, and then waits until they have all started executing, at
  168. which point, all earlier RCU callbacks are guaranteed to have completed.
  169. The original code for rcu_barrier() was as follows:
  170. 1 void rcu_barrier(void)
  171. 2 {
  172. 3 BUG_ON(in_interrupt());
  173. 4 /* Take cpucontrol mutex to protect against CPU hotplug */
  174. 5 mutex_lock(&rcu_barrier_mutex);
  175. 6 init_completion(&rcu_barrier_completion);
  176. 7 atomic_set(&rcu_barrier_cpu_count, 0);
  177. 8 on_each_cpu(rcu_barrier_func, NULL, 0, 1);
  178. 9 wait_for_completion(&rcu_barrier_completion);
  179. 10 mutex_unlock(&rcu_barrier_mutex);
  180. 11 }
  181. Line 3 verifies that the caller is in process context, and lines 5 and 10
  182. use rcu_barrier_mutex to ensure that only one rcu_barrier() is using the
  183. global completion and counters at a time, which are initialized on lines
  184. 6 and 7. Line 8 causes each CPU to invoke rcu_barrier_func(), which is
  185. shown below. Note that the final "1" in on_each_cpu()'s argument list
  186. ensures that all the calls to rcu_barrier_func() will have completed
  187. before on_each_cpu() returns. Line 9 then waits for the completion.
  188. This code was rewritten in 2008 to support rcu_barrier_bh() and
  189. rcu_barrier_sched() in addition to the original rcu_barrier().
  190. The rcu_barrier_func() runs on each CPU, where it invokes call_rcu()
  191. to post an RCU callback, as follows:
  192. 1 static void rcu_barrier_func(void *notused)
  193. 2 {
  194. 3 int cpu = smp_processor_id();
  195. 4 struct rcu_data *rdp = &per_cpu(rcu_data, cpu);
  196. 5 struct rcu_head *head;
  197. 6
  198. 7 head = &rdp->barrier;
  199. 8 atomic_inc(&rcu_barrier_cpu_count);
  200. 9 call_rcu(head, rcu_barrier_callback);
  201. 10 }
  202. Lines 3 and 4 locate RCU's internal per-CPU rcu_data structure,
  203. which contains the struct rcu_head that needed for the later call to
  204. call_rcu(). Line 7 picks up a pointer to this struct rcu_head, and line
  205. 8 increments a global counter. This counter will later be decremented
  206. by the callback. Line 9 then registers the rcu_barrier_callback() on
  207. the current CPU's queue.
  208. The rcu_barrier_callback() function simply atomically decrements the
  209. rcu_barrier_cpu_count variable and finalizes the completion when it
  210. reaches zero, as follows:
  211. 1 static void rcu_barrier_callback(struct rcu_head *notused)
  212. 2 {
  213. 3 if (atomic_dec_and_test(&rcu_barrier_cpu_count))
  214. 4 complete(&rcu_barrier_completion);
  215. 5 }
  216. Quick Quiz #2: What happens if CPU 0's rcu_barrier_func() executes
  217. immediately (thus incrementing rcu_barrier_cpu_count to the
  218. value one), but the other CPU's rcu_barrier_func() invocations
  219. are delayed for a full grace period? Couldn't this result in
  220. rcu_barrier() returning prematurely?
  221. rcu_barrier() Summary
  222. The rcu_barrier() primitive has seen relatively little use, since most
  223. code using RCU is in the core kernel rather than in modules. However, if
  224. you are using RCU from an unloadable module, you need to use rcu_barrier()
  225. so that your module may be safely unloaded.
  226. Answers to Quick Quizzes
  227. Quick Quiz #1: Is there any other situation where rcu_barrier() might
  228. be required?
  229. Answer: Interestingly enough, rcu_barrier() was not originally
  230. implemented for module unloading. Nikita Danilov was using
  231. RCU in a filesystem, which resulted in a similar situation at
  232. filesystem-unmount time. Dipankar Sarma coded up rcu_barrier()
  233. in response, so that Nikita could invoke it during the
  234. filesystem-unmount process.
  235. Much later, yours truly hit the RCU module-unload problem when
  236. implementing rcutorture, and found that rcu_barrier() solves
  237. this problem as well.
  238. Quick Quiz #2: What happens if CPU 0's rcu_barrier_func() executes
  239. immediately (thus incrementing rcu_barrier_cpu_count to the
  240. value one), but the other CPU's rcu_barrier_func() invocations
  241. are delayed for a full grace period? Couldn't this result in
  242. rcu_barrier() returning prematurely?
  243. Answer: This cannot happen. The reason is that on_each_cpu() has its last
  244. argument, the wait flag, set to "1". This flag is passed through
  245. to smp_call_function() and further to smp_call_function_on_cpu(),
  246. causing this latter to spin until the cross-CPU invocation of
  247. rcu_barrier_func() has completed. This by itself would prevent
  248. a grace period from completing on non-CONFIG_PREEMPT kernels,
  249. since each CPU must undergo a context switch (or other quiescent
  250. state) before the grace period can complete. However, this is
  251. of no use in CONFIG_PREEMPT kernels.
  252. Therefore, on_each_cpu() disables preemption across its call
  253. to smp_call_function() and also across the local call to
  254. rcu_barrier_func(). This prevents the local CPU from context
  255. switching, again preventing grace periods from completing. This
  256. means that all CPUs have executed rcu_barrier_func() before
  257. the first rcu_barrier_callback() can possibly execute, in turn
  258. preventing rcu_barrier_cpu_count from prematurely reaching zero.
  259. Currently, -rt implementations of RCU keep but a single global
  260. queue for RCU callbacks, and thus do not suffer from this
  261. problem. However, when the -rt RCU eventually does have per-CPU
  262. callback queues, things will have to change. One simple change
  263. is to add an rcu_read_lock() before line 8 of rcu_barrier()
  264. and an rcu_read_unlock() after line 8 of this same function. If
  265. you can think of a better change, please let me know!