rcu.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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,
  69. void (*func)(struct rcu_head *head));
  70. This function invokes func(head) after all pre-existing RCU
  71. read-side critical sections on all threads have completed. This
  72. marks the end of the removal phase, with func taking care
  73. asynchronously of the reclamation phase.
  74. The foo struct needs to have an rcu_head structure added,
  75. perhaps as follows:
  76. struct foo {
  77. struct rcu_head rcu;
  78. int a;
  79. char b;
  80. long c;
  81. };
  82. so that the reclaimer function can fetch the struct foo address
  83. and free it:
  84. call_rcu1(&foo.rcu, foo_reclaim);
  85. void foo_reclaim(struct rcu_head *rp)
  86. {
  87. struct foo *fp = container_of(rp, struct foo, rcu);
  88. g_free(fp);
  89. }
  90. For the common case where the rcu_head member is the first of the
  91. struct, you can use the following macro.
  92. void call_rcu(T *p,
  93. void (*func)(T *p),
  94. field-name);
  95. void g_free_rcu(T *p,
  96. field-name);
  97. call_rcu1 is typically used through these macro, in the common case
  98. where the "struct rcu_head" is the first field in the struct. If
  99. the callback function is g_free, in particular, g_free_rcu can be
  100. used. In the above case, one could have written simply:
  101. g_free_rcu(&foo, rcu);
  102. typeof(*p) atomic_rcu_read(p);
  103. atomic_rcu_read() is similar to atomic_load_acquire(), but it makes
  104. some assumptions on the code that calls it. This allows a more
  105. optimized implementation.
  106. atomic_rcu_read assumes that whenever a single RCU critical
  107. section reads multiple shared data, these reads are either
  108. data-dependent or need no ordering. This is almost always the
  109. case when using RCU, because read-side critical sections typically
  110. navigate one or more pointers (the pointers that are changed on
  111. every update) until reaching a data structure of interest,
  112. and then read from there.
  113. RCU read-side critical sections must use atomic_rcu_read() to
  114. read data, unless concurrent writes are prevented by another
  115. synchronization mechanism.
  116. Furthermore, RCU read-side critical sections should traverse the
  117. data structure in a single direction, opposite to the direction
  118. in which the updater initializes it.
  119. void atomic_rcu_set(p, typeof(*p) v);
  120. atomic_rcu_set() is similar to atomic_store_release(), though it also
  121. makes assumptions on the code that calls it in order to allow a more
  122. optimized implementation.
  123. In particular, atomic_rcu_set() suffices for synchronization
  124. with readers, if the updater never mutates a field within a
  125. data item that is already accessible to readers. This is the
  126. case when initializing a new copy of the RCU-protected data
  127. structure; just ensure that initialization of *p is carried out
  128. before atomic_rcu_set() makes the data item visible to readers.
  129. If this rule is observed, writes will happen in the opposite
  130. order as reads in the RCU read-side critical sections (or if
  131. there is just one update), and there will be no need for other
  132. synchronization mechanism to coordinate the accesses.
  133. The following APIs must be used before RCU is used in a thread:
  134. void rcu_register_thread(void);
  135. Mark a thread as taking part in the RCU mechanism. Such a thread
  136. will have to report quiescent points regularly, either manually
  137. or through the QemuCond/QemuSemaphore/QemuEvent APIs.
  138. void rcu_unregister_thread(void);
  139. Mark a thread as not taking part anymore in the RCU mechanism.
  140. It is not a problem if such a thread reports quiescent points,
  141. either manually or by using the QemuCond/QemuSemaphore/QemuEvent
  142. APIs.
  143. Note that these APIs are relatively heavyweight, and should _not_ be
  144. nested.
  145. Convenience macros
  146. ==================
  147. Two macros are provided that automatically release the read lock at the
  148. end of the scope.
  149. RCU_READ_LOCK_GUARD()
  150. Takes the lock and will release it at the end of the block it's
  151. used in.
  152. WITH_RCU_READ_LOCK_GUARD() { code }
  153. Is used at the head of a block to protect the code within the block.
  154. Note that 'goto'ing out of the guarded block will also drop the lock.
  155. DIFFERENCES WITH LINUX
  156. ======================
  157. - Waiting on a mutex is possible, though discouraged, within an RCU critical
  158. section. This is because spinlocks are rarely (if ever) used in userspace
  159. programming; not allowing this would prevent upgrading an RCU read-side
  160. critical section to become an updater.
  161. - atomic_rcu_read and atomic_rcu_set replace rcu_dereference and
  162. rcu_assign_pointer. They take a _pointer_ to the variable being accessed.
  163. - call_rcu is a macro that has an extra argument (the name of the first
  164. field in the struct, which must be a struct rcu_head), and expects the
  165. type of the callback's argument to be the type of the first argument.
  166. call_rcu1 is the same as Linux's call_rcu.
  167. RCU PATTERNS
  168. ============
  169. Many patterns using read-writer locks translate directly to RCU, with
  170. the advantages of higher scalability and deadlock immunity.
  171. In general, RCU can be used whenever it is possible to create a new
  172. "version" of a data structure every time the updater runs. This may
  173. sound like a very strict restriction, however:
  174. - the updater does not mean "everything that writes to a data structure",
  175. but rather "everything that involves a reclamation step". See the
  176. array example below
  177. - in some cases, creating a new version of a data structure may actually
  178. be very cheap. For example, modifying the "next" pointer of a singly
  179. linked list is effectively creating a new version of the list.
  180. Here are some frequently-used RCU idioms that are worth noting.
  181. RCU list processing
  182. -------------------
  183. TBD (not yet used in QEMU)
  184. RCU reference counting
  185. ----------------------
  186. Because grace periods are not allowed to complete while there is an RCU
  187. read-side critical section in progress, the RCU read-side primitives
  188. may be used as a restricted reference-counting mechanism. For example,
  189. consider the following code fragment:
  190. rcu_read_lock();
  191. p = atomic_rcu_read(&foo);
  192. /* do something with p. */
  193. rcu_read_unlock();
  194. The RCU read-side critical section ensures that the value of "p" remains
  195. valid until after the rcu_read_unlock(). In some sense, it is acquiring
  196. a reference to p that is later released when the critical section ends.
  197. The write side looks simply like this (with appropriate locking):
  198. qemu_mutex_lock(&foo_mutex);
  199. old = foo;
  200. atomic_rcu_set(&foo, new);
  201. qemu_mutex_unlock(&foo_mutex);
  202. synchronize_rcu();
  203. free(old);
  204. If the processing cannot be done purely within the critical section, it
  205. is possible to combine this idiom with a "real" reference count:
  206. rcu_read_lock();
  207. p = atomic_rcu_read(&foo);
  208. foo_ref(p);
  209. rcu_read_unlock();
  210. /* do something with p. */
  211. foo_unref(p);
  212. The write side can be like this:
  213. qemu_mutex_lock(&foo_mutex);
  214. old = foo;
  215. atomic_rcu_set(&foo, new);
  216. qemu_mutex_unlock(&foo_mutex);
  217. synchronize_rcu();
  218. foo_unref(old);
  219. or with call_rcu:
  220. qemu_mutex_lock(&foo_mutex);
  221. old = foo;
  222. atomic_rcu_set(&foo, new);
  223. qemu_mutex_unlock(&foo_mutex);
  224. call_rcu(foo_unref, old, rcu);
  225. In both cases, the write side only performs removal. Reclamation
  226. happens when the last reference to a "foo" object is dropped.
  227. Using synchronize_rcu() is undesirably expensive, because the
  228. last reference may be dropped on the read side. Hence you can
  229. use call_rcu() instead:
  230. foo_unref(struct foo *p) {
  231. if (atomic_fetch_dec(&p->refcount) == 1) {
  232. call_rcu(foo_destroy, p, rcu);
  233. }
  234. }
  235. Note that the same idioms would be possible with reader/writer
  236. locks:
  237. read_lock(&foo_rwlock); write_mutex_lock(&foo_rwlock);
  238. p = foo; p = foo;
  239. /* do something with p. */ foo = new;
  240. read_unlock(&foo_rwlock); free(p);
  241. write_mutex_unlock(&foo_rwlock);
  242. free(p);
  243. ------------------------------------------------------------------
  244. read_lock(&foo_rwlock); write_mutex_lock(&foo_rwlock);
  245. p = foo; old = foo;
  246. foo_ref(p); foo = new;
  247. read_unlock(&foo_rwlock); foo_unref(old);
  248. /* do something with p. */ write_mutex_unlock(&foo_rwlock);
  249. read_lock(&foo_rwlock);
  250. foo_unref(p);
  251. read_unlock(&foo_rwlock);
  252. foo_unref could use a mechanism such as bottom halves to move deallocation
  253. out of the write-side critical section.
  254. RCU resizable arrays
  255. --------------------
  256. Resizable arrays can be used with RCU. The expensive RCU synchronization
  257. (or call_rcu) only needs to take place when the array is resized.
  258. The two items to take care of are:
  259. - ensuring that the old version of the array is available between removal
  260. and reclamation;
  261. - avoiding mismatches in the read side between the array data and the
  262. array size.
  263. The first problem is avoided simply by not using realloc. Instead,
  264. each resize will allocate a new array and copy the old data into it.
  265. The second problem would arise if the size and the data pointers were
  266. two members of a larger struct:
  267. struct mystuff {
  268. ...
  269. int data_size;
  270. int data_alloc;
  271. T *data;
  272. ...
  273. };
  274. Instead, we store the size of the array with the array itself:
  275. struct arr {
  276. int size;
  277. int alloc;
  278. T data[];
  279. };
  280. struct arr *global_array;
  281. read side:
  282. rcu_read_lock();
  283. struct arr *array = atomic_rcu_read(&global_array);
  284. x = i < array->size ? array->data[i] : -1;
  285. rcu_read_unlock();
  286. return x;
  287. write side (running under a lock):
  288. if (global_array->size == global_array->alloc) {
  289. /* Creating a new version. */
  290. new_array = g_malloc(sizeof(struct arr) +
  291. global_array->alloc * 2 * sizeof(T));
  292. new_array->size = global_array->size;
  293. new_array->alloc = global_array->alloc * 2;
  294. memcpy(new_array->data, global_array->data,
  295. global_array->alloc * sizeof(T));
  296. /* Removal phase. */
  297. old_array = global_array;
  298. atomic_rcu_set(&new_array->data, new_array);
  299. synchronize_rcu();
  300. /* Reclamation phase. */
  301. free(old_array);
  302. }
  303. SOURCES
  304. =======
  305. * Documentation/RCU/ from the Linux kernel