Coroutines for better asynchronous programming
PATCH v3 4/4 coroutine: pool coroutines to speed up creation
In reply to Stefan HajnocziThis patch speeds up coroutine creation by reusing freed coroutines. When a coroutine terminates it is placed in the pool instead of having its resources freed. The next time a coroutine is created it can be taken straight from the pool and requires no initialization.
Performance results on an Intel Core2 Duo T9400 (2.53GHz) for ./check-coroutine --benchmark-lifecycle 20000000:
No pooling: 19.5 sec
With pooling: 1.1 sec
--- qemu-coroutine-int.h | 2 ++ qemu-coroutine.c | 33 ++++++++++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-)
qemu-coroutine-int.h +2 -0
@@ -45,6 +45,8 @@ struct Coroutine {void *data;CoroutineEntry *entry; +QLIST_ENTRY (Coroutine) pool_next; +jmp_buf env; };
qemu-coroutine.c +30 -3
@@ -24,16 +24,35 @@#include "qemu-coroutine.h" #include "qemu-coroutine-int.h" +enum { +/* Maximum free pool size prevents holding too many freed coroutines */ +POOL_MAX_SIZE =64 , +}; + +static QLIST_HEAD(, Coroutine) pool = QLIST_HEAD_INITIALIZER(&pool); +static unsigned int pool_size;static Coroutine leader;static Coroutine *current; -static void coroutine_terminate (Coroutine *co) +static void coroutine_delete (Coroutine *co) { -trace_qemu_coroutine_terminate (co);qemu_free (co->stack);qemu_free (co); } +static void coroutine_terminate (Coroutine *co) +{ +trace_qemu_coroutine_terminate (co); + +if (pool_size <POOL_MAX_SIZE ) { +QLIST_INSERT_HEAD (&pool, co, pool_next); + co->caller =NULL ; + pool_size++; + }else { +coroutine_delete (co); + } +} +static Coroutine *coroutine_new (void ) {const size_t stack_size =4 <<20 ;
@@ -49,7 +68,15 @@ Coroutine *qemu_coroutine_create(CoroutineEntry *entry) {Coroutine *co; - co =coroutine_new (); + co =QLIST_FIRST (&pool); + +if (co) { +QLIST_REMOVE (co, pool_next); + pool_size--; + }else { + co =coroutine_new (); + } + co->entry = entry;return co;
Signature · 1 line
1.7.4.4
v3 cover Coroutines for better asynchronous programming
QEMU is event-driven and suffers when blocking operations are performed because VM execution may be stopped until the operation completes. Therefore many operations that could block are performed asynchronously and a callback is invoked when the operation has completed. This allows QEMU to continue executing while the operation is pending.
The downside to callbacks is that they split up code into many smaller functions, each of which is a single step in a state machine that quickly becomes complex and hard to understand. Callback functions also result in lots of noise as variables are packed and unpacked into temporary structs that pass state to the callback function.
This patch series introduces coroutines as a solution for writing asynchronous code while still having a nice sequential control flow. The semantics are explained in the first patch. The second patch adds automated tests.
A nice feature of coroutines is that it is relatively easy to take synchronous code and lift it into a coroutine to make it asynchronous. Work has been done to move qcow2 request processing into coroutines and thereby make it asynchronous (today qcow2 will perform synchronous metadata accesses). This qcow2 work is still ongoing and not quite ready for mainline yet.
Coroutines are also being used for virtfs (virtio-9p) so I have submitted this patch now because virtfs patches that depend on coroutines are being published.
Other areas of QEMU that could take advantage of coroutines include the VNC server, migration, and qemu-tools.
v3:
* Updated LGPL v2 license header to use web link
* Removed atexit(3) pool freeing
* Removed thread-local current/leader
* Documented thread-safety limitation
* Disabled trace events
v2:
* Added ./check-coroutine --lifecycle-benchmark for performance measurement
* Split pooling into a separate patch with performance justification
* Set maximum pool size to prevent holding onto too many free coroutines
* Added atexit(3) handler to free pool
* Coding style cleanups
PATCH v3 2/4 coroutine: add check-coroutine automated tests
To run automated tests for coroutines:
make check-coroutine
./check-coroutine
On success the program terminates with exit status 0. On failure an error message is written to stderr and the program exits with exit status 1.
--- Makefile | 3 +- check-coroutine.c | 188 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 190 insertions(+), 1 deletions(-) create mode 100644 check-coroutine.c
Makefile +2 -1
@@ -132,7 +132,7 @@ qemu-io$(EXESUF): qemu-io.o cmd.o qemu-tool.o qemu-error.o $(oslib-obj-y) $(trac qemu-img-cmds.h: $(SRC_PATH)/qemu-img-cmds.hx $(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -h < $< > $@," GEN $@") -check-qint.o check-qstring.o check-qdict.o check-qlist.o check-qfloat.o check-qjson.o: $(GENERATED_HEADERS) +check-qint.o check-qstring.o check-qdict.o check-qlist.o check-qfloat.o check-qjson.o check-coroutine.o: $(GENERATED_HEADERS) CHECK_PROG_DEPS = qemu-malloc.o $(oslib-obj-y) $(trace-obj-y)
@@ -142,6 +142,7 @@ check-qdict: check-qdict.o qdict.o qfloat.o qint.o qstring.o qbool.o qlist.o $(C check-qlist: check-qlist.o qlist.o qint.o $(CHECK_PROG_DEPS) check-qfloat: check-qfloat.o qfloat.o $(CHECK_PROG_DEPS) check-qjson: check-qjson.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o qjson.o json-streamer.o json-lexer.o json-parser.o $(CHECK_PROG_DEPS) +check-coroutine: check-coroutine.o $(coroutine-obj-y) $(CHECK_PROG_DEPS) QEMULIBS=libhw32 libhw64 libuser libdis libdis-user
check-coroutine.c new file +188 -0
188 lines not on this page · raw message
Signature · 1 line
1.7.4.4
PATCH v3 3/4 coroutine: add check-coroutine --benchmark-lifecycle
In reply to Stefan HajnocziAdd a microbenchmark for coroutine create, enter, and return (aka lifecycle). This is a useful benchmark because users are expected to create many coroutines, one per I/O request for example, and we therefore need to provide good performance in that scenario.
To run:
make check-coroutine ./check-coroutine --benchmark-lifecycle 20000000
This will do 20,000,000 coroutine create, enter, return iterations and print the resulting time.
--- check-coroutine.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 48 insertions(+), 0 deletions(-)
check-coroutine.c +48 -0
@@ -11,8 +11,10 @@* */ +#include <string.h> #include <stdlib.h> #include <stdio.h> +#include <sys/time.h> #include "qemu-coroutine.h" static const char *cur_test_name;
@@ -163,6 +165,43 @@ static void test_lifecycle(void)test_assert (done,"expected done to be true (second time)" ); } +/* +* Lifecycle benchmark +*/ + +static void coroutine_fn empty_coroutine(void *opaque) +{ +/* Do nothing */ +} + +static void benchmark_lifecycle (const char *iterations) +{ +Coroutine *coroutine; +unsigned int i, max; +struct timeval start, finish; +time_t dsec; +suseconds_t dusec; + + max =atoi (iterations); + +gettimeofday (&start,NULL ); +for (i =0 ; i < max; i++) { + coroutine =qemu_coroutine_create (empty_coroutine); +qemu_coroutine_enter (coroutine,NULL ); + } +gettimeofday (&finish,NULL ); + + dsec = finish.tv_sec - start.tv_sec; +if (finish.tv_usec < start.tv_usec) { + dsec--; + dusec = finish.tv_usec +1000000 - start.tv_usec; + }else { + dusec = finish.tv_usec - start.tv_usec; + } +printf ("Lifecycle %u iterations: %lu sec %lu us\n" , + max, dsec, dusec); +} +#define TESTCASE (fn) { #fn, fn }int main (int argc,char **argv) {
@@ -179,6 +218,15 @@ int main(int argc, char **argv) };int i; +if (argc ==3 &&strcmp (argv[1 ],"--benchmark-lifecycle" ) ==0 ) { +benchmark_lifecycle (argv[2 ]); +return EXIT_SUCCESS ; + }else if (argc !=1 ) { +fprintf (stderr,"usage: %s [--benchmark-lifecycle <iterations>]\n" , + argv[0 ]); +return EXIT_FAILURE ; + } +for (i =0 ; testcases[i].name; i++) { cur_test_name = testcases[i].name;printf ("%s\n" , testcases[i].name);
Signature · 1 line
1.7.4.4
PATCH v3 1/4 coroutine: introduce coroutines
In reply to Stefan HajnocziFrom: Kevin Wolf <[email protected]>
Asynchronous code is becoming very complex. At the same time synchronous code is growing because it is convenient to write. Sometimes duplicate code paths are even added, one synchronous and the other asynchronous. This patch introduces coroutines which allow code that looks synchronous but is asynchronous under the covers.
A coroutine has its own stack and is therefore able to preserve state across blocking operations, which traditionally require callback functions and manual marshalling of parameters.
Creating and starting a coroutine is easy:
coroutine = qemu_coroutine_create(my_coroutine); qemu_coroutine_enter(coroutine, my_data);
The coroutine then executes until it returns or yields:
void coroutine_fn my_coroutine(void *opaque) {
MyData *my_data = opaque; /* do some work */
qemu_coroutine_yield();
/* do some more work */}
Yielding switches control back to the caller of qemu_coroutine_enter(). This is typically used to switch back to the main thread's event loop after issuing an asynchronous I/O request. The request callback will then invoke qemu_coroutine_enter() once more to switch back to the coroutine.
Note that coroutines never execute concurrently and should only be used from threads which hold the global mutex. This restriction makes programming with coroutines easier than with threads. Race conditions cannot occur since only one coroutine may be active at any time. Other coroutines can only run across yield.
This coroutines implementation is based on the gtk-vnc implementation written by Anthony Liguori <[email protected]> but it has been significantly rewritten by Kevin Wolf <[email protected]> to use setjmp()/longjmp() instead of the more expensive swapcontext().
--- Makefile.objs | 7 +++ coroutine-ucontext.c | 72 +++++++++++++++++++++++++++++ coroutine-win32.c | 57 +++++++++++++++++++++++ qemu-coroutine-int.h | 53 +++++++++++++++++++++ qemu-coroutine.c | 125 ++++++++++++++++++++++++++++++++++++++++++++++++++ qemu-coroutine.h | 85 ++++++++++++++++++++++++++++++++++ trace-events | 5 ++ 7 files changed, 404 insertions(+), 0 deletions(-) create mode 100644 coroutine-ucontext.c create mode 100644 coroutine-win32.c create mode 100644 qemu-coroutine-int.h create mode 100644 qemu-coroutine.c create mode 100644 qemu-coroutine.h
Makefile.objs +7 -0
@@ -11,6 +11,12 @@ oslib-obj-$(CONFIG_WIN32) += oslib-win32.o qemu-thread-win32.o oslib-obj-$(CONFIG_POSIX) += oslib-posix.o qemu-thread-posix.o ####################################################################### +# coroutines +coroutine-obj-y = qemu-coroutine.o +coroutine-obj-$(CONFIG_POSIX) += coroutine-ucontext.o +coroutine-obj-$(CONFIG_WIN32) += coroutine-win32.o + +####################################################################### # block-obj-y is code used by both qemu system emulation and qemu-img block-obj-y = cutils.o cache-utils.o qemu-malloc.o qemu-option.o module.o async.o
@@ -67,6 +73,7 @@ common-obj-y += readline.o console.o cursor.o qemu-error.o common-obj-y += $(oslib-obj-y) common-obj-$(CONFIG_WIN32) += os-win32.o common-obj-$(CONFIG_POSIX) += os-posix.o +common-obj-y += $(coroutine-obj-y) common-obj-y += tcg-runtime.o host-utils.o common-obj-y += irq.o ioport.o input.o
coroutine-ucontext.c new file +72 -0
72 lines not on this page · raw message
coroutine-win32.c new file +57 -0
57 lines not on this page · raw message
qemu-coroutine-int.h new file +53 -0
53 lines not on this page · raw message
qemu-coroutine.c new file +125 -0
125 lines not on this page · raw message
qemu-coroutine.h new file +85 -0
85 lines not on this page · raw message
trace-events +5 -0
@@ -374,3 +374,8 @@ disable xen_unmap_block(void* addr, unsigned long size) "%p, size %#lx" # exec.c disable qemu_put_ram_ptr(void* addr) "%p" + +# qemu-coroutine.c +disable qemu_coroutine_enter(void *from, void *to, void *opaque) "from %p to %p opaque %p" +disable qemu_coroutine_yield(void *from, void *to) "from %p to %p" +disable qemu_coroutine_terminate(void *co) "self %p"
Signature · 1 line
1.7.4.4
Re: [Qemu-devel] [PATCH v3 1/4] coroutine: introduce coroutines
Quoted 4 lines · Stefan Hajnoczi
This coroutines implementation is based on the gtk-vnc implementation written by Anthony Liguori<[email protected]> but it has been significantly rewritten by Kevin Wolf<[email protected]> to use setjmp()/longjmp() instead of the more expensive
swapcontext().
Since in the future we'll have at least three implementations of coroutines (ucontext, win32 fibers, threads) can you squash in something like the attached to allow "subclassing" of coroutines using DO_UPCAST)?
Resolving conflicts with 4/4 should be trivial
(Sorry for not doing my homework completely; I started describing in English what I had in mind, but it was too much of a mouthful).
Paolo
Quoted 1 line
From
d6798e8d30a5de9381a30638223e8283f0817660Mon Sep 17 00:00:00 2001
From: Paolo Bonzini <[email protected]>
Date: Fri, 13 May 2011 12:20:48 +0200
Subject: [PATCH] allow subclassing of coroutines
--- coroutine-ucontext.c | 45 +++++++++++++++++++++++++++++++++++++-------- coroutine-win32.c | 38 +++++++++++++++++++++++++++++++++----- qemu-coroutine-int.h | 4 ++-- qemu-coroutine.c | 23 ++++++----------------- 4 files changed, 78 insertions(+), 32 deletions(-)
coroutine-ucontext.c +37 -8
@@ -27,11 +27,33 @@#include <ucontext.h> #include "qemu-coroutine-int.h" -static Coroutine *new_coroutine; +struct CoroutineUContext { +Coroutine base; + +jmp_buf env; +}; + +typedef struct CoroutineUContext CoroutineUContext ; + +static CoroutineUContext *new_coroutine; + +int qemu_coroutine_switch (Coroutine *from_,Coroutine *to_,int action) +{ +CoroutineUContext *from =DO_UPCAST (CoroutineUContext, base, from_); +CoroutineUContext *to =DO_UPCAST (CoroutineUContext, base, to_); +int ret; + + ret =setjmp (from->env); +if (ret ==0 ) { +longjmp (to->env, action); + }else { +return ret; + } +}static void continuation_trampoline (void ) { -Coroutine *co = new_coroutine; +CoroutineUContext *co = new_coroutine;/* Initialize longjmp environment and switch back to * qemu_coroutine_init_env() in the old ucontext. */
@@ -40,16 +62,23 @@ static void continuation_trampoline(void) }while (true) { - co->entry (co->data); -if (!setjmp (co->env)) { -longjmp (co->caller->env,COROUTINE_TERMINATE ); - } + co->base.entry (co->base.data); +qemu_coroutine_switch (&co->base, co->base.caller,COROUTINE_TERMINATE ); } } -int qemu_coroutine_init_env (Coroutine *co,size_t stack_size) +Coroutine *qemu_coroutine_new (size_t stack_size) +{ +CoroutineUContext *co; + co =qemu_mallocz (sizeof (*co)); + co->base.stack =qemu_malloc (stack_size); +return &co->base; +} + +int qemu_coroutine_init_env (Coroutine *co_,size_t stack_size) {ucontext_t old_uc, uc; +CoroutineUContext *co =DO_UPCAST (CoroutineUContext, base, co_);/* Create a new ucontext for switching to the coroutine stack and setting * up a longjmp environment. */
@@ -58,7 +87,7 @@ int qemu_coroutine_init_env(Coroutine *co, size_t stack_size) } uc.uc_link = &old_uc; - uc.uc_stack.ss_sp = co->stack; + uc.uc_stack.ss_sp = co->base.stack; uc.uc_stack.ss_size = stack_size; uc.uc_stack.ss_flags =0 ;
coroutine-win32.c +33 -5
@@ -24,20 +24,48 @@#include "qemu-coroutine-int.h" -static void __attribute__((used))trampoline (Coroutine *co) +struct CoroutineWin32 { +Coroutine base; + +jmp_buf env; +}; + +typedef struct CoroutineWin32 CoroutineWin32 ; + +int qemu_coroutine_switch (Coroutine *from_,Coroutine *to_,int action) +{ +CoroutineWin32 *from =DO_UPCAST (CoroutineWin32, base, from_); +CoroutineWin32 *to =DO_UPCAST (CoroutineWin32, base, to_); +int ret; + + ret =setjmp (from->env); +if (ret ==0 ) { +longjmp (to->env, action); + }else { +return ret; + } +} + +static void __attribute__((used))trampoline (CoroutineWin32 *co) {if (!setjmp (co->env)) {return ; }while (true) { - co->entry (co->data); -if (!setjmp (co->env)) { -longjmp (co->caller->env,COROUTINE_TERMINATE ); - } + co->base.entry (co->base.data); +qemu_coroutine_switch (&co->base, co->base.caller,COROUTINE_TERMINATE ); } } +Coroutine *qemu_coroutine_new (size_t stack_size) +{ +CoroutineWin32 *co; + co =qemu_mallocz (sizeof (*co)); + co->base.stack =qemu_malloc (stack_size); +return &co->base; +} +int qemu_coroutine_init_env (Coroutine *co,size_t stack_size) {#ifdef __i386__
qemu-coroutine-int.h +2 -2
@@ -44,10 +44,10 @@ struct Coroutine {/* Used to pass arguments/return values for coroutines */ void *data; CoroutineEntry *entry; - - jmp_buf env; };int qemu_coroutine_init_env (Coroutine *co,size_t stack_size); +int qemu_coroutine_switch (Coroutine *from_,Coroutine *to_,int action); +Coroutine *qemu_coroutine_new (size_t stack_size);#endif
qemu-coroutine.c +6 -17
@@ -34,24 +34,15 @@ static void coroutine_terminate(Coroutine *co)qemu_free (co); } -static Coroutine *coroutine_new (void ) -{ -const size_t stack_size =4 <<20 ; -Coroutine *co; - - co =qemu_mallocz (sizeof (*co)); - co->stack =qemu_malloc (stack_size); -qemu_coroutine_init_env (co, stack_size); -return co; -} -Coroutine *qemu_coroutine_create (CoroutineEntry *entry) { +const size_t stack_size =4 <<20 ;Coroutine *co; - co =coroutine_new (); + co =qemu_coroutine_new (stack_size); co->entry = entry; +qemu_coroutine_init_env (co, stack_size);return co; }
@@ -76,7 +67,8 @@ static void *coroutine_swap(Coroutine *from, Coroutine *to, void *opaque) to->data = opaque; - ret =setjmp (from->env); + current = to; + ret =qemu_coroutine_switch (from, to,COROUTINE_YIELD );switch (ret) {case COROUTINE_YIELD :return from->data;
@@ -86,10 +78,7 @@ static void *coroutine_swap(Coroutine *from, Coroutine *to, void *opaque)coroutine_terminate (to);return to_data;default : -/* Switch to called coroutine */ - current = to; -longjmp (to->env,COROUTINE_YIELD ); -return NULL ; +abort (); } }
Signature · 1 line
1.7.4.4
Re: [Qemu-devel] [PATCH v3 1/4] coroutine: introduce coroutines
Quoted 11 lines · Paolo Bonzini
Quoted 5 lines · Stefan Hajnoczi
This coroutines implementation is based on the gtk-vnc implementation written by Anthony Liguori<[email protected]> but it has been significantly rewritten by Kevin Wolf<[email protected]> to use setjmp()/longjmp() instead of the more expensive
swapcontext().Since in the future we'll have at least three implementations of coroutines (ucontext, win32 fibers, threads) can you squash in something like the attached to allow "subclassing" of coroutines using
DO_UPCAST)? Resolving conflicts with 4/4 should be trivial
Yes, I'll tweak your patch and add it.
Stefan
Quoted 22 lines · Stefan Hajnoczi
QEMU is event-driven and suffers when blocking operations are performed because VM execution may be stopped until the operation completes. Therefore many operations that could block are performed asynchronously and a callback is invoked when the operation has completed. This allows QEMU to continue executing while the operation is pending.
The downside to callbacks is that they split up code into many smaller functions, each of which is a single step in a state machine that quickly becomes complex and hard to understand. Callback functions also result in lots of noise as variables are packed and unpacked into temporary structs that pass state to the callback function.
This patch series introduces coroutines as a solution for writing asynchronous code while still having a nice sequential control flow. The semantics are explained in the first patch. The second patch adds automated tests.
A nice feature of coroutines is that it is relatively easy to take synchronous code and lift it into a coroutine to make it asynchronous. Work has been done to move qcow2 request processing into coroutines and thereby make it asynchronous (today qcow2 will perform synchronous metadata accesses). This qcow2 work is still ongoing and not quite ready for mainline yet.
Quoted 5 lines
Coroutines are also being used for virtfs (virtio-9p) so I have submitted this patch now because virtfs patches that depend on coroutines are being published.
Other areas of QEMU that could take advantage of coroutines include the VNC server, migration, and qemu-tools.
Hum, the VNC server is already threaded, how would coroutines help ? Do you plan to rewrite the server using coroutines instead of threads ?
Thanks
Signature · 2 lines
Corentin Chary http://xf.iksaif.net
Quoted 27 lines · Corentin Chary
Quoted 25 lines · Stefan Hajnoczi
QEMU is event-driven and suffers when blocking operations are performed because VM execution may be stopped until the operation completes. Therefore many operations that could block are performed asynchronously and a callback is invoked when the operation has completed. This allows QEMU to continue executing while the operation is pending.
The downside to callbacks is that they split up code into many smaller functions, each of which is a single step in a state machine that quickly becomes complex and hard to understand. Callback functions also result in lots of noise as variables are packed and unpacked into temporary structs that pass state to the callback function.
This patch series introduces coroutines as a solution for writing asynchronous code while still having a nice sequential control flow. The semantics are explained in the first patch. The second patch adds automated tests.
A nice feature of coroutines is that it is relatively easy to take synchronous code and lift it into a coroutine to make it asynchronous. Work has been done to move qcow2 request processing into coroutines and thereby make it asynchronous (today qcow2 will perform synchronous metadata accesses). This qcow2 work is still ongoing and not quite ready for mainline yet.
Coroutines are also being used for virtfs (virtio-9p) so I have submitted this patch now because virtfs patches that depend on coroutines are being published.
Quoted 6 lines
Quoted 2 lines
Other areas of QEMU that could take advantage of coroutines include the VNC server, migration, and qemu-tools.
Hum, the VNC server is already threaded, how would coroutines help ? Do you plan to rewrite the server using coroutines instead of threads ?
The main control flow in the VNC server is a state-machine. Imagine a VNC session running as sequential code in a coroutine instead of being broken up across callbacks. I think it would be easier to follow although rewriting it now may not be worth the effort unless significant future VNC work is planned for the future.
Stefan