rcubarrier.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. .. _rcu_barrier:
  2. RCU and Unloadable Modules
  3. ==========================
  4. [Originally published in LWN Jan. 14, 2007: http://lwn.net/Articles/217484/]
  5. RCU updaters sometimes use call_rcu() to initiate an asynchronous wait for
  6. a grace period to elapse. This primitive takes a pointer to an rcu_head
  7. struct placed within the RCU-protected data structure and another pointer
  8. to a function that may be invoked later to free that structure. Code to
  9. delete an element p from the linked list from IRQ context might then be
  10. as follows::
  11. list_del_rcu(p);
  12. call_rcu(&p->rcu, p_callback);
  13. Since call_rcu() never blocks, this code can safely be used from within
  14. IRQ context. The function p_callback() might be defined as follows::
  15. static void p_callback(struct rcu_head *rp)
  16. {
  17. struct pstruct *p = container_of(rp, struct pstruct, rcu);
  18. kfree(p);
  19. }
  20. Unloading Modules That Use call_rcu()
  21. -------------------------------------
  22. But what if the p_callback() function is defined in an unloadable module?
  23. If we unload the module while some RCU callbacks are pending,
  24. the CPUs executing these callbacks are going to be severely
  25. disappointed when they are later invoked, as fancifully depicted at
  26. http://lwn.net/images/ns/kernel/rcu-drop.jpg.
  27. We could try placing a synchronize_rcu() in the module-exit code path,
  28. but this is not sufficient. Although synchronize_rcu() does wait for a
  29. grace period to elapse, it does not wait for the callbacks to complete.
  30. One might be tempted to try several back-to-back synchronize_rcu()
  31. calls, but this is still not guaranteed to work. If there is a very
  32. heavy RCU-callback load, then some of the callbacks might be deferred in
  33. order to allow other processing to proceed. For but one example, such
  34. deferral is required in realtime kernels in order to avoid excessive
  35. scheduling latencies.
  36. rcu_barrier()
  37. -------------
  38. This situation can be handled by the rcu_barrier() primitive. Rather
  39. than waiting for a grace period to elapse, rcu_barrier() waits for all
  40. outstanding RCU callbacks to complete. Please note that rcu_barrier()
  41. does **not** imply synchronize_rcu(), in particular, if there are no RCU
  42. callbacks queued anywhere, rcu_barrier() is within its rights to return
  43. immediately, without waiting for anything, let alone a grace period.
  44. Pseudo-code using rcu_barrier() is as follows:
  45. 1. Prevent any new RCU callbacks from being posted.
  46. 2. Execute rcu_barrier().
  47. 3. Allow the module to be unloaded.
  48. There is also an srcu_barrier() function for SRCU, and you of course
  49. must match the flavor of srcu_barrier() with that of call_srcu().
  50. If your module uses multiple srcu_struct structures, then it must also
  51. use multiple invocations of srcu_barrier() when unloading that module.
  52. For example, if it uses call_rcu(), call_srcu() on srcu_struct_1, and
  53. call_srcu() on srcu_struct_2, then the following three lines of code
  54. will be required when unloading::
  55. 1 rcu_barrier();
  56. 2 srcu_barrier(&srcu_struct_1);
  57. 3 srcu_barrier(&srcu_struct_2);
  58. If latency is of the essence, workqueues could be used to run these
  59. three functions concurrently.
  60. An ancient version of the rcutorture module makes use of rcu_barrier()
  61. in its exit function as follows::
  62. 1 static void
  63. 2 rcu_torture_cleanup(void)
  64. 3 {
  65. 4 int i;
  66. 5
  67. 6 fullstop = 1;
  68. 7 if (shuffler_task != NULL) {
  69. 8 VERBOSE_PRINTK_STRING("Stopping rcu_torture_shuffle task");
  70. 9 kthread_stop(shuffler_task);
  71. 10 }
  72. 11 shuffler_task = NULL;
  73. 12
  74. 13 if (writer_task != NULL) {
  75. 14 VERBOSE_PRINTK_STRING("Stopping rcu_torture_writer task");
  76. 15 kthread_stop(writer_task);
  77. 16 }
  78. 17 writer_task = NULL;
  79. 18
  80. 19 if (reader_tasks != NULL) {
  81. 20 for (i = 0; i < nrealreaders; i++) {
  82. 21 if (reader_tasks[i] != NULL) {
  83. 22 VERBOSE_PRINTK_STRING(
  84. 23 "Stopping rcu_torture_reader task");
  85. 24 kthread_stop(reader_tasks[i]);
  86. 25 }
  87. 26 reader_tasks[i] = NULL;
  88. 27 }
  89. 28 kfree(reader_tasks);
  90. 29 reader_tasks = NULL;
  91. 30 }
  92. 31 rcu_torture_current = NULL;
  93. 32
  94. 33 if (fakewriter_tasks != NULL) {
  95. 34 for (i = 0; i < nfakewriters; i++) {
  96. 35 if (fakewriter_tasks[i] != NULL) {
  97. 36 VERBOSE_PRINTK_STRING(
  98. 37 "Stopping rcu_torture_fakewriter task");
  99. 38 kthread_stop(fakewriter_tasks[i]);
  100. 39 }
  101. 40 fakewriter_tasks[i] = NULL;
  102. 41 }
  103. 42 kfree(fakewriter_tasks);
  104. 43 fakewriter_tasks = NULL;
  105. 44 }
  106. 45
  107. 46 if (stats_task != NULL) {
  108. 47 VERBOSE_PRINTK_STRING("Stopping rcu_torture_stats task");
  109. 48 kthread_stop(stats_task);
  110. 49 }
  111. 50 stats_task = NULL;
  112. 51
  113. 52 /* Wait for all RCU callbacks to fire. */
  114. 53 rcu_barrier();
  115. 54
  116. 55 rcu_torture_stats_print(); /* -After- the stats thread is stopped! */
  117. 56
  118. 57 if (cur_ops->cleanup != NULL)
  119. 58 cur_ops->cleanup();
  120. 59 if (atomic_read(&n_rcu_torture_error))
  121. 60 rcu_torture_print_module_parms("End of test: FAILURE");
  122. 61 else
  123. 62 rcu_torture_print_module_parms("End of test: SUCCESS");
  124. 63 }
  125. Line 6 sets a global variable that prevents any RCU callbacks from
  126. re-posting themselves. This will not be necessary in most cases, since
  127. RCU callbacks rarely include calls to call_rcu(). However, the rcutorture
  128. module is an exception to this rule, and therefore needs to set this
  129. global variable.
  130. Lines 7-50 stop all the kernel tasks associated with the rcutorture
  131. module. Therefore, once execution reaches line 53, no more rcutorture
  132. RCU callbacks will be posted. The rcu_barrier() call on line 53 waits
  133. for any pre-existing callbacks to complete.
  134. Then lines 55-62 print status and do operation-specific cleanup, and
  135. then return, permitting the module-unload operation to be completed.
  136. .. _rcubarrier_quiz_1:
  137. Quick Quiz #1:
  138. Is there any other situation where rcu_barrier() might
  139. be required?
  140. :ref:`Answer to Quick Quiz #1 <answer_rcubarrier_quiz_1>`
  141. Your module might have additional complications. For example, if your
  142. module invokes call_rcu() from timers, you will need to first refrain
  143. from posting new timers, cancel (or wait for) all the already-posted
  144. timers, and only then invoke rcu_barrier() to wait for any remaining
  145. RCU callbacks to complete.
  146. Of course, if your module uses call_rcu(), you will need to invoke
  147. rcu_barrier() before unloading. Similarly, if your module uses
  148. call_srcu(), you will need to invoke srcu_barrier() before unloading,
  149. and on the same srcu_struct structure. If your module uses call_rcu()
  150. **and** call_srcu(), then (as noted above) you will need to invoke
  151. rcu_barrier() **and** srcu_barrier().
  152. Implementing rcu_barrier()
  153. --------------------------
  154. Dipankar Sarma's implementation of rcu_barrier() makes use of the fact
  155. that RCU callbacks are never reordered once queued on one of the per-CPU
  156. queues. His implementation queues an RCU callback on each of the per-CPU
  157. callback queues, and then waits until they have all started executing, at
  158. which point, all earlier RCU callbacks are guaranteed to have completed.
  159. The original code for rcu_barrier() was roughly as follows::
  160. 1 void rcu_barrier(void)
  161. 2 {
  162. 3 BUG_ON(in_interrupt());
  163. 4 /* Take cpucontrol mutex to protect against CPU hotplug */
  164. 5 mutex_lock(&rcu_barrier_mutex);
  165. 6 init_completion(&rcu_barrier_completion);
  166. 7 atomic_set(&rcu_barrier_cpu_count, 1);
  167. 8 on_each_cpu(rcu_barrier_func, NULL, 0, 1);
  168. 9 if (atomic_dec_and_test(&rcu_barrier_cpu_count))
  169. 10 complete(&rcu_barrier_completion);
  170. 11 wait_for_completion(&rcu_barrier_completion);
  171. 12 mutex_unlock(&rcu_barrier_mutex);
  172. 13 }
  173. Line 3 verifies that the caller is in process context, and lines 5 and 12
  174. use rcu_barrier_mutex to ensure that only one rcu_barrier() is using the
  175. global completion and counters at a time, which are initialized on lines
  176. 6 and 7. Line 8 causes each CPU to invoke rcu_barrier_func(), which is
  177. shown below. Note that the final "1" in on_each_cpu()'s argument list
  178. ensures that all the calls to rcu_barrier_func() will have completed
  179. before on_each_cpu() returns. Line 9 removes the initial count from
  180. rcu_barrier_cpu_count, and if this count is now zero, line 10 finalizes
  181. the completion, which prevents line 11 from blocking. Either way,
  182. line 11 then waits (if needed) for the completion.
  183. .. _rcubarrier_quiz_2:
  184. Quick Quiz #2:
  185. Why doesn't line 8 initialize rcu_barrier_cpu_count to zero,
  186. thereby avoiding the need for lines 9 and 10?
  187. :ref:`Answer to Quick Quiz #2 <answer_rcubarrier_quiz_2>`
  188. This code was rewritten in 2008 and several times thereafter, but this
  189. still gives the general idea.
  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 the 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. .. _rcubarrier_quiz_3:
  217. Quick Quiz #3:
  218. What happens if CPU 0's rcu_barrier_func() executes
  219. immediately (thus incrementing rcu_barrier_cpu_count to the
  220. value one), but the other CPU's rcu_barrier_func() invocations
  221. are delayed for a full grace period? Couldn't this result in
  222. rcu_barrier() returning prematurely?
  223. :ref:`Answer to Quick Quiz #3 <answer_rcubarrier_quiz_3>`
  224. The current rcu_barrier() implementation is more complex, due to the need
  225. to avoid disturbing idle CPUs (especially on battery-powered systems)
  226. and the need to minimally disturb non-idle CPUs in real-time systems.
  227. In addition, a great many optimizations have been applied. However,
  228. the code above illustrates the concepts.
  229. rcu_barrier() Summary
  230. ---------------------
  231. The rcu_barrier() primitive is used relatively infrequently, since most
  232. code using RCU is in the core kernel rather than in modules. However, if
  233. you are using RCU from an unloadable module, you need to use rcu_barrier()
  234. so that your module may be safely unloaded.
  235. Answers to Quick Quizzes
  236. ------------------------
  237. .. _answer_rcubarrier_quiz_1:
  238. Quick Quiz #1:
  239. Is there any other situation where rcu_barrier() might
  240. be required?
  241. Answer:
  242. Interestingly enough, rcu_barrier() was not originally
  243. implemented for module unloading. Nikita Danilov was using
  244. RCU in a filesystem, which resulted in a similar situation at
  245. filesystem-unmount time. Dipankar Sarma coded up rcu_barrier()
  246. in response, so that Nikita could invoke it during the
  247. filesystem-unmount process.
  248. Much later, yours truly hit the RCU module-unload problem when
  249. implementing rcutorture, and found that rcu_barrier() solves
  250. this problem as well.
  251. :ref:`Back to Quick Quiz #1 <rcubarrier_quiz_1>`
  252. .. _answer_rcubarrier_quiz_2:
  253. Quick Quiz #2:
  254. Why doesn't line 8 initialize rcu_barrier_cpu_count to zero,
  255. thereby avoiding the need for lines 9 and 10?
  256. Answer:
  257. Suppose that the on_each_cpu() function shown on line 8 was
  258. delayed, so that CPU 0's rcu_barrier_func() executed and
  259. the corresponding grace period elapsed, all before CPU 1's
  260. rcu_barrier_func() started executing. This would result in
  261. rcu_barrier_cpu_count being decremented to zero, so that line
  262. 11's wait_for_completion() would return immediately, failing to
  263. wait for CPU 1's callbacks to be invoked.
  264. Note that this was not a problem when the rcu_barrier() code
  265. was first added back in 2005. This is because on_each_cpu()
  266. disables preemption, which acted as an RCU read-side critical
  267. section, thus preventing CPU 0's grace period from completing
  268. until on_each_cpu() had dealt with all of the CPUs. However,
  269. with the advent of preemptible RCU, rcu_barrier() no longer
  270. waited on nonpreemptible regions of code in preemptible kernels,
  271. that being the job of the new rcu_barrier_sched() function.
  272. However, with the RCU flavor consolidation around v4.20, this
  273. possibility was once again ruled out, because the consolidated
  274. RCU once again waits on nonpreemptible regions of code.
  275. Nevertheless, that extra count might still be a good idea.
  276. Relying on these sort of accidents of implementation can result
  277. in later surprise bugs when the implementation changes.
  278. :ref:`Back to Quick Quiz #2 <rcubarrier_quiz_2>`
  279. .. _answer_rcubarrier_quiz_3:
  280. Quick Quiz #3:
  281. What happens if CPU 0's rcu_barrier_func() executes
  282. immediately (thus incrementing rcu_barrier_cpu_count to the
  283. value one), but the other CPU's rcu_barrier_func() invocations
  284. are delayed for a full grace period? Couldn't this result in
  285. rcu_barrier() returning prematurely?
  286. Answer:
  287. This cannot happen. The reason is that on_each_cpu() has its last
  288. argument, the wait flag, set to "1". This flag is passed through
  289. to smp_call_function() and further to smp_call_function_on_cpu(),
  290. causing this latter to spin until the cross-CPU invocation of
  291. rcu_barrier_func() has completed. This by itself would prevent
  292. a grace period from completing on non-CONFIG_PREEMPTION kernels,
  293. since each CPU must undergo a context switch (or other quiescent
  294. state) before the grace period can complete. However, this is
  295. of no use in CONFIG_PREEMPTION kernels.
  296. Therefore, on_each_cpu() disables preemption across its call
  297. to smp_call_function() and also across the local call to
  298. rcu_barrier_func(). Because recent RCU implementations treat
  299. preemption-disabled regions of code as RCU read-side critical
  300. sections, this prevents grace periods from completing. This
  301. means that all CPUs have executed rcu_barrier_func() before
  302. the first rcu_barrier_callback() can possibly execute, in turn
  303. preventing rcu_barrier_cpu_count from prematurely reaching zero.
  304. But if on_each_cpu() ever decides to forgo disabling preemption,
  305. as might well happen due to real-time latency considerations,
  306. initializing rcu_barrier_cpu_count to one will save the day.
  307. :ref:`Back to Quick Quiz #3 <rcubarrier_quiz_3>`