PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/Documentation/RCU/rcubarrier.rst

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