listRCU.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. .. _list_rcu_doc:
  2. Using RCU to Protect Read-Mostly Linked Lists
  3. =============================================
  4. One of the most common uses of RCU is protecting read-mostly linked lists
  5. (``struct list_head`` in list.h). One big advantage of this approach is
  6. that all of the required memory ordering is provided by the list macros.
  7. This document describes several list-based RCU use cases.
  8. When iterating a list while holding the rcu_read_lock(), writers may
  9. modify the list. The reader is guaranteed to see all of the elements
  10. which were added to the list before they acquired the rcu_read_lock()
  11. and are still on the list when they drop the rcu_read_unlock().
  12. Elements which are added to, or removed from the list may or may not
  13. be seen. If the writer calls list_replace_rcu(), the reader may see
  14. either the old element or the new element; they will not see both,
  15. nor will they see neither.
  16. Example 1: Read-mostly list: Deferred Destruction
  17. -------------------------------------------------
  18. A widely used usecase for RCU lists in the kernel is lockless iteration over
  19. all processes in the system. ``task_struct::tasks`` represents the list node that
  20. links all the processes. The list can be traversed in parallel to any list
  21. additions or removals.
  22. The traversal of the list is done using ``for_each_process()`` which is defined
  23. by the 2 macros::
  24. #define next_task(p) \
  25. list_entry_rcu((p)->tasks.next, struct task_struct, tasks)
  26. #define for_each_process(p) \
  27. for (p = &init_task ; (p = next_task(p)) != &init_task ; )
  28. The code traversing the list of all processes typically looks like::
  29. rcu_read_lock();
  30. for_each_process(p) {
  31. /* Do something with p */
  32. }
  33. rcu_read_unlock();
  34. The simplified and heavily inlined code for removing a process from a
  35. task list is::
  36. void release_task(struct task_struct *p)
  37. {
  38. write_lock(&tasklist_lock);
  39. list_del_rcu(&p->tasks);
  40. write_unlock(&tasklist_lock);
  41. call_rcu(&p->rcu, delayed_put_task_struct);
  42. }
  43. When a process exits, ``release_task()`` calls ``list_del_rcu(&p->tasks)``
  44. via __exit_signal() and __unhash_process() under ``tasklist_lock``
  45. writer lock protection. The list_del_rcu() invocation removes
  46. the task from the list of all tasks. The ``tasklist_lock``
  47. prevents concurrent list additions/removals from corrupting the
  48. list. Readers using ``for_each_process()`` are not protected with the
  49. ``tasklist_lock``. To prevent readers from noticing changes in the list
  50. pointers, the ``task_struct`` object is freed only after one or more
  51. grace periods elapse, with the help of call_rcu(), which is invoked via
  52. put_task_struct_rcu_user(). This deferring of destruction ensures that
  53. any readers traversing the list will see valid ``p->tasks.next`` pointers
  54. and deletion/freeing can happen in parallel with traversal of the list.
  55. This pattern is also called an **existence lock**, since RCU refrains
  56. from invoking the delayed_put_task_struct() callback function until
  57. all existing readers finish, which guarantees that the ``task_struct``
  58. object in question will remain in existence until after the completion
  59. of all RCU readers that might possibly have a reference to that object.
  60. Example 2: Read-Side Action Taken Outside of Lock: No In-Place Updates
  61. ----------------------------------------------------------------------
  62. Some reader-writer locking use cases compute a value while holding
  63. the read-side lock, but continue to use that value after that lock is
  64. released. These use cases are often good candidates for conversion
  65. to RCU. One prominent example involves network packet routing.
  66. Because the packet-routing data tracks the state of equipment outside
  67. of the computer, it will at times contain stale data. Therefore, once
  68. the route has been computed, there is no need to hold the routing table
  69. static during transmission of the packet. After all, you can hold the
  70. routing table static all you want, but that won't keep the external
  71. Internet from changing, and it is the state of the external Internet
  72. that really matters. In addition, routing entries are typically added
  73. or deleted, rather than being modified in place. This is a rare example
  74. of the finite speed of light and the non-zero size of atoms actually
  75. helping make synchronization be lighter weight.
  76. A straightforward example of this type of RCU use case may be found in
  77. the system-call auditing support. For example, a reader-writer locked
  78. implementation of ``audit_filter_task()`` might be as follows::
  79. static enum audit_state audit_filter_task(struct task_struct *tsk, char **key)
  80. {
  81. struct audit_entry *e;
  82. enum audit_state state;
  83. read_lock(&auditsc_lock);
  84. /* Note: audit_filter_mutex held by caller. */
  85. list_for_each_entry(e, &audit_tsklist, list) {
  86. if (audit_filter_rules(tsk, &e->rule, NULL, &state)) {
  87. if (state == AUDIT_STATE_RECORD)
  88. *key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
  89. read_unlock(&auditsc_lock);
  90. return state;
  91. }
  92. }
  93. read_unlock(&auditsc_lock);
  94. return AUDIT_BUILD_CONTEXT;
  95. }
  96. Here the list is searched under the lock, but the lock is dropped before
  97. the corresponding value is returned. By the time that this value is acted
  98. on, the list may well have been modified. This makes sense, since if
  99. you are turning auditing off, it is OK to audit a few extra system calls.
  100. This means that RCU can be easily applied to the read side, as follows::
  101. static enum audit_state audit_filter_task(struct task_struct *tsk, char **key)
  102. {
  103. struct audit_entry *e;
  104. enum audit_state state;
  105. rcu_read_lock();
  106. /* Note: audit_filter_mutex held by caller. */
  107. list_for_each_entry_rcu(e, &audit_tsklist, list) {
  108. if (audit_filter_rules(tsk, &e->rule, NULL, &state)) {
  109. if (state == AUDIT_STATE_RECORD)
  110. *key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
  111. rcu_read_unlock();
  112. return state;
  113. }
  114. }
  115. rcu_read_unlock();
  116. return AUDIT_BUILD_CONTEXT;
  117. }
  118. The read_lock() and read_unlock() calls have become rcu_read_lock()
  119. and rcu_read_unlock(), respectively, and the list_for_each_entry()
  120. has become list_for_each_entry_rcu(). The **_rcu()** list-traversal
  121. primitives add READ_ONCE() and diagnostic checks for incorrect use
  122. outside of an RCU read-side critical section.
  123. The changes to the update side are also straightforward. A reader-writer lock
  124. might be used as follows for deletion and insertion in these simplified
  125. versions of audit_del_rule() and audit_add_rule()::
  126. static inline int audit_del_rule(struct audit_rule *rule,
  127. struct list_head *list)
  128. {
  129. struct audit_entry *e;
  130. write_lock(&auditsc_lock);
  131. list_for_each_entry(e, list, list) {
  132. if (!audit_compare_rule(rule, &e->rule)) {
  133. list_del(&e->list);
  134. write_unlock(&auditsc_lock);
  135. return 0;
  136. }
  137. }
  138. write_unlock(&auditsc_lock);
  139. return -EFAULT; /* No matching rule */
  140. }
  141. static inline int audit_add_rule(struct audit_entry *entry,
  142. struct list_head *list)
  143. {
  144. write_lock(&auditsc_lock);
  145. if (entry->rule.flags & AUDIT_PREPEND) {
  146. entry->rule.flags &= ~AUDIT_PREPEND;
  147. list_add(&entry->list, list);
  148. } else {
  149. list_add_tail(&entry->list, list);
  150. }
  151. write_unlock(&auditsc_lock);
  152. return 0;
  153. }
  154. Following are the RCU equivalents for these two functions::
  155. static inline int audit_del_rule(struct audit_rule *rule,
  156. struct list_head *list)
  157. {
  158. struct audit_entry *e;
  159. /* No need to use the _rcu iterator here, since this is the only
  160. * deletion routine. */
  161. list_for_each_entry(e, list, list) {
  162. if (!audit_compare_rule(rule, &e->rule)) {
  163. list_del_rcu(&e->list);
  164. call_rcu(&e->rcu, audit_free_rule);
  165. return 0;
  166. }
  167. }
  168. return -EFAULT; /* No matching rule */
  169. }
  170. static inline int audit_add_rule(struct audit_entry *entry,
  171. struct list_head *list)
  172. {
  173. if (entry->rule.flags & AUDIT_PREPEND) {
  174. entry->rule.flags &= ~AUDIT_PREPEND;
  175. list_add_rcu(&entry->list, list);
  176. } else {
  177. list_add_tail_rcu(&entry->list, list);
  178. }
  179. return 0;
  180. }
  181. Normally, the write_lock() and write_unlock() would be replaced by a
  182. spin_lock() and a spin_unlock(). But in this case, all callers hold
  183. ``audit_filter_mutex``, so no additional locking is required. The
  184. auditsc_lock can therefore be eliminated, since use of RCU eliminates the
  185. need for writers to exclude readers.
  186. The list_del(), list_add(), and list_add_tail() primitives have been
  187. replaced by list_del_rcu(), list_add_rcu(), and list_add_tail_rcu().
  188. The **_rcu()** list-manipulation primitives add memory barriers that are
  189. needed on weakly ordered CPUs. The list_del_rcu() primitive omits the
  190. pointer poisoning debug-assist code that would otherwise cause concurrent
  191. readers to fail spectacularly.
  192. So, when readers can tolerate stale data and when entries are either added or
  193. deleted, without in-place modification, it is very easy to use RCU!
  194. Example 3: Handling In-Place Updates
  195. ------------------------------------
  196. The system-call auditing code does not update auditing rules in place. However,
  197. if it did, the reader-writer-locked code to do so might look as follows
  198. (assuming only ``field_count`` is updated, otherwise, the added fields would
  199. need to be filled in)::
  200. static inline int audit_upd_rule(struct audit_rule *rule,
  201. struct list_head *list,
  202. __u32 newaction,
  203. __u32 newfield_count)
  204. {
  205. struct audit_entry *e;
  206. struct audit_entry *ne;
  207. write_lock(&auditsc_lock);
  208. /* Note: audit_filter_mutex held by caller. */
  209. list_for_each_entry(e, list, list) {
  210. if (!audit_compare_rule(rule, &e->rule)) {
  211. e->rule.action = newaction;
  212. e->rule.field_count = newfield_count;
  213. write_unlock(&auditsc_lock);
  214. return 0;
  215. }
  216. }
  217. write_unlock(&auditsc_lock);
  218. return -EFAULT; /* No matching rule */
  219. }
  220. The RCU version creates a copy, updates the copy, then replaces the old
  221. entry with the newly updated entry. This sequence of actions, allowing
  222. concurrent reads while making a copy to perform an update, is what gives
  223. RCU (*read-copy update*) its name.
  224. The RCU version of audit_upd_rule() is as follows::
  225. static inline int audit_upd_rule(struct audit_rule *rule,
  226. struct list_head *list,
  227. __u32 newaction,
  228. __u32 newfield_count)
  229. {
  230. struct audit_entry *e;
  231. struct audit_entry *ne;
  232. list_for_each_entry(e, list, list) {
  233. if (!audit_compare_rule(rule, &e->rule)) {
  234. ne = kmalloc(sizeof(*entry), GFP_ATOMIC);
  235. if (ne == NULL)
  236. return -ENOMEM;
  237. audit_copy_rule(&ne->rule, &e->rule);
  238. ne->rule.action = newaction;
  239. ne->rule.field_count = newfield_count;
  240. list_replace_rcu(&e->list, &ne->list);
  241. call_rcu(&e->rcu, audit_free_rule);
  242. return 0;
  243. }
  244. }
  245. return -EFAULT; /* No matching rule */
  246. }
  247. Again, this assumes that the caller holds ``audit_filter_mutex``. Normally, the
  248. writer lock would become a spinlock in this sort of code.
  249. The update_lsm_rule() does something very similar, for those who would
  250. prefer to look at real Linux-kernel code.
  251. Another use of this pattern can be found in the openswitch driver's *connection
  252. tracking table* code in ``ct_limit_set()``. The table holds connection tracking
  253. entries and has a limit on the maximum entries. There is one such table
  254. per-zone and hence one *limit* per zone. The zones are mapped to their limits
  255. through a hashtable using an RCU-managed hlist for the hash chains. When a new
  256. limit is set, a new limit object is allocated and ``ct_limit_set()`` is called
  257. to replace the old limit object with the new one using list_replace_rcu().
  258. The old limit object is then freed after a grace period using kfree_rcu().
  259. Example 4: Eliminating Stale Data
  260. ---------------------------------
  261. The auditing example above tolerates stale data, as do most algorithms
  262. that are tracking external state. After all, given there is a delay
  263. from the time the external state changes before Linux becomes aware
  264. of the change, and so as noted earlier, a small quantity of additional
  265. RCU-induced staleness is generally not a problem.
  266. However, there are many examples where stale data cannot be tolerated.
  267. One example in the Linux kernel is the System V IPC (see the shm_lock()
  268. function in ipc/shm.c). This code checks a *deleted* flag under a
  269. per-entry spinlock, and, if the *deleted* flag is set, pretends that the
  270. entry does not exist. For this to be helpful, the search function must
  271. return holding the per-entry spinlock, as shm_lock() does in fact do.
  272. .. _quick_quiz:
  273. Quick Quiz:
  274. For the deleted-flag technique to be helpful, why is it necessary
  275. to hold the per-entry lock while returning from the search function?
  276. :ref:`Answer to Quick Quiz <quick_quiz_answer>`
  277. If the system-call audit module were to ever need to reject stale data, one way
  278. to accomplish this would be to add a ``deleted`` flag and a ``lock`` spinlock to the
  279. ``audit_entry`` structure, and modify audit_filter_task() as follows::
  280. static enum audit_state audit_filter_task(struct task_struct *tsk)
  281. {
  282. struct audit_entry *e;
  283. enum audit_state state;
  284. rcu_read_lock();
  285. list_for_each_entry_rcu(e, &audit_tsklist, list) {
  286. if (audit_filter_rules(tsk, &e->rule, NULL, &state)) {
  287. spin_lock(&e->lock);
  288. if (e->deleted) {
  289. spin_unlock(&e->lock);
  290. rcu_read_unlock();
  291. return AUDIT_BUILD_CONTEXT;
  292. }
  293. rcu_read_unlock();
  294. if (state == AUDIT_STATE_RECORD)
  295. *key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
  296. return state;
  297. }
  298. }
  299. rcu_read_unlock();
  300. return AUDIT_BUILD_CONTEXT;
  301. }
  302. The ``audit_del_rule()`` function would need to set the ``deleted`` flag under the
  303. spinlock as follows::
  304. static inline int audit_del_rule(struct audit_rule *rule,
  305. struct list_head *list)
  306. {
  307. struct audit_entry *e;
  308. /* No need to use the _rcu iterator here, since this
  309. * is the only deletion routine. */
  310. list_for_each_entry(e, list, list) {
  311. if (!audit_compare_rule(rule, &e->rule)) {
  312. spin_lock(&e->lock);
  313. list_del_rcu(&e->list);
  314. e->deleted = 1;
  315. spin_unlock(&e->lock);
  316. call_rcu(&e->rcu, audit_free_rule);
  317. return 0;
  318. }
  319. }
  320. return -EFAULT; /* No matching rule */
  321. }
  322. This too assumes that the caller holds ``audit_filter_mutex``.
  323. Note that this example assumes that entries are only added and deleted.
  324. Additional mechanism is required to deal correctly with the update-in-place
  325. performed by audit_upd_rule(). For one thing, audit_upd_rule() would
  326. need to hold the locks of both the old ``audit_entry`` and its replacement
  327. while executing the list_replace_rcu().
  328. Example 5: Skipping Stale Objects
  329. ---------------------------------
  330. For some use cases, reader performance can be improved by skipping
  331. stale objects during read-side list traversal, where stale objects
  332. are those that will be removed and destroyed after one or more grace
  333. periods. One such example can be found in the timerfd subsystem. When a
  334. ``CLOCK_REALTIME`` clock is reprogrammed (for example due to setting
  335. of the system time) then all programmed ``timerfds`` that depend on
  336. this clock get triggered and processes waiting on them are awakened in
  337. advance of their scheduled expiry. To facilitate this, all such timers
  338. are added to an RCU-managed ``cancel_list`` when they are setup in
  339. ``timerfd_setup_cancel()``::
  340. static void timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags)
  341. {
  342. spin_lock(&ctx->cancel_lock);
  343. if ((ctx->clockid == CLOCK_REALTIME ||
  344. ctx->clockid == CLOCK_REALTIME_ALARM) &&
  345. (flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) {
  346. if (!ctx->might_cancel) {
  347. ctx->might_cancel = true;
  348. spin_lock(&cancel_lock);
  349. list_add_rcu(&ctx->clist, &cancel_list);
  350. spin_unlock(&cancel_lock);
  351. }
  352. } else {
  353. __timerfd_remove_cancel(ctx);
  354. }
  355. spin_unlock(&ctx->cancel_lock);
  356. }
  357. When a timerfd is freed (fd is closed), then the ``might_cancel``
  358. flag of the timerfd object is cleared, the object removed from the
  359. ``cancel_list`` and destroyed, as shown in this simplified and inlined
  360. version of timerfd_release()::
  361. int timerfd_release(struct inode *inode, struct file *file)
  362. {
  363. struct timerfd_ctx *ctx = file->private_data;
  364. spin_lock(&ctx->cancel_lock);
  365. if (ctx->might_cancel) {
  366. ctx->might_cancel = false;
  367. spin_lock(&cancel_lock);
  368. list_del_rcu(&ctx->clist);
  369. spin_unlock(&cancel_lock);
  370. }
  371. spin_unlock(&ctx->cancel_lock);
  372. if (isalarm(ctx))
  373. alarm_cancel(&ctx->t.alarm);
  374. else
  375. hrtimer_cancel(&ctx->t.tmr);
  376. kfree_rcu(ctx, rcu);
  377. return 0;
  378. }
  379. If the ``CLOCK_REALTIME`` clock is set, for example by a time server, the
  380. hrtimer framework calls ``timerfd_clock_was_set()`` which walks the
  381. ``cancel_list`` and wakes up processes waiting on the timerfd. While iterating
  382. the ``cancel_list``, the ``might_cancel`` flag is consulted to skip stale
  383. objects::
  384. void timerfd_clock_was_set(void)
  385. {
  386. ktime_t moffs = ktime_mono_to_real(0);
  387. struct timerfd_ctx *ctx;
  388. unsigned long flags;
  389. rcu_read_lock();
  390. list_for_each_entry_rcu(ctx, &cancel_list, clist) {
  391. if (!ctx->might_cancel)
  392. continue;
  393. spin_lock_irqsave(&ctx->wqh.lock, flags);
  394. if (ctx->moffs != moffs) {
  395. ctx->moffs = KTIME_MAX;
  396. ctx->ticks++;
  397. wake_up_locked_poll(&ctx->wqh, EPOLLIN);
  398. }
  399. spin_unlock_irqrestore(&ctx->wqh.lock, flags);
  400. }
  401. rcu_read_unlock();
  402. }
  403. The key point is that because RCU-protected traversal of the
  404. ``cancel_list`` happens concurrently with object addition and removal,
  405. sometimes the traversal can access an object that has been removed from
  406. the list. In this example, a flag is used to skip such objects.
  407. Summary
  408. -------
  409. Read-mostly list-based data structures that can tolerate stale data are
  410. the most amenable to use of RCU. The simplest case is where entries are
  411. either added or deleted from the data structure (or atomically modified
  412. in place), but non-atomic in-place modifications can be handled by making
  413. a copy, updating the copy, then replacing the original with the copy.
  414. If stale data cannot be tolerated, then a *deleted* flag may be used
  415. in conjunction with a per-entry spinlock in order to allow the search
  416. function to reject newly deleted data.
  417. .. _quick_quiz_answer:
  418. Answer to Quick Quiz:
  419. For the deleted-flag technique to be helpful, why is it necessary
  420. to hold the per-entry lock while returning from the search function?
  421. If the search function drops the per-entry lock before returning,
  422. then the caller will be processing stale data in any case. If it
  423. is really OK to be processing stale data, then you don't need a
  424. *deleted* flag. If processing stale data really is a problem,
  425. then you need to hold the per-entry lock across all of the code
  426. that uses the value that was returned.
  427. :ref:`Back to Quick Quiz <quick_quiz>`