1 Using RCU (Read-Copy-Update) for synchronization
2 ================================================
4 Read-copy update (RCU) is a synchronization mechanism that is used to
5 protect read-mostly data structures. RCU is very efficient and scalable
6 on the read side (it is wait-free), and thus can make the read paths
9 RCU supports concurrency between a single writer and multiple readers,
10 thus it is not used alone. Typically, the write-side will use a lock to
11 serialize multiple updates, but other approaches are possible (e.g.,
12 restricting updates to a single task). In QEMU, when a lock is used,
13 this will often be the "iothread mutex", also known as the "big QEMU
14 lock" (BQL). Also, restricting updates to a single task is done in
15 QEMU using the "bottom half" API.
17 RCU is fundamentally a "wait-to-finish" mechanism. The read side marks
18 sections of code with "critical sections", and the update side will wait
19 for the execution of all *currently running* critical sections before
20 proceeding, or before asynchronously executing a callback.
22 The key point here is that only the currently running critical sections
23 are waited for; critical sections that are started _after_ the beginning
24 of the wait do not extend the wait, despite running concurrently with
25 the updater. This is the reason why RCU is more scalable than,
26 for example, reader-writer locks. It is so much more scalable that
27 the system will have a single instance of the RCU mechanism; a single
28 mechanism can be used for an arbitrary number of "things", without
29 having to worry about things such as contention or deadlocks.
31 How is this possible? The basic idea is to split updates in two phases,
32 "removal" and "reclamation". During removal, we ensure that subsequent
33 readers will not be able to get a reference to the old data. After
34 removal has completed, a critical section will not be able to access
35 the old data. Therefore, critical sections that begin after removal
36 do not matter; as soon as all previous critical sections have finished,
37 there cannot be any readers who hold references to the data structure,
38 and these can now be safely reclaimed (e.g., freed or unref'ed).
42 thread 1 thread 2 thread 3
43 ------------------- ------------------------ -------------------
45 | finish removal phase
47 | | enter RCU crit.sec.
50 begin reclamation phase |
54 Note how thread 3 is still executing its critical section when thread 2
55 starts reclaiming data. This is possible, because the old version of the
56 data structure was not accessible at the time thread 3 began executing
57 that critical section.
63 The core RCU API is small:
65 void rcu_read_lock(void);
67 Used by a reader to inform the reclaimer that the reader is
68 entering an RCU read-side critical section.
70 void rcu_read_unlock(void);
72 Used by a reader to inform the reclaimer that the reader is
73 exiting an RCU read-side critical section. Note that RCU
74 read-side critical sections may be nested and/or overlapping.
76 void synchronize_rcu(void);
78 Blocks until all pre-existing RCU read-side critical sections
79 on all threads have completed. This marks the end of the removal
80 phase and the beginning of reclamation phase.
82 Note that it would be valid for another update to come while
83 synchronize_rcu is running. Because of this, it is better that
84 the updater releases any locks it may hold before calling
85 synchronize_rcu. If this is not possible (for example, because
86 the updater is protected by the BQL), you can use call_rcu.
88 void call_rcu1(struct rcu_head * head,
89 void (*func)(struct rcu_head *head));
91 This function invokes func(head) after all pre-existing RCU
92 read-side critical sections on all threads have completed. This
93 marks the end of the removal phase, with func taking care
94 asynchronously of the reclamation phase.
96 The foo struct needs to have an rcu_head structure added,
106 so that the reclaimer function can fetch the struct foo address
109 call_rcu1(&foo.rcu, foo_reclaim);
111 void foo_reclaim(struct rcu_head *rp)
113 struct foo *fp = container_of(rp, struct foo, rcu);
117 For the common case where the rcu_head member is the first of the
118 struct, you can use the following macro.
124 call_rcu1 is typically used through this macro, in the common case
125 where the "struct rcu_head" is the first field in the struct. In
126 the above case, one could have written simply:
128 call_rcu(foo_reclaim, g_free, rcu);
130 typeof(*p) atomic_rcu_read(p);
132 atomic_rcu_read() is similar to atomic_mb_read(), but it makes
133 some assumptions on the code that calls it. This allows a more
134 optimized implementation.
136 atomic_rcu_read assumes that whenever a single RCU critical
137 section reads multiple shared data, these reads are either
138 data-dependent or need no ordering. This is almost always the
139 case when using RCU, because read-side critical sections typically
140 navigate one or more pointers (the pointers that are changed on
141 every update) until reaching a data structure of interest,
142 and then read from there.
144 RCU read-side critical sections must use atomic_rcu_read() to
145 read data, unless concurrent writes are presented by another
146 synchronization mechanism.
148 Furthermore, RCU read-side critical sections should traverse the
149 data structure in a single direction, opposite to the direction
150 in which the updater initializes it.
152 void atomic_rcu_set(p, typeof(*p) v);
154 atomic_rcu_set() is also similar to atomic_mb_set(), and it also
155 makes assumptions on the code that calls it in order to allow a more
156 optimized implementation.
158 In particular, atomic_rcu_set() suffices for synchronization
159 with readers, if the updater never mutates a field within a
160 data item that is already accessible to readers. This is the
161 case when initializing a new copy of the RCU-protected data
162 structure; just ensure that initialization of *p is carried out
163 before atomic_rcu_set() makes the data item visible to readers.
164 If this rule is observed, writes will happen in the opposite
165 order as reads in the RCU read-side critical sections (or if
166 there is just one update), and there will be no need for other
167 synchronization mechanism to coordinate the accesses.
169 The following APIs must be used before RCU is used in a thread:
171 void rcu_register_thread(void);
173 Mark a thread as taking part in the RCU mechanism. Such a thread
174 will have to report quiescent points regularly, either manually
175 or through the QemuCond/QemuSemaphore/QemuEvent APIs.
177 void rcu_unregister_thread(void);
179 Mark a thread as not taking part anymore in the RCU mechanism.
180 It is not a problem if such a thread reports quiescent points,
181 either manually or by using the QemuCond/QemuSemaphore/QemuEvent
184 Note that these APIs are relatively heavyweight, and should _not_ be
188 DIFFERENCES WITH LINUX
189 ======================
191 - Waiting on a mutex is possible, though discouraged, within an RCU critical
192 section. This is because spinlocks are rarely (if ever) used in userspace
193 programming; not allowing this would prevent upgrading an RCU read-side
194 critical section to become an updater.
196 - atomic_rcu_read and atomic_rcu_set replace rcu_dereference and
197 rcu_assign_pointer. They take a _pointer_ to the variable being accessed.
199 - call_rcu is a macro that has an extra argument (the name of the first
200 field in the struct, which must be a struct rcu_head), and expects the
201 type of the callback's argument to be the type of the first argument.
202 call_rcu1 is the same as Linux's call_rcu.
208 Many patterns using read-writer locks translate directly to RCU, with
209 the advantages of higher scalability and deadlock immunity.
211 In general, RCU can be used whenever it is possible to create a new
212 "version" of a data structure every time the updater runs. This may
213 sound like a very strict restriction, however:
215 - the updater does not mean "everything that writes to a data structure",
216 but rather "everything that involves a reclamation step". See the
219 - in some cases, creating a new version of a data structure may actually
220 be very cheap. For example, modifying the "next" pointer of a singly
221 linked list is effectively creating a new version of the list.
223 Here are some frequently-used RCU idioms that are worth noting.
229 TBD (not yet used in QEMU)
232 RCU reference counting
233 ----------------------
235 Because grace periods are not allowed to complete while there is an RCU
236 read-side critical section in progress, the RCU read-side primitives
237 may be used as a restricted reference-counting mechanism. For example,
238 consider the following code fragment:
241 p = atomic_rcu_read(&foo);
242 /* do something with p. */
245 The RCU read-side critical section ensures that the value of "p" remains
246 valid until after the rcu_read_unlock(). In some sense, it is acquiring
247 a reference to p that is later released when the critical section ends.
248 The write side looks simply like this (with appropriate locking):
250 qemu_mutex_lock(&foo_mutex);
252 atomic_rcu_set(&foo, new);
253 qemu_mutex_unlock(&foo_mutex);
257 If the processing cannot be done purely within the critical section, it
258 is possible to combine this idiom with a "real" reference count:
261 p = atomic_rcu_read(&foo);
264 /* do something with p. */
267 The write side can be like this:
269 qemu_mutex_lock(&foo_mutex);
271 atomic_rcu_set(&foo, new);
272 qemu_mutex_unlock(&foo_mutex);
278 qemu_mutex_lock(&foo_mutex);
280 atomic_rcu_set(&foo, new);
281 qemu_mutex_unlock(&foo_mutex);
282 call_rcu(foo_unref, old, rcu);
284 In both cases, the write side only performs removal. Reclamation
285 happens when the last reference to a "foo" object is dropped.
286 Using synchronize_rcu() is undesirably expensive, because the
287 last reference may be dropped on the read side. Hence you can
288 use call_rcu() instead:
290 foo_unref(struct foo *p) {
291 if (atomic_fetch_dec(&p->refcount) == 1) {
292 call_rcu(foo_destroy, p, rcu);
297 Note that the same idioms would be possible with reader/writer
300 read_lock(&foo_rwlock); write_mutex_lock(&foo_rwlock);
302 /* do something with p. */ foo = new;
303 read_unlock(&foo_rwlock); free(p);
304 write_mutex_unlock(&foo_rwlock);
307 ------------------------------------------------------------------
309 read_lock(&foo_rwlock); write_mutex_lock(&foo_rwlock);
311 foo_ref(p); foo = new;
312 read_unlock(&foo_rwlock); foo_unref(old);
313 /* do something with p. */ write_mutex_unlock(&foo_rwlock);
314 read_lock(&foo_rwlock);
316 read_unlock(&foo_rwlock);
318 foo_unref could use a mechanism such as bottom halves to move deallocation
319 out of the write-side critical section.
325 Resizable arrays can be used with RCU. The expensive RCU synchronization
326 (or call_rcu) only needs to take place when the array is resized.
327 The two items to take care of are:
329 - ensuring that the old version of the array is available between removal
332 - avoiding mismatches in the read side between the array data and the
335 The first problem is avoided simply by not using realloc. Instead,
336 each resize will allocate a new array and copy the old data into it.
337 The second problem would arise if the size and the data pointers were
338 two members of a larger struct:
348 Instead, we store the size of the array with the array itself:
355 struct arr *global_array;
359 struct arr *array = atomic_rcu_read(&global_array);
360 x = i < array->size ? array->data[i] : -1;
364 write side (running under a lock):
365 if (global_array->size == global_array->alloc) {
366 /* Creating a new version. */
367 new_array = g_malloc(sizeof(struct arr) +
368 global_array->alloc * 2 * sizeof(T));
369 new_array->size = global_array->size;
370 new_array->alloc = global_array->alloc * 2;
371 memcpy(new_array->data, global_array->data,
372 global_array->alloc * sizeof(T));
375 old_array = global_array;
376 atomic_rcu_set(&new_array->data, new_array);
379 /* Reclamation phase. */
387 * Documentation/RCU/ from the Linux kernel