RCU Implementation for Qemu
cover RCU Implementation for Qemu
This is a rebase of Paolo's May patchset on v1.6.0-rc3
The tree is availavle on github:
https://github.com/ncultra/qemu/tree/rcu-for-1.7
Mike Day (3):
fix #include directive for rcu header
include osdep.h for definition of glue(a,b)
fix pointer reference to rcu_assign_pointer
Paolo Bonzini (11):
qemu-thread: add QemuEvent
rcu: add rcu library
qemu-thread: register threads with RCU
rcu: add call_rcu
rcu: add rcutorture
rcu: allow nested calls to rcu_thread_offline/rcu_thread_online
qemu-thread: report RCU quiescent states
event loop: report RCU quiescent states
cpus: report RCU quiescent states
block: report RCU quiescent states
migration: report RCU quiescent states
aio-posix.c | 9 +- aio-win32.c | 7 + block/raw-posix.c | 3 + block/raw-win32.c | 3 + cpus.c | 3 + docs/rcu.txt | 434 +++++++++++++++++++++++++++++++++++++++++++ hw/9pfs/virtio-9p-synth.c | 1 + include/qemu/queue.h | 13 ++ include/qemu/rcu-pointer.h | 110 +++++++++++ include/qemu/rcu.h | 208 +++++++++++++++++++++ include/qemu/thread-posix.h | 8 + include/qemu/thread-win32.h | 4 + include/qemu/thread.h | 10 +- kvm-all.c | 3 + libcacard/Makefile | 3 +- main-loop.c | 7 +- migration.c | 2 + tests/Makefile | 4 +- tests/rcutorture.c | 439 ++++++++++++++++++++++++++++++++++++++++++++ util/Makefile.objs | 1 + util/qemu-thread-posix.c | 173 ++++++++++++++++- util/qemu-thread-win32.c | 44 ++++- util/rcu.c | 320 ++++++++++++++++++++++++++++++++ 23 files changed, 1796 insertions(+), 13 deletions(-) create mode 100644 docs/rcu.txt create mode 100644 include/qemu/rcu-pointer.h create mode 100644 include/qemu/rcu.h create mode 100644 tests/rcutorture.c create mode 100644 util/rcu.c
Signature · 1 line
1.8.3.1
RFC PATCH 1/14 qemu-thread: add QemuEvent
From: Paolo Bonzini <[email protected]>
This emulates Win32 manual-reset events using futexes or conditional variables. Typical ways to use them are with multi-producer, single-consumer data structures, to test for a complex condition whose elements come from different threads:
for (;;) {
qemu_event_reset(ev);
... test complex condition ...
if (condition is true) {
break;
}
qemu_event_wait(ev);
}Alternatively:
... compute condition ...
if (condition) {
do {
qemu_event_wait(ev);
qemu_event_reset(ev);
... compute condition ...
} while(condition);
qemu_event_set(ev);
}QemuEvent provides a very fast userspace path in the common case when no other thread is waiting, or the event is not changing state. It is used to report RCU quiescent states to the thread calling synchronize_rcu (the latter being the single consumer), and to report call_rcu invocations to the thread that receives them.
--- include/qemu/thread-posix.h | 8 +++ include/qemu/thread-win32.h | 4 ++ include/qemu/thread.h | 7 +++ util/qemu-thread-posix.c | 116 ++++++++++++++++++++++++++++++++++++++++++++ util/qemu-thread-win32.c | 26 ++++++++++ 5 files changed, 161 insertions(+)
include/qemu/thread-posix.h +8 -0
@@ -21,6 +21,14 @@ struct QemuSemaphore {#endif }; +struct QemuEvent { +#ifndef __linux__ +pthread_mutex_t lock; +pthread_cond_t cond; +#endif +unsigned value; +}; +struct QemuThread {pthread_t thread; };
include/qemu/thread-win32.h +4 -0
@@ -17,6 +17,10 @@ struct QemuSemaphore {HANDLE sema; }; +struct QemuEvent { +HANDLE event; +}; +typedef struct QemuThreadData QemuThreadData ;struct QemuThread {QemuThreadData *data;
include/qemu/thread.h +7 -0
@@ -7,6 +7,7 @@typedef struct QemuMutex QemuMutex ;typedef struct QemuCond QemuCond ;typedef struct QemuSemaphore QemuSemaphore ; +typedef struct QemuEvent QemuEvent ;typedef struct QemuThread QemuThread ;#ifdef _WIN32
@@ -45,6 +46,12 @@ void qemu_sem_wait(QemuSemaphore *sem);int qemu_sem_timedwait (QemuSemaphore *sem,int ms);void qemu_sem_destroy (QemuSemaphore *sem); +void qemu_event_init (QemuEvent *ev,bool init); +void qemu_event_set (QemuEvent *ev); +void qemu_event_reset (QemuEvent *ev); +void qemu_event_wait (QemuEvent *ev); +void qemu_event_destroy (QemuEvent *ev); +void qemu_thread_create (QemuThread *thread,void *(*start_routine)(void *),void *arg,int mode);
util/qemu-thread-posix.c +116 -0
129 lines not on this page · raw message
util/qemu-thread-win32.c +26 -0
@@ -227,6 +227,32 @@ void qemu_sem_wait(QemuSemaphore *sem) } } +void qemu_event_init (QemuEvent *ev,bool init) +{ +/* Manual reset. */ + ev->event =CreateEvent (NULL , TRUE, init,NULL ); +} + +void qemu_event_destroy (QemuEvent *ev) +{ +CloseHandle (ev->event); +} + +void qemu_event_set (QemuEvent *ev) +{ +SetEvent (ev->event); +} + +void qemu_event_reset (QemuEvent *ev) +{ +ResetEvent (ev->event); +} + +void qemu_event_wait (QemuEvent *ev) +{ +WaitForSingleObject (ev->event,INFINITE ); +} +struct QemuThreadData {/* Passed to win32_start_routine. */ void *(*start_routine)(void *);
Signature · 1 line
1.8.3.1
RFC PATCH 2/14 rcu: add rcu library
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
This includes a (mangled) copy of the urcu-qsbr code from liburcu. The main changes are: 1) removing dependencies on many other header files in liburcu; 2) removing for simplicity the tentative busy waiting in synchronize_rcu, which has limited performance effects; 3) replacing futexes in synchronize_rcu with QemuEvents for Win32 portability. The API is the same as liburcu, so it should be possible in the future to require liburcu on POSIX systems for example and use our copy only on Windows.
Among the various versions available I chose urcu-qsbr, which has the fastest rcu_read_{lock,unlock} but requires the program to manually annotate quiescent points or intervals. QEMU threads usually have easily identified quiescent periods, so this should not be a problem.
--- docs/rcu.txt | 301 +++++++++++++++++++++++++++++++++++++++++++++ hw/9pfs/virtio-9p-synth.c | 1 + include/qemu/queue.h | 13 ++ include/qemu/rcu-pointer.h | 110 +++++++++++++++++ include/qemu/rcu.h | 168 +++++++++++++++++++++++++ include/qemu/thread.h | 3 - libcacard/Makefile | 3 +- util/Makefile.objs | 1 + util/rcu.c | 203 ++++++++++++++++++++++++++++++ 9 files changed, 799 insertions(+), 4 deletions(-) create mode 100644 docs/rcu.txt create mode 100644 include/qemu/rcu-pointer.h create mode 100644 include/qemu/rcu.h create mode 100644 util/rcu.c
docs/rcu.txt new file +301 -0
@@ -0,0 +1,301 @@ +Using RCU (Read-Copy-Update) for synchronization +================================================ + +Read-copy update (RCU) is a synchronization mechanism that is used to +protect read-mostly data structures. RCU is very efficient and scalable +on the read side (it is wait-free), and thus can make the read paths +extremely fast. + +RCU supports concurrency between a single writer and multiple readers, +thus it is not used alone. Typically, the write-side will use a lock to +serialize multiple updates, but other approaches are possible (e.g., +restricting updates to a single task). In QEMU, when a lock is used, +this will often be the "iothread mutex", also known as the "big QEMU +lock" (BQL). Also, restricting updates to a single task is done in +QEMU using the "bottom half" API. + +RCU is fundamentally a "wait-to-finish" mechanism. The read side marks +sections of code with "critical sections", and the update side will wait +for the execution of all *currently running* critical sections before +proceeding, or before asynchronously executing a callback. + +The key point here is that only the currently running critical sections +are waited for; critical sections that are started _after_ the beginning +of the wait do not extend the wait, despite running concurrently with +the updater. This is the reason why RCU is more scalable than, +for example, reader-writer locks. It is so much more scalable that +the system will have a single instance of the RCU mechanism; a single +mechanism can be used for an arbitrary number of "things", without +having to worry about things such as contention or deadlocks. + +How is this possible? The basic idea is to split updates in two phases, +"removal" and "reclamation". During removal, we ensure that subsequent +readers will not be able to get a reference to the old data. After +removal has completed, a critical section will not be able to access +the old data. Therefore, critical sections that begin after removal +do not matter; as soon as all previous critical sections have finished, +there cannot be any readers who hold references to the data structure, +which may not be safely reclaimed (e.g., freed or unref'ed). + +Here is a picutre: + + thread 1 thread 2 thread 3 + ------------------- ------------------------ ------------------- + enter RCU crit.sec. + | finish removal phase + | begin wait + | | enter RCU crit.sec. + exit RCU crit.sec | | + complete wait | + begin reclamation phase | + exit RCU crit.sec. + + +Note how thread 3 is still executing its critical section when thread 2 +starts reclaiming data. This is possible, because the old version of the +data structure was not accessible at the time thread 3 began executing +that critical section. + + +RCU API +======= + +The core RCU API is small: + + void rcu_read_lock(void); + + Used by a reader to inform the reclaimer that the reader is + entering an RCU read-side critical section. + + void rcu_read_unlock(void); + + Used by a reader to inform the reclaimer that the reader is + exiting an RCU read-side critical section. Note that RCU + read-side critical sections may be nested and/or overlapping. + + void synchronize_rcu(void); + + Blocks until all pre-existing RCU read-side critical sections + on all threads have completed. This marks the end of the removal + phase and the beginning of reclamation phase. + + Note that it would be valid for another update to come while + synchronize_rcu is running. Because of this, it is better that + the updater releases any locks it may hold before calling + synchronize_rcu. + + typeof(*p) rcu_dereference(p); + typeof(p) rcu_assign_pointer(p, typeof(p) v); + + These macros are similar to atomic_mb_read() and atomic_mb_set() + respectively. However, they make some assumptions on the code + that calls them, which allows a more optimized implementation. + + rcu_assign_pointer assumes that the update side is not going + to read from the data structure after "publishing" the new + values; that is, it assumes that all assignments happen at + the very end of the removal phase. + + rcu_dereference assumes that whenever a single RCU critical + section reads multiple shared data, these reads are either + data-dependent or need no ordering. This is almost always the + case when using RCU. If this were not the case, you can use + atomic_mb_read() or smp_rmb(). + + If you are going to be fetching multiple fields from the + RCU-protected structure, repeated rcu_dereference() calls + would look ugly and incur unnecessary overhead on Alpha CPUs. + You can then do this: + + p = &rcu_dereference(head); + foo = head->foo; + bar = head->bar; + + +RCU QUIESCENT STATES +==================== + +An efficient implementation of rcu_read_lock() and rcu_read_unlock() +relies on the availability of fast thread-local storage. Unfortunately, +this is not possible on all the systems supported by QEMU (in particular +on many POSIX systems other than Linux and Solaris). + +For this reason, QEMU's RCU implementation resorts to manual annotation +of "quiescent states", i.e. points where no RCU read-side critical +section can be active. All threads that participate in the RCU mechanism +need to annotate such points. + +Marking quiescent states is done with the following three APIs: + + void rcu_quiescent_state(void); + + Marks a point in the execution of the current thread where no + RCU read-side critical section can be active. + + void rcu_thread_offline(void); + + Marks the beginning of an "extended quiescent state" for the + current thread, i.e. an interval of time during which no + RCU read-side critical section can be active. + + void rcu_thread_online(void); + + Marks the end of an extended quiescent state for the current + thread. + + +Furthermore, threads that participate in the RCU mechanism must communicate +this fact using the following APIs: + + void rcu_register_thread(void); + + Mark a thread as taking part in the RCU mechanism. Such a thread + will have to report quiescent points regularly, either manually + or through the QemuCond/QemuSemaphore/QemuEvent APIs. + + void rcu_unregister_thread(void); + + Mark a thread as not taking part anymore in the RCU mechanism. + It is not a problem if such a thread reports quiescent points, + either manually or by using the QemuCond/QemuSemaphore/QemuEvent + APIs. + +Note that these APIs are relatively heavyweight, and should _not_ be +nested. + + +DIFFERENCES WITH LINUX +====================== + +- Sleeping is possible, though discouraged, within an RCU critical section. + +- rcu_dereference takes a _pointer_ to the variable being accessed. + Wrong usage will be detected by the compiler. + +- Quiescent points must be marked explicitly unless the thread uses + condvars/semaphores/events for synchronization. + + +RCU PATTERNS +============ + +Many patterns using read-writer locks translate directly to RCU, with +the advantages of higher scalability and deadlock immunity. + +In general, RCU can be used whenever it is possible to create a new +"version" of a data structure every time the updater runs. This may +sound like a very strict restriction, however: + +- the updater does not mean "everything that writes to a data structure", + but rather "everything that involves a reclamation step". See the + array example below + +- in some cases, creating a new version of a data structure may actually + be very cheap. For example, modifying the "next" pointer of a singly + linked list is effectively creating a new version of the list. + + +them however are worth noting. + +RCU list processing +------------------- + +TBD (not yet used in QEMU) + + +RCU reference counting +---------------------- + +Because grace periods are not allowed to complete while there is an RCU +read-side critical section in progress, the RCU read-side primitives +may be used as a restricted reference-counting mechanism. For example, +consider the following code fragment: + + rcu_read_lock(); + p = rcu_dereference(&foo); + /* do something with p. */ + rcu_read_unlock(); + +The RCU read-side critical section ensures that the value of "p" remains +valid until after the rcu_read_unlock(). In some sense, it is acquiring +a reference to p that is later released when the critical section ends. +The write side looks simply like this (with appropriate locking): + + qemu_mutex_lock(&foo_mutex); + old = foo; + rcu_assign_pointer(foo, new); + qemu_mutex_unlock(&foo_mutex); + synchronize_rcu(); + free(old); + +Note that the same idiom would be possible with reader/writer +locks: + + read_lock(&foo_rwlock); write_mutex_lock(&foo_rwlock); + p = foo; p = foo; + /* do something with p. */ foo = new; + read_unlock(&foo_rwlock); free(p); + write_mutex_unlock(&foo_rwlock); + free(p); + + +RCU resizable arrays +-------------------- + +Resizable arrays can be used with RCU. The expensive RCU synchronization +only needs to take place when the array is resized. The two items to +take care of are: + +- ensuring that the old version of the array is available between removal + and reclamation; + +- avoiding mismatches in the read side between the array data and the + array size. + +The first problem is avoided simply by not using realloc. Instead, +each resize will allocate a new array and copy the old data into it. +The second problem would arise if the size and the data pointers were +two members of a larger struct: + + struct mystuff { + ... + int data_size; + int data_alloc; + T *data; + ... + }; + +Instead, we store the size of the array with the array itself: + + struct arr { + int size; + int alloc; + T data[]; + }; + struct arr *global_array; + + read side: + rcu_read_lock(); + struct arr *array = rcu_dereference(&global_array); + x = i < array->size ? array->data[i] : -1; + rcu_read_unlock(); + return x; + + write side (running under a lock): + if (global_array->size == global_array->alloc) { + /* Creating a new version. */ + new_array = g_malloc(sizeof(struct arr) + + global_array->alloc * 2 * sizeof(T)); + new_array->size = global_array->size; + new_array->alloc = global_array->alloc * 2; + memcpy(new_array->data, global_array->data, + global_array->alloc * sizeof(T)); + + /* Removal phase. */ + old_array = global_array; + rcu_assign_pointer(new_array->data, new_array); + synchronize_rcu(); + + /* Reclamation phase. */ + free(old_array); + }
hw/9pfs/virtio-9p-synth.c +1 -0
@@ -17,6 +17,7 @@#include "virtio-9p-xattr.h" #include "fsdev/qemu-fsdev.h" #include "virtio-9p-synth.h" +#include "util/rcu.h" #include <sys/stat.h>
include/qemu/queue.h +13 -0
@@ -104,6 +104,19 @@ struct { \ (head)->lh_first =NULL ; \ } while (/*CONSTCOND*/0) +#define QLIST_SWAP(dstlist, srclist, field) do { \ + void *tmplist; \ + tmplist = (srclist)->lh_first; \ + (srclist)->lh_first = (dstlist)->lh_first; \ + if ((srclist)->lh_first != NULL) { \ + (srclist)->lh_first->field.le_prev = &(srclist)->lh_first; \ + } \ + (dstlist)->lh_first = tmplist; \ + if ((dstlist)->lh_first != NULL) { \ + (dstlist)->lh_first->field.le_prev = &(dstlist)->lh_first; \ + } \ +} while (/*CONSTCOND*/0) +#define QLIST_INSERT_AFTER (listelm, elm, field) do { \ if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ (listelm)->field.le_next->field.le_prev = \
include/qemu/rcu-pointer.h new file +110 -0
110 lines not on this page · raw message
include/qemu/rcu.h new file +168 -0
168 lines not on this page · raw message
include/qemu/thread.h +0 -3
@@ -25,9 +25,6 @@ void qemu_mutex_lock(QemuMutex *mutex);int qemu_mutex_trylock (QemuMutex *mutex);void qemu_mutex_unlock (QemuMutex *mutex); -#define rcu_read_lock () do { } while (0) -#define rcu_read_unlock () do { } while (0) -void qemu_cond_init (QemuCond *cond);void qemu_cond_destroy (QemuCond *cond);
libcacard/Makefile +2 -1
@@ -4,7 +4,8 @@ TOOLS += vscclient$(EXESUF) # objects linked into a shared library, built with libtool with -fPIC if required libcacard-obj-y = $(stub-obj-y) $(libcacard-y) -libcacard-obj-y += util/osdep.o util/cutils.o util/qemu-timer-common.o util/error.o +libcacard-obj-y += util/osdep.o util/cutils.o util/qemu-timer-common.o +libcacard-obj-y += util/rcu.o util/error.o libcacard-obj-$(CONFIG_WIN32) += util/oslib-win32.o util/qemu-thread-win32.o libcacard-obj-$(CONFIG_POSIX) += util/oslib-posix.o util/qemu-thread-posix.o libcacard-obj-y += $(filter trace/%, $(util-obj-y))
util/Makefile.objs +1 -0
@@ -11,3 +11,4 @@ util-obj-y += iov.o aes.o qemu-config.o qemu-sockets.o uri.o notify.o util-obj-y += qemu-option.o qemu-progress.o util-obj-y += hexdump.o util-obj-y += crc32c.o +util-obj-y += rcu.o
util/rcu.c new file +203 -0
203 lines not on this page · raw message
Signature · 1 line
1.8.3.1
RFC PATCH 3/14 fix #include directive for rcu header
In reply to Mike Day--- hw/9pfs/virtio-9p-synth.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
hw/9pfs/virtio-9p-synth.c +1 -1
@@ -17,7 +17,7 @@#include "virtio-9p-xattr.h" #include "fsdev/qemu-fsdev.h" #include "virtio-9p-synth.h" -#include "util/rcu.h" +#include "qemu/rcu.h" #include <sys/stat.h>
Signature · 1 line
1.8.3.1
RFC PATCH 4/14 qemu-thread: register threads with RCU
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
--- docs/rcu.txt | 13 +++++++------ util/qemu-thread-posix.c | 28 +++++++++++++++++++++++++++- util/qemu-thread-win32.c | 2 ++ 3 files changed, 36 insertions(+), 7 deletions(-)
docs/rcu.txt +7 -6
@@ -122,8 +122,8 @@ on many POSIX systems other than Linux and Solaris). For this reason, QEMU's RCU implementation resorts to manual annotation of "quiescent states", i.e. points where no RCU read-side critical -section can be active. All threads that participate in the RCU mechanism -need to annotate such points. +section can be active. All threads created with qemu_thread_create +participate in the RCU mechanism and need to annotate such points. Marking quiescent states is done with the following three APIs:
@@ -144,8 +144,8 @@ Marking quiescent states is done with the following three APIs: thread. -Furthermore, threads that participate in the RCU mechanism must communicate -this fact using the following APIs: +The following APIs can be used to use RCU in a thread that is not +created with qemu_thread_create(): void rcu_register_thread(void);
@@ -160,8 +160,9 @@ this fact using the following APIs: either manually or by using the QemuCond/QemuSemaphore/QemuEvent APIs. -Note that these APIs are relatively heavyweight, and should _not_ be -nested. +Note that these APIs are relatively heavyweight, should _not_ be +nested, and should not be called in threads that are created with +qemu_thread_create(). DIFFERENCES WITH LINUX
util/qemu-thread-posix.c +27 -1
@@ -26,6 +26,7 @@#endif #include "qemu/thread.h" #include "qemu/atomic.h" +#include "qemu/rcu.h" static void error_exit (int err,const char *msg) {
@@ -388,6 +389,26 @@ void qemu_event_wait(QemuEvent *ev) } +typedef struct QemuThreadData { +/* Passed to win32_start_routine. */ +void *(*start_routine)(void *); +void *arg; +}QemuThreadData ; + +static void *thread_start_routine (void *arg) +{ +QemuThreadData *data = (QemuThreadData *) arg; +void *(*start_routine)(void *) = data->start_routine; +void *thread_arg = data->arg; +void *ret; + +rcu_register_thread (); +g_free (data); + ret =start_routine (thread_arg); +rcu_unregister_thread (); +return ret; +} +void qemu_thread_create (QemuThread *thread,void *(*start_routine)(void *),void *arg,int mode)
@@ -395,6 +416,11 @@ void qemu_thread_create(QemuThread *thread,sigset_t set, oldset;int err;pthread_attr_t attr; +QemuThreadData *data; + + data =g_malloc (sizeof (*data)); + data->start_routine = start_routine; + data->arg = arg; err =pthread_attr_init (&attr);if (err) {
@@ -410,7 +436,7 @@ void qemu_thread_create(QemuThread *thread,/* Leave signal handling to the iothread. */ sigfillset (&set);pthread_sigmask (SIG_SETMASK , &set, &oldset); - err =pthread_create (&thread->thread, &attr, start_routine, arg); + err =pthread_create (&thread->thread, &attr, thread_start_routine, data);if (err)error_exit (err, __func__);
util/qemu-thread-win32.c +2 -0
@@ -278,6 +278,7 @@ static unsigned __stdcall win32_start_routine(void *arg) data =NULL ; } qemu_thread_data = data; +rcu_register_thread ();qemu_thread_exit (start_routine (thread_arg));abort (); }
@@ -293,6 +294,7 @@ void qemu_thread_exit(void *arg) data->exited = true;LeaveCriticalSection (&data->cs); } +rcu_unregister_thread ();_endthreadex (0 ); }
Signature · 1 line
1.8.3.1
RFC PATCH 5/14 rcu: add call_rcu
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
--- docs/rcu.txt | 108 +++++++++++++++++++++++++++++++++++++++++++++-- include/qemu/rcu.h | 22 ++++++++++ util/rcu.c | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 246 insertions(+), 4 deletions(-)
docs/rcu.txt +104 -4
@@ -82,7 +82,50 @@ The core RCU API is small: Note that it would be valid for another update to come while synchronize_rcu is running. Because of this, it is better that the updater releases any locks it may hold before calling - synchronize_rcu. + synchronize_rcu. If this is not possible (for example, because + the updater is protected by the BQL), you can use call_rcu. + + void call_rcu1(struct rcu_head * head, + void (*func)(struct rcu_head *head)); + + This function invokes func(head) after all pre-existing RCU + read-side critical sections on all threads have completed. This + marks the end of the removal phase, with func taking care + asynchronously of the reclamation phase. + + The foo struct needs to have an rcu_head structure added, + perhaps as follows: + + struct foo { + struct rcu_head rcu; + int a; + char b; + long c; + }; + + so that the reclaimer function can fetch the struct foo address + and free it: + + call_rcu1(foo_reclaim, &foo.rcu); + + void foo_reclaim(struct rcu_head *rp) + { + struct foo *fp = container_of(rp, struct foo, rcu); + g_free(fp); + } + + For the common case where the rcu_head member is the first of the + struct, you can use the following macro. + + void call_rcu(T *p, + void (*func)(T *p), + field-name); + + call_rcu1 is typically used through this macro, in the common case + where the "struct rcu_head" is the first field in the struct. In + the above case, one could have written simply: + + call_rcu(foo_reclaim, g_free, rcu); typeof(*p) rcu_dereference(p); typeof(p) rcu_assign_pointer(p, typeof(p) v);
@@ -173,6 +216,11 @@ DIFFERENCES WITH LINUX - rcu_dereference takes a _pointer_ to the variable being accessed. Wrong usage will be detected by the compiler. +- call_rcu is a macro that has an extra argument (the name of the first + field in the struct, which must be a struct rcu_head), and expects the + type of the callback's argument to be the type of the first argument. + call_rcu1 is the same as Linux's call_rcu. + - Quiescent points must be marked explicitly unless the thread uses condvars/semaphores/events for synchronization.
@@ -229,7 +277,47 @@ The write side looks simply like this (with appropriate locking): synchronize_rcu(); free(old); -Note that the same idiom would be possible with reader/writer +If the processing cannot be done purely within the critical section, it +is possible to combine this idiom with a "real" reference count: + + rcu_read_lock(); + p = rcu_dereference(&foo); + foo_ref(p); + rcu_read_unlock(); + /* do something with p. */ + foo_unref(p); + +The write side can be like this: + + qemu_mutex_lock(&foo_mutex); + old = foo; + rcu_assign_pointer(foo, new); + qemu_mutex_unlock(&foo_mutex); + synchronize_rcu(); + foo_unref(old); + +or with call_rcu: + + qemu_mutex_lock(&foo_mutex); + old = foo; + rcu_assign_pointer(foo, new); + qemu_mutex_unlock(&foo_mutex); + call_rcu(foo_unref, old, rcu); + +In both cases, the write side only performs removal. Reclamation +happens when the last reference to a "foo" object is dropped. +Using synchronize_rcu() is undesirably expensive, because the +last reference may be dropped on the read side. Hence you can +use call_rcu() instead: + + foo_unref(struct foo *p) { + if (atomic_dec(&p->refcount) == 0) { + call_rcu(foo_destroy, p, rcu); + } + } + + +Note that the same idioms would be possible with reader/writer locks: read_lock(&foo_rwlock); write_mutex_lock(&foo_rwlock);
@@ -239,13 +327,25 @@ locks: write_mutex_unlock(&foo_rwlock); free(p); + ------------------------------------------------------------------ + + read_lock(&foo_rwlock); write_mutex_lock(&foo_rwlock); + p = foo; old = foo; + foo_ref(p); foo = new; + read_unlock(&foo_rwlock); write_mutex_unlock(&foo_rwlock); + /* do something with p. */ foo_unref(old); + foo_unref(p); + +foo_unref could use a mechanism such as bottom halves to move deallocation +out of hot paths. + RCU resizable arrays -------------------- Resizable arrays can be used with RCU. The expensive RCU synchronization -only needs to take place when the array is resized. The two items to -take care of are: +(or call_rcu) only needs to take place when the array is resized. +The two items to take care of are: - ensuring that the old version of the array is available between removal and reclamation;
include/qemu/rcu.h +22 -0
@@ -161,6 +161,28 @@ extern void synchronize_rcu(void);extern void rcu_register_thread (void );extern void rcu_unregister_thread (void ); +struct rcu_head ; +typedef void RCUCBFunc (struct rcu_head *head); + +struct rcu_head { +struct rcu_head *next; +RCUCBFunc *func; +}; + +extern void call_rcu1 (struct rcu_head *head,RCUCBFunc *func); + +/* The operands of the minus operator must have the same type, +* which must be the one that we specify in the cast. +*/ +#define call_rcu (head, func, field) \ + call_rcu1(({ \ + char __attribute__((unused)) \ + offset_must_be_zero[-offsetof(typeof(*(head)), field)], \ + func_type_invalid = (func) - (void (*)(typeof(head)))(func); \ + &(head)->field; \ + }), \ + (RCUCBFunc *)(func)) + #ifdef __cplusplus }#endif
util/rcu.c +120 -0
145 lines not on this page · raw message
Signature · 1 line
1.8.3.1
RFC PATCH 6/14 rcu: add rcutorture
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
A stress test program (works, too :)).
--- tests/Makefile | 4 +- tests/rcutorture.c | 439 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 442 insertions(+), 1 deletion(-) create mode 100644 tests/rcutorture.c
tests/Makefile +3 -1
@@ -99,7 +99,8 @@ test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \ tests/test-string-input-visitor.o tests/test-qmp-output-visitor.o \ tests/test-qmp-input-visitor.o tests/test-qmp-input-strict.o \ tests/test-qmp-commands.o tests/test-visitor-serialization.o \ - tests/test-x86-cpuid.o tests/test-mul64.o tests/test-int128.o + tests/test-x86-cpuid.o tests/test-mul64.o tests/rcutortore.o \ + tests/test-int128.o test-qapi-obj-y = tests/test-qapi-visit.o tests/test-qapi-types.o
@@ -122,6 +123,7 @@ tests/test-hbitmap$(EXESUF): tests/test-hbitmap.o libqemuutil.a libqemustub.a tests/test-x86-cpuid$(EXESUF): tests/test-x86-cpuid.o tests/test-xbzrle$(EXESUF): tests/test-xbzrle.o xbzrle.o page_cache.o libqemuutil.a tests/test-cutils$(EXESUF): tests/test-cutils.o util/cutils.o ++tests/rcutorture$(EXESUF): tests/rcutorture.o libqemuutil.a tests/test-int128$(EXESUF): tests/test-int128.o tests/test-qapi-types.c tests/test-qapi-types.h :\
tests/rcutorture.c new file +439 -0
439 lines not on this page · raw message
Signature · 1 line
1.8.3.1
RFC PATCH 7/14 rcu: allow nested calls to rcu_thread_offline/rcu_thread_online
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
--- docs/rcu.txt | 5 +++++ include/qemu/rcu.h | 21 +++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-)
docs/rcu.txt +5 -0
@@ -187,6 +187,11 @@ Marking quiescent states is done with the following three APIs: thread. +rcu_thread_offline() and rcu_thread_online() can be nested. The end of +the extended quiescent state will coincide with the outermost call to +rcu_thread_online(). + + The following APIs can be used to use RCU in a thread that is not created with qemu_thread_create():
include/qemu/rcu.h +19 -2
@@ -77,6 +77,9 @@ struct rcu_reader_data {unsigned long ctr;bool waiting; +/* Data used by reader only */ +unsigned offline; +/* Data used for registry, protected by rcu_gp_lock */ QLIST_ENTRY (rcu_reader_data) node; };
@@ -127,9 +130,14 @@ static inline void rcu_read_unlock(void)static inline void rcu_quiescent_state (void ) {struct rcu_reader_data *p_rcu_reader =get_rcu_reader (); +unsigned ctr; + +if (p_rcu_reader->offline >0 ) { +return ; + }/* Reuses smp_rmb() in the last rcu_read_unlock(). */ -unsigned ctr =atomic_read (&rcu_gp_ctr); + ctr =atomic_read (&rcu_gp_ctr);atomic_xchg (&p_rcu_reader->ctr, ctr);if (atomic_read (&p_rcu_reader->waiting)) {atomic_set (&p_rcu_reader->waiting, false);
@@ -141,6 +149,10 @@ static inline void rcu_thread_offline(void) {struct rcu_reader_data *p_rcu_reader =get_rcu_reader (); +if (p_rcu_reader->offline++ >0 ) { +return ; + } +atomic_xchg (&p_rcu_reader->ctr,0 );if (atomic_read (&p_rcu_reader->waiting)) {atomic_set (&p_rcu_reader->waiting, false);
@@ -150,7 +162,12 @@ static inline void rcu_thread_offline(void)static inline void rcu_thread_online (void ) { -rcu_quiescent_state (); +struct rcu_reader_data *p_rcu_reader =get_rcu_reader (); + +assert (p_rcu_reader->offline !=0 ); +if (--p_rcu_reader->offline ==0 ) { +rcu_quiescent_state (); + } }extern void synchronize_rcu (void );
Signature · 1 line
1.8.3.1
RFC PATCH 8/14 qemu-thread: report RCU quiescent states
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
Most threads will use mutexes and other sleeping synchronization primitives (condition variables, semaphores, events) periodically. For these threads, the synchronization primitives are natural places to report a quiescent state (possibly an extended one).
--- docs/rcu.txt | 27 +++++++++++++++++++++++++++ util/qemu-thread-posix.c | 29 +++++++++++++++++++++++++---- util/qemu-thread-win32.c | 16 +++++++++++++++- util/rcu.c | 3 --- 4 files changed, 67 insertions(+), 8 deletions(-)
docs/rcu.txt +27 -0
@@ -168,6 +168,33 @@ of "quiescent states", i.e. points where no RCU read-side critical section can be active. All threads created with qemu_thread_create participate in the RCU mechanism and need to annotate such points. +Luckily, in most cases no manual annotation is needed, because waiting +on condition variables (qemu_cond_wait), semaphores (qemu_sem_wait, +qemu_sem_timedwait) or events (qemu_event_wait) implicitly marks the thread +as quiescent for the whole duration of the wait. (There is an exception +for semaphore waits with a zero timeout). + +Manual annotation is still needed in the following cases: + +- threads that spend their sleeping time in the kernel, for example + in a call to select(), poll() or WaitForMultipleObjects(). The QEMU + I/O thread is an example of this case. + +- threads that perform a lot of I/O. In QEMU, the workers used for + aio=thread are an example of this case (see aio_worker in block/raw-*). + +- threads that run continuously until they exit. The migration thread + is an example of this case. + +Regarding the second case, note that the workers run in the QEMU thread +pool. The thread pool uses semaphores for synchronization, hence it does +report quiescent states periodically. However, in some cases (e.g. NFS +mounted with the "hard" option) the workers can take an arbitrarily long +amount of time. When this happens, synchronize_rcu() will not exit and +call_rcu() callbacks will be delayed arbitrarily. It is therefore a +good idea to mark I/O system calls as quiescence points in the worker +functions. + Marking quiescent states is done with the following three APIs: void rcu_quiescent_state(void);
util/qemu-thread-posix.c +25 -4
@@ -119,7 +119,9 @@ void qemu_cond_wait(QemuCond *cond, QemuMutex *mutex) {int err; +rcu_thread_offline (); err =pthread_cond_wait (&cond->cond, &mutex->lock); +rcu_thread_online ();if (err)error_exit (err, __func__); }
@@ -211,6 +213,10 @@ int qemu_sem_timedwait(QemuSemaphore *sem, int ms)int rc;struct timespec ts; +if (ms) { +rcu_thread_offline (); + } +#if defined(__APPLE__) || defined(__NetBSD__) rc =0 ;compute_abs_deadline (&ts, ms);
@@ -228,7 +234,10 @@ int qemu_sem_timedwait(QemuSemaphore *sem, int ms) --sem->count; }pthread_mutex_unlock (&sem->lock); -return (rc ==ETIMEDOUT ?-1 :0 ); +if (rc ==ETIMEDOUT ) { + rc ==-1 ; + } +#else if (ms <=0 ) {/* This is cheaper than sem_timedwait. */
@@ -236,7 +245,7 @@ int qemu_sem_timedwait(QemuSemaphore *sem, int ms) rc =sem_trywait (&sem->sem); }while (rc ==-1 && errno ==EINTR );if (rc ==-1 && errno ==EAGAIN ) { -return -1 ; + goto out; } }else {compute_abs_deadline (&ts, ms);
@@ -244,19 +253,26 @@ int qemu_sem_timedwait(QemuSemaphore *sem, int ms) rc = sem_timedwait(&sem->sem, &ts); }while (rc ==-1 && errno ==EINTR );if (rc ==-1 && errno ==ETIMEDOUT ) { -return -1 ; + goto out; } }if (rc <0 ) {error_exit (errno, __func__); } -return 0 ; +#endif + +out: +if (ms) { +rcu_thread_online (); + } +return rc; }void qemu_sem_wait (QemuSemaphore *sem) {int rc; +rcu_thread_offline ();#if defined(__APPLE__) || defined(__NetBSD__)pthread_mutex_lock (&sem->lock);
@@ -276,6 +292,7 @@ void qemu_sem_wait(QemuSemaphore *sem) error_exit(errno, __func__); }#endif +rcu_thread_online (); }#ifdef __linux__
@@ -384,7 +401,11 @@ void qemu_event_wait(QemuEvent *ev)return ; } } +rcu_thread_offline ();futex_wait (ev,EV_BUSY ); +rcu_thread_online (); + }else { +rcu_quiescent_state (); } }
util/qemu-thread-win32.c +15 -1
@@ -12,6 +12,7 @@*/ #include "qemu-common.h" #include "qemu/thread.h" +#include "qemu/rcu.h" #include <process.h> #include <assert.h> #include <limits.h>
@@ -170,7 +171,9 @@ void qemu_cond_wait(QemuCond *cond, QemuMutex *mutex)* leaving mutex unlocked before we wait on semaphore. */ qemu_mutex_unlock (mutex); +rcu_thread_offline ();WaitForSingleObject (cond->sema,INFINITE ); +rcu_thread_online ();/* Now waiters must rendez-vous with the signaling thread and * let it continue. For cond_broadcast this has heavy contention
@@ -210,7 +213,16 @@ void qemu_sem_post(QemuSemaphore *sem)int qemu_sem_timedwait (QemuSemaphore *sem,int ms) { -int rc =WaitForSingleObject (sem->sema, ms); +int rc; + +if (ms) { +rcu_thread_offline (); + } + rc =WaitForSingleObject (sem->sema, ms); +if (ms) { +rcu_thread_offline (); + } +if (rc ==WAIT_OBJECT_0 ) {return 0 ; }
@@ -250,7 +262,9 @@ void qemu_event_reset(QemuEvent *ev)void qemu_event_wait (QemuEvent *ev) { +rcu_thread_offline ();WaitForSingleObject (ev->event,INFINITE ); +rcu_thread_online (); }struct QemuThreadData {
util/rcu.c +0 -3
@@ -240,9 +240,6 @@ static void *call_rcu_thread(void *opaque) {struct rcu_head *node; -/* This thread is just a writer. */ -rcu_thread_offline (); -for (;;) {int tries =0 ;int n =atomic_read (&rcu_call_count);
Signature · 1 line
1.8.3.1
RFC PATCH 9/14 event loop: report RCU quiescent states
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
Threads that run event loops also have places that can sleep for an extended time. Place an extended quiescent state there.
--- aio-posix.c | 9 ++++++++- aio-win32.c | 7 +++++++ main-loop.c | 7 ++++++- 3 files changed, 21 insertions(+), 2 deletions(-)
aio-posix.c +8 -1
@@ -17,6 +17,7 @@#include "block/block.h" #include "qemu/queue.h" #include "qemu/sockets.h" +#include "qemu/rcu.h" struct AioHandler {
@@ -232,10 +233,16 @@ bool aio_poll(AioContext *ctx, bool blocking) }/* wait until next event */ +if (blocking) { +rcu_thread_offline (); + } ret =g_poll ((GPollFD *)ctx->pollfds->data, ctx->pollfds->len, blocking ?-1 :0 ); - +if (blocking) { +rcu_thread_online (); + } +/* if we have any readable fds, dispatch event */ if (ret >0 ) { QLIST_FOREACH(node, &ctx->aio_handlers, node) {
aio-win32.c +7 -0
@@ -175,7 +175,14 @@ bool aio_poll(AioContext *ctx, bool blocking)/* wait until next event */ while (count >0 ) {int timeout = blocking ?INFINITE :0 ; + +if (timeout) { +rcu_thread_offline (); + }int ret =WaitForMultipleObjects (count, events, FALSE, timeout); +if (timeout) { +rcu_thread_online (); + }/* if we have any signaled events, dispatch event */ if ((DWORD ) (ret -WAIT_OBJECT_0 ) >= count) {
main-loop.c +6 -1
@@ -27,6 +27,7 @@#include "qemu/sockets.h" // struct in_addr needed for libslirp.h #include "slirp/libslirp.h" #include "qemu/main-loop.h" +#include "qemu/rcu.h" #include "block/aio.h" #ifndef _WIN32
@@ -220,6 +221,7 @@ static int os_host_main_loop_wait(uint32_t timeout)if (timeout >0 ) { spin_counter =0 ;qemu_mutex_unlock_iothread (); +rcu_thread_offline (); }else { spin_counter++; }
@@ -227,7 +229,8 @@ static int os_host_main_loop_wait(uint32_t timeout) ret =g_poll ((GPollFD *)gpollfds->data, gpollfds->len, timeout);if (timeout >0 ) { -qemu_mutex_lock_iothread (); +rcu_thread_online (); +qemu_mutex_lock_iothread (); }glib_pollfds_poll ();
@@ -424,7 +427,9 @@ static int os_host_main_loop_wait(uint32_t timeout) }qemu_mutex_unlock_iothread (); +rcu_thread_offline (); g_poll_ret =g_poll (poll_fds, n_poll_fds + w->num, poll_timeout); +rcu_thread_online ();qemu_mutex_lock_iothread ();if (g_poll_ret >0 ) {for (i =0 ; i < w->num; i++) {
Signature · 1 line
1.8.3.1
RFC PATCH 10/14 cpus: report RCU quiescent states
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
CPU threads have extended quiescent states while relinquishing control to the accelerator (except TCG).
--- cpus.c | 3 +++ kvm-all.c | 3 +++ 2 files changed, 6 insertions(+)
cpus.c +3 -0
@@ -37,6 +37,7 @@#include "sysemu/qtest.h" #include "qemu/main-loop.h" #include "qemu/bitmap.h" +#include "qemu/rcu.h" #ifndef _WIN32#include "qemu/compatfd.h"
@@ -818,6 +819,7 @@ static void *qemu_dummy_cpu_thread_fn(void *arg)while (1 ) { current_cpu =NULL ;qemu_mutex_unlock_iothread (); +rcu_thread_offline (); do { int sig; r = sigwait(&waitset, &sig);
@@ -826,6 +828,7 @@ static void *qemu_dummy_cpu_thread_fn(void *arg)perror ("sigwait" );exit (1 ); } +rcu_thread_online ();qemu_mutex_lock_iothread (); current_cpu = cpu;qemu_wait_io_event_common (cpu);
kvm-all.c +3 -0
@@ -33,6 +33,7 @@#include "exec/memory.h" #include "exec/address-spaces.h" #include "qemu/event_notifier.h" +#include "qemu/rcu.h" #include "trace.h" /* This check must be after config-host.h is included */
@@ -1641,7 +1642,9 @@ int kvm_cpu_exec(CPUState *cpu) }qemu_mutex_unlock_iothread (); +rcu_thread_offline (); run_ret =kvm_vcpu_ioctl (cpu,KVM_RUN ,0 ); +rcu_thread_online ();qemu_mutex_lock_iothread ();kvm_arch_post_run (cpu, run);
Signature · 1 line
1.8.3.1
RFC PATCH 11/14 block: report RCU quiescent states
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
The aio workers may spend a long time executing I/O operations; mark that time as an extended quiescent state.
--- block/raw-posix.c | 3 +++ block/raw-win32.c | 3 +++ 2 files changed, 6 insertions(+)
block/raw-posix.c +3 -0
@@ -26,6 +26,7 @@#include "qemu/log.h" #include "block/block_int.h" #include "qemu/module.h" +#include "qemu/rcu.h" #include "trace.h" #include "block/thread-pool.h" #include "qemu/iov.h"
@@ -735,6 +736,7 @@ static int aio_worker(void *arg)RawPosixAIOData *aiocb = arg;ssize_t ret =0 ; +rcu_thread_offline ();switch (aiocb->aio_type &QEMU_AIO_TYPE_MASK ) {case QEMU_AIO_READ : ret =handle_aiocb_rw (aiocb);
@@ -774,6 +776,7 @@ static int aio_worker(void *arg) }g_slice_free (RawPosixAIOData, aiocb); +rcu_thread_online ();return ret; }
block/raw-win32.c +3 -0
@@ -25,6 +25,7 @@#include "qemu/timer.h" #include "block/block_int.h" #include "qemu/module.h" +#include "qemu/rcu.h" #include "raw-aio.h" #include "trace.h" #include "block/thread-pool.h"
@@ -99,6 +100,7 @@ static int aio_worker(void *arg)ssize_t ret =0 ;size_t count; +rcu_thread_offline ();switch (aiocb->aio_type &QEMU_AIO_TYPE_MASK ) {case QEMU_AIO_READ : count =handle_aiocb_rw (aiocb);
@@ -136,6 +138,7 @@ static int aio_worker(void *arg) }g_slice_free (RawWin32AIOData, aiocb); +rcu_thread_online ();return ret; }
Signature · 1 line
1.8.3.1
RFC PATCH 12/14 migration: report RCU quiescent states
In reply to Mike DayFrom: Paolo Bonzini <[email protected]>
The migration thread polls s->state periodically, it does not use a mutex or condition variable, so it has to report quiescent states manually.
--- migration.c | 2 ++ 1 file changed, 2 insertions(+)
migration.c +2 -0
@@ -22,6 +22,7 @@#include "qemu/sockets.h" #include "migration/block.h" #include "qemu/thread.h" +#include "qemu/rcu.h" #include "qmp-commands.h" #include "trace.h"
@@ -563,6 +564,7 @@ static void *migration_thread(void *opaque)int64_t current_time;uint64_t pending_size; +rcu_quiescent_state ();if (!qemu_file_rate_limit (s->file)) {DPRINTF ("iterate\n" ); pending_size =qemu_savevm_state_pending (s->file, max_size);
Signature · 1 line
1.8.3.1
PATCH 13/14 include osdep.h for definition of glue(a, b)
In reply to Mike Dayinclude/qemu/rcu.h +1 -0
@@ -39,6 +39,7 @@#include "qemu/compiler.h" #include "qemu/rcu-pointer.h" #include "qemu/thread.h" +#include "qemu/osdep.h" #include "qemu/queue.h" #include "qemu/atomic.h"
Signature · 1 line
1.8.3.1
PATCH 14/14 fix pointer reference to rcu_assign_pointer
In reply to Mike Day--- tests/rcutorture.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
tests/rcutorture.c +1 -1
@@ -293,7 +293,7 @@ static void *rcu_update_stress_test(void *arg)smp_mb (); p->pipe_count =0 ; p->mbtest =1 ; -rcu_assign_pointer (&rcu_stress_current, &p); +rcu_assign_pointer (rcu_stress_current, p); rcu_stress_idx = i;for (i =0 ; i <RCU_STRESS_PIPE_LEN ; i++)if (i != rcu_stress_idx) {
Signature · 1 line
1.8.3.1