2
0

rcu.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. Using RCU (Read-Copy-Update) for synchronization
  2. ================================================
  3. Read-copy update (RCU) is a synchronization mechanism that is used to
  4. protect read-mostly data structures. RCU is very efficient and scalable
  5. on the read side (it is wait-free), and thus can make the read paths
  6. extremely fast.
  7. RCU supports concurrency between a single writer and multiple readers,
  8. thus it is not used alone. Typically, the write-side will use a lock to
  9. serialize multiple updates, but other approaches are possible (e.g.,
  10. restricting updates to a single task). In QEMU, when a lock is used,
  11. this will often be the "iothread mutex", also known as the "big QEMU
  12. lock" (BQL). Also, restricting updates to a single task is done in
  13. QEMU using the "bottom half" API.
  14. RCU is fundamentally a "wait-to-finish" mechanism. The read side marks
  15. sections of code with "critical sections", and the update side will wait
  16. for the execution of all *currently running* critical sections before
  17. proceeding, or before asynchronously executing a callback.
  18. The key point here is that only the currently running critical sections
  19. are waited for; critical sections that are started **after** the beginning
  20. of the wait do not extend the wait, despite running concurrently with
  21. the updater. This is the reason why RCU is more scalable than,
  22. for example, reader-writer locks. It is so much more scalable that
  23. the system will have a single instance of the RCU mechanism; a single
  24. mechanism can be used for an arbitrary number of "things", without
  25. having to worry about things such as contention or deadlocks.
  26. How is this possible? The basic idea is to split updates in two phases,
  27. "removal" and "reclamation". During removal, we ensure that subsequent
  28. readers will not be able to get a reference to the old data. After
  29. removal has completed, a critical section will not be able to access
  30. the old data. Therefore, critical sections that begin after removal
  31. do not matter; as soon as all previous critical sections have finished,
  32. there cannot be any readers who hold references to the data structure,
  33. and these can now be safely reclaimed (e.g., freed or unref'ed).
  34. Here is a picture::
  35. thread 1 thread 2 thread 3
  36. ------------------- ------------------------ -------------------
  37. enter RCU crit.sec.
  38. | finish removal phase
  39. | begin wait
  40. | | enter RCU crit.sec.
  41. exit RCU crit.sec | |
  42. complete wait |
  43. begin reclamation phase |
  44. exit RCU crit.sec.
  45. Note how thread 3 is still executing its critical section when thread 2
  46. starts reclaiming data. This is possible, because the old version of the
  47. data structure was not accessible at the time thread 3 began executing
  48. that critical section.
  49. RCU API
  50. -------
  51. The core RCU API is small:
  52. ``void rcu_read_lock(void);``
  53. Used by a reader to inform the reclaimer that the reader is
  54. entering an RCU read-side critical section.
  55. ``void rcu_read_unlock(void);``
  56. Used by a reader to inform the reclaimer that the reader is
  57. exiting an RCU read-side critical section. Note that RCU
  58. read-side critical sections may be nested and/or overlapping.
  59. ``void synchronize_rcu(void);``
  60. Blocks until all pre-existing RCU read-side critical sections
  61. on all threads have completed. This marks the end of the removal
  62. phase and the beginning of reclamation phase.
  63. Note that it would be valid for another update to come while
  64. ``synchronize_rcu`` is running. Because of this, it is better that
  65. the updater releases any locks it may hold before calling
  66. ``synchronize_rcu``. If this is not possible (for example, because
  67. the updater is protected by the BQL), you can use ``call_rcu``.
  68. ``void call_rcu1(struct rcu_head * head, void (*func)(struct rcu_head *head));``
  69. This function invokes ``func(head)`` after all pre-existing RCU
  70. read-side critical sections on all threads have completed. This
  71. marks the end of the removal phase, with func taking care
  72. asynchronously of the reclamation phase.
  73. The ``foo`` struct needs to have an ``rcu_head`` structure added,
  74. perhaps as follows::
  75. struct foo {
  76. struct rcu_head rcu;
  77. int a;
  78. char b;
  79. long c;
  80. };
  81. so that the reclaimer function can fetch the ``struct foo`` address
  82. and free it::
  83. call_rcu1(&foo.rcu, foo_reclaim);
  84. void foo_reclaim(struct rcu_head *rp)
  85. {
  86. struct foo *fp = container_of(rp, struct foo, rcu);
  87. g_free(fp);
  88. }
  89. ``call_rcu1`` is typically used via either the ``call_rcu`` or
  90. ``g_free_rcu`` macros, which handle the common case where the
  91. ``rcu_head`` member is the first of the struct.
  92. ``void call_rcu(T *p, void (*func)(T *p), field-name);``
  93. If the ``struct rcu_head`` is the first field in the struct, you can
  94. use this macro instead of ``call_rcu1``.
  95. ``void g_free_rcu(T *p, field-name);``
  96. This is a special-case version of ``call_rcu`` where the callback
  97. function is ``g_free``.
  98. In the example given in ``call_rcu1``, one could have written simply::
  99. g_free_rcu(&foo, rcu);
  100. ``typeof(*p) qatomic_rcu_read(p);``
  101. ``qatomic_rcu_read()`` is similar to ``qatomic_load_acquire()``, but
  102. it makes some assumptions on the code that calls it. This allows a
  103. more optimized implementation.
  104. ``qatomic_rcu_read`` assumes that whenever a single RCU critical
  105. section reads multiple shared data, these reads are either
  106. data-dependent or need no ordering. This is almost always the
  107. case when using RCU, because read-side critical sections typically
  108. navigate one or more pointers (the pointers that are changed on
  109. every update) until reaching a data structure of interest,
  110. and then read from there.
  111. RCU read-side critical sections must use ``qatomic_rcu_read()`` to
  112. read data, unless concurrent writes are prevented by another
  113. synchronization mechanism.
  114. Furthermore, RCU read-side critical sections should traverse the
  115. data structure in a single direction, opposite to the direction
  116. in which the updater initializes it.
  117. ``void qatomic_rcu_set(p, typeof(*p) v);``
  118. ``qatomic_rcu_set()`` is similar to ``qatomic_store_release()``,
  119. though it also makes assumptions on the code that calls it in
  120. order to allow a more optimized implementation.
  121. In particular, ``qatomic_rcu_set()`` suffices for synchronization
  122. with readers, if the updater never mutates a field within a
  123. data item that is already accessible to readers. This is the
  124. case when initializing a new copy of the RCU-protected data
  125. structure; just ensure that initialization of ``*p`` is carried out
  126. before ``qatomic_rcu_set()`` makes the data item visible to readers.
  127. If this rule is observed, writes will happen in the opposite
  128. order as reads in the RCU read-side critical sections (or if
  129. there is just one update), and there will be no need for other
  130. synchronization mechanism to coordinate the accesses.
  131. The following APIs must be used before RCU is used in a thread:
  132. ``void rcu_register_thread(void);``
  133. Mark a thread as taking part in the RCU mechanism. Such a thread
  134. will have to report quiescent points regularly, either manually
  135. or through the ``QemuCond``/``QemuSemaphore``/``QemuEvent`` APIs.
  136. ``void rcu_unregister_thread(void);``
  137. Mark a thread as not taking part anymore in the RCU mechanism.
  138. It is not a problem if such a thread reports quiescent points,
  139. either manually or by using the
  140. ``QemuCond``/``QemuSemaphore``/``QemuEvent`` APIs.
  141. Note that these APIs are relatively heavyweight, and should **not** be
  142. nested.
  143. Convenience macros
  144. ------------------
  145. Two macros are provided that automatically release the read lock at the
  146. end of the scope.
  147. ``RCU_READ_LOCK_GUARD()``
  148. Takes the lock and will release it at the end of the block it's
  149. used in.
  150. ``WITH_RCU_READ_LOCK_GUARD() { code }``
  151. Is used at the head of a block to protect the code within the block.
  152. Note that a ``goto`` out of the guarded block will also drop the lock.
  153. Differences with Linux
  154. ----------------------
  155. - Waiting on a mutex is possible, though discouraged, within an RCU critical
  156. section. This is because spinlocks are rarely (if ever) used in userspace
  157. programming; not allowing this would prevent upgrading an RCU read-side
  158. critical section to become an updater.
  159. - ``qatomic_rcu_read`` and ``qatomic_rcu_set`` replace ``rcu_dereference`` and
  160. ``rcu_assign_pointer``. They take a **pointer** to the variable being accessed.
  161. - ``call_rcu`` is a macro that has an extra argument (the name of the first
  162. field in the struct, which must be a struct ``rcu_head``), and expects the
  163. type of the callback's argument to be the type of the first argument.
  164. ``call_rcu1`` is the same as Linux's ``call_rcu``.
  165. RCU Patterns
  166. ------------
  167. Many patterns using read-writer locks translate directly to RCU, with
  168. the advantages of higher scalability and deadlock immunity.
  169. In general, RCU can be used whenever it is possible to create a new
  170. "version" of a data structure every time the updater runs. This may
  171. sound like a very strict restriction, however:
  172. - the updater does not mean "everything that writes to a data structure",
  173. but rather "everything that involves a reclamation step". See the
  174. array example below
  175. - in some cases, creating a new version of a data structure may actually
  176. be very cheap. For example, modifying the "next" pointer of a singly
  177. linked list is effectively creating a new version of the list.
  178. Here are some frequently-used RCU idioms that are worth noting.
  179. RCU list processing
  180. ^^^^^^^^^^^^^^^^^^^
  181. TBD (not yet used in QEMU)
  182. RCU reference counting
  183. ^^^^^^^^^^^^^^^^^^^^^^
  184. Because grace periods are not allowed to complete while there is an RCU
  185. read-side critical section in progress, the RCU read-side primitives
  186. may be used as a restricted reference-counting mechanism. For example,
  187. consider the following code fragment::
  188. rcu_read_lock();
  189. p = qatomic_rcu_read(&foo);
  190. /* do something with p. */
  191. rcu_read_unlock();
  192. The RCU read-side critical section ensures that the value of ``p`` remains
  193. valid until after the ``rcu_read_unlock()``. In some sense, it is acquiring
  194. a reference to ``p`` that is later released when the critical section ends.
  195. The write side looks simply like this (with appropriate locking)::
  196. qemu_mutex_lock(&foo_mutex);
  197. old = foo;
  198. qatomic_rcu_set(&foo, new);
  199. qemu_mutex_unlock(&foo_mutex);
  200. synchronize_rcu();
  201. free(old);
  202. If the processing cannot be done purely within the critical section, it
  203. is possible to combine this idiom with a "real" reference count::
  204. rcu_read_lock();
  205. p = qatomic_rcu_read(&foo);
  206. foo_ref(p);
  207. rcu_read_unlock();
  208. /* do something with p. */
  209. foo_unref(p);
  210. The write side can be like this::
  211. qemu_mutex_lock(&foo_mutex);
  212. old = foo;
  213. qatomic_rcu_set(&foo, new);
  214. qemu_mutex_unlock(&foo_mutex);
  215. synchronize_rcu();
  216. foo_unref(old);
  217. or with ``call_rcu``::
  218. qemu_mutex_lock(&foo_mutex);
  219. old = foo;
  220. qatomic_rcu_set(&foo, new);
  221. qemu_mutex_unlock(&foo_mutex);
  222. call_rcu(foo_unref, old, rcu);
  223. In both cases, the write side only performs removal. Reclamation
  224. happens when the last reference to a ``foo`` object is dropped.
  225. Using ``synchronize_rcu()`` is undesirably expensive, because the
  226. last reference may be dropped on the read side. Hence you can
  227. use ``call_rcu()`` instead::
  228. foo_unref(struct foo *p) {
  229. if (qatomic_fetch_dec(&p->refcount) == 1) {
  230. call_rcu(foo_destroy, p, rcu);
  231. }
  232. }
  233. Note that the same idioms would be possible with reader/writer
  234. locks::
  235. read_lock(&foo_rwlock); write_mutex_lock(&foo_rwlock);
  236. p = foo; p = foo;
  237. /* do something with p. */ foo = new;
  238. read_unlock(&foo_rwlock); free(p);
  239. write_mutex_unlock(&foo_rwlock);
  240. free(p);
  241. ------------------------------------------------------------------
  242. read_lock(&foo_rwlock); write_mutex_lock(&foo_rwlock);
  243. p = foo; old = foo;
  244. foo_ref(p); foo = new;
  245. read_unlock(&foo_rwlock); foo_unref(old);
  246. /* do something with p. */ write_mutex_unlock(&foo_rwlock);
  247. read_lock(&foo_rwlock);
  248. foo_unref(p);
  249. read_unlock(&foo_rwlock);
  250. ``foo_unref`` could use a mechanism such as bottom halves to move deallocation
  251. out of the write-side critical section.
  252. RCU resizable arrays
  253. ^^^^^^^^^^^^^^^^^^^^
  254. Resizable arrays can be used with RCU. The expensive RCU synchronization
  255. (or ``call_rcu``) only needs to take place when the array is resized.
  256. The two items to take care of are:
  257. - ensuring that the old version of the array is available between removal
  258. and reclamation;
  259. - avoiding mismatches in the read side between the array data and the
  260. array size.
  261. The first problem is avoided simply by not using ``realloc``. Instead,
  262. each resize will allocate a new array and copy the old data into it.
  263. The second problem would arise if the size and the data pointers were
  264. two members of a larger struct::
  265. struct mystuff {
  266. ...
  267. int data_size;
  268. int data_alloc;
  269. T *data;
  270. ...
  271. };
  272. Instead, we store the size of the array with the array itself::
  273. struct arr {
  274. int size;
  275. int alloc;
  276. T data[];
  277. };
  278. struct arr *global_array;
  279. read side:
  280. rcu_read_lock();
  281. struct arr *array = qatomic_rcu_read(&global_array);
  282. x = i < array->size ? array->data[i] : -1;
  283. rcu_read_unlock();
  284. return x;
  285. write side (running under a lock):
  286. if (global_array->size == global_array->alloc) {
  287. /* Creating a new version. */
  288. new_array = g_malloc(sizeof(struct arr) +
  289. global_array->alloc * 2 * sizeof(T));
  290. new_array->size = global_array->size;
  291. new_array->alloc = global_array->alloc * 2;
  292. memcpy(new_array->data, global_array->data,
  293. global_array->alloc * sizeof(T));
  294. /* Removal phase. */
  295. old_array = global_array;
  296. qatomic_rcu_set(&global_array, new_array);
  297. synchronize_rcu();
  298. /* Reclamation phase. */
  299. free(old_array);
  300. }
  301. References
  302. ----------
  303. * The `Linux kernel RCU documentation <https://docs.kernel.org/RCU/>`__