Skip to contentSkip to conversation

Coroutines for better asynchronous programming

PATCH Superseded Stefan Hajnoczi 4 participants 20 messages Jun 12, 2011 – Jun 30, 2011 Kbuild

v5 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v5 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 second patch. The fourth 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.

v5:
* GThread-based implementation for platforms without makecontext(3) (Aneesh Kumar K.V <[email protected]>)
* Switch to gtester test framework

v4:
* Windows Fibers support (Paolo Bonzini <[email protected]>)
* Return-after-setjmp() fix (Aneesh Kumar K.V <[email protected]>)
* Re-entrancy for multi-threaded coroutines support
* qemu-coroutine.h cleanup and documentation

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

Aneesh Kumar K.V (1):
coroutine: implement coroutines using gthread

Anthony Liguori (1):
Add hard build dependency on glib

Kevin Wolf (1):
coroutine: introduce coroutines

Stefan Hajnoczi (2):
coroutine: add check-coroutine automated tests
coroutine: add check-coroutine --benchmark-lifecycle

 .gitignore           |    1 +
 Makefile             |    5 +-
 Makefile.objs        |   13 +++
 Makefile.target      |    1 +
 configure            |   29 +++++++
 coroutine-gthread.c  |  131 ++++++++++++++++++++++++++++
 coroutine-ucontext.c |  229 ++++++++++++++++++++++++++++++++++++++++++++++++++
 coroutine-win32.c    |   92 ++++++++++++++++++++
 qemu-coroutine-int.h |   48 +++++++++++
 qemu-coroutine.c     |   75 ++++++++++++++++
 qemu-coroutine.h     |   95 +++++++++++++++++++++
 test-coroutine.c     |  192 ++++++++++++++++++++++++++++++++++++++++++
 trace-events         |    5 +
 13 files changed, 915 insertions(+), 1 deletions(-)
 create mode 100644 coroutine-gthread.c
 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
 create mode 100644 test-coroutine.c
Signature · 1 line
1.7.5.3
#1 lore raw

PATCH v5 1/5 Add hard build dependency on glib

From: Anthony Liguori <[email protected]>

GLib is an extremely common library that has a portable thread implementation along with tons of other goodies.

GLib and GObject have a fantastic amount of infrastructure we can leverage in QEMU including an object oriented programming infrastructure.

Short term, it has a very nice thread pool implementation that we could leverage in something like virtio-9p. It also has a test harness implementation that this series will use.

---
 Makefile        |    2 ++
 Makefile.objs   |    2 ++
 Makefile.target |    1 +
 configure       |   13 +++++++++++++
 4 files changed, 18 insertions(+), 0 deletions(-)
Makefile +2 -0
index 096480b..306cd9b 100644
@@ -106,6 +106,8 @@ audio/audio.o audio/fmodaudio.o: QEMU_CFLAGS += $(FMOD_CFLAGS)
 
 QEMU_CFLAGS+=$(CURL_CFLAGS)
 
+QEMU_CFLAGS+=$(GLIB_CFLAGS)
+
 ui/cocoa.o: ui/cocoa.m
 
 ui/sdl.o audio/sdlaudio.o ui/sdl_zoom.o baum.o: QEMU_CFLAGS += $(SDL_CFLAGS)
Makefile.objs +2 -0
index 52d8b23..a7807e8 100644
@@ -368,3 +368,5 @@ vl.o: QEMU_CFLAGS+=$(GPROF_CFLAGS)
 
 vl.o: QEMU_CFLAGS+=$(SDL_CFLAGS)
 
+vl.o: QEMU_CFLAGS+=$(GLIB_CFLAGS)
+
Makefile.target +1 -0
index b1a0f6d..0d900e2 100644
@@ -202,6 +202,7 @@ QEMU_CFLAGS += $(VNC_TLS_CFLAGS)
 QEMU_CFLAGS += $(VNC_SASL_CFLAGS)
 QEMU_CFLAGS += $(VNC_JPEG_CFLAGS)
 QEMU_CFLAGS += $(VNC_PNG_CFLAGS)
+QEMU_CFLAGS += $(GLIB_CFLAGS)
 
 # xen backend driver support
 obj-i386-$(CONFIG_XEN) += xen_machine_pv.o xen_domainbuild.o
configure +13 -0
index 663b557..3697eba 100755
@@ -1767,6 +1767,18 @@ EOF
 fi
 
 ##########################################
+# glib support probe
+if $pkg_config --modversion gthread-2.0 gio-2.0 > /dev/null 2>&1 ; then
+    glib_cflags=`$pkg_config --cflags gthread-2.0 gio-2.0 2>/dev/null`
+    glib_libs=`$pkg_config --libs gthread-2.0 gio-2.0 2>/dev/null`
+    libs_softmmu="$glib_libs $libs_softmmu"
+    libs_tools="$glib_libs $libs_tools"
+else
+    echo "glib-2.0 required to compile QEMU"
+    exit 1
+fi
+
+##########################################
 # kvm probe
 if test "$kvm" != "no" ; then
     cat > $TMPC <<EOF
@@ -2923,6 +2935,7 @@ if test "$bluez" = "yes" ; then
   echo "CONFIG_BLUEZ=y" >> $config_host_mak
   echo "BLUEZ_CFLAGS=$bluez_cflags" >> $config_host_mak
 fi
+echo "GLIB_CFLAGS=$glib_cflags" >> $config_host_mak
 if test "$xen" = "yes" ; then
   echo "CONFIG_XEN=y" >> $config_host_mak
   echo "CONFIG_XEN_CTRL_INTERFACE_VERSION=$xen_ctrl_version" >> $config_host_mak
Signature · 1 line
1.7.5.3
#2 lore raw

Re: [Qemu-devel] [PATCH v5 1/5] Add hard build dependency on glib

Am 12.06.2011 um 22:46 schrieb Stefan Hajnoczi:

Quoted 7 lines

From: Anthony Liguori <[email protected]>

GLib is an extremely common library that has a portable thread implementation along with tons of other goodies.

GLib and GObject have a fantastic amount of infrastructure we can leverage in QEMU including an object oriented programming infrastructure.

GObject still doesn't build on Darwin/ppc64:

CC gboxed.lo
../../glib-2.28.8/gobject/gboxed.c: In function 'g_closure_get_type':
../../glib-2.28.8/gobject/gboxed.c:120: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:120: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:120: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:120: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_value_get_type':
../../glib-2.28.8/gobject/gboxed.c:121: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:121: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:121: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:121: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_value_array_get_type':
../../glib-2.28.8/gobject/gboxed.c:122: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:122: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:122: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:122: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_date_get_type':
../../glib-2.28.8/gobject/gboxed.c:123: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:123: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:123: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:123: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_gstring_get_type':
../../glib-2.28.8/gobject/gboxed.c:125: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:125: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:125: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:125: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_hash_table_get_type':
../../glib-2.28.8/gobject/gboxed.c:126: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:126: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:126: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:126: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_array_get_type':
../../glib-2.28.8/gobject/gboxed.c:127: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:127: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:127: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:127: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_ptr_array_get_type':
../../glib-2.28.8/gobject/gboxed.c:128: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:128: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:128: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:128: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_byte_array_get_type':
../../glib-2.28.8/gobject/gboxed.c:129: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:129: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:129: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:129: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_regex_get_type':
../../glib-2.28.8/gobject/gboxed.c:132: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:132: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:132: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:132: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_variant_type_get_gtype':
../../glib-2.28.8/gobject/gboxed.c:138: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:138: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:138: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:138: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_error_get_type':
../../glib-2.28.8/gobject/gboxed.c:141: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:141: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:141: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:141: error: incompatible type for argument 3 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c: In function 'g_date_time_get_type':
../../glib-2.28.8/gobject/gboxed.c:143: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:143: warning: union cannot be made transparent ../../glib-2.28.8/gobject/gboxed.c:143: error: incompatible type for argument 2 of '_g_register_boxed' ../../glib-2.28.8/gobject/gboxed.c:143: error: incompatible type for argument 3 of '_g_register_boxed' make[4]: *** [gboxed.lo] Error 1
make[3]: *** [all-recursive] Error 1
make[2]: *** [all] Error 2
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2

With both gcc 4.0.1 and 4.2.1, using CC="gcc -arch ppc64" CPPFLAGS="-arch ppc64" and supplying GNU gettext and GNU libiconv (since it chokes on the system iconv.h). No Google hit.

Any thoughts?

Andreas

#3 lore raw

Re: [Qemu-devel] [PATCH v5 1/5] Add hard build dependency on glib

Quoted 3 lines · Andreas Färber

With both gcc 4.0.1 and 4.2.1, using CC="gcc -arch ppc64" CPPFLAGS="-arch ppc64" and supplying GNU gettext and GNU libiconv (since it chokes on the system iconv.h). No Google hit.

Strange, Fink seems to support it:
http://pdb.finkproject.org/pdb/package.php/glib2-dev

Stefan

#4 lore raw

Re: [Qemu-devel] [PATCH v5 1/5] Add hard build dependency on glib

Am 18.06.2011 um 19:21 schrieb Stefan Hajnoczi:

Quoted 8 lines

On Sat, Jun 18, 2011 at 5:15 PM, Andreas Färber <[email protected]

Quoted 4 lines

wrote:
With both gcc 4.0.1 and 4.2.1, using CC="gcc -arch ppc64" CPPFLAGS="-arch ppc64" and supplying GNU gettext and GNU libiconv (since it chokes on the system iconv.h). No Google hit.

Strange, Fink seems to support it:
http://pdb.finkproject.org/pdb/package.php/glib2-dev

Says nothing about powerpc64...

Andreas

#5 lore raw

Re: [Qemu-devel] [PATCH v5 1/5] Add hard build dependency on glib

Quoted 5 lines · Andreas Färber

Am 18.06.2011 um 19:21 schrieb Stefan Hajnoczi:

Quoted 3 lines
Quoted 1 line · Andreas Färber
Quoted 8 lines
Quoted 6 lines
Quoted 3 lines

With both gcc 4.0.1 and 4.2.1, using CC="gcc -arch ppc64" CPPFLAGS="-arch ppc64" and supplying GNU gettext and GNU libiconv (since it chokes on the system iconv.h). No Google hit.

Strange, Fink seems to support it:
http://pdb.finkproject.org/pdb/package.php/glib2-dev

Says nothing about powerpc64...

Shows my ignorance of Mac or Darwin :). I figured 10.5/powerpc is what you're after.

Stefan

#6 lore raw

Re: [Qemu-devel] [PATCH v5 1/5] Add hard build dependency on glib

Am 18.06.2011 um 22:46 schrieb Stefan Hajnoczi:

Quoted 12 lines

On Sat, Jun 18, 2011 at 8:44 PM, Andreas Färber <[email protected]

Quoted 11 lines

wrote:
Am 18.06.2011 um 19:21 schrieb Stefan Hajnoczi:

Quoted 8 lines

On Sat, Jun 18, 2011 at 5:15 PM, Andreas Färber <[email protected]

Quoted 1 line
Quoted 4 lines · wrote:

With both gcc 4.0.1 and 4.2.1, using CC="gcc -arch ppc64" CPPFLAGS="-arch ppc64" and supplying GNU gettext and GNU libiconv (since it chokes on the system iconv.h). No Google hit.

Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

Strange, Fink seems to support it:
http://pdb.finkproject.org/pdb/package.php/glib2-dev

Says nothing about powerpc64...

Shows my ignorance of Mac or Darwin :). I figured 10.5/powerpc is what you're after.

No prob, it was a very short-lived technology - arrived in v10.4 half-done, became usable in v10.5 and was dropped in v10.6 in favor of Intel. You have the same ppc vs. ppc64 split for Linux packages btw.

GLib 2.22.4 finished building okay now. I've filed a bug against GLib. Hope it works at runtime.

Andreas

#7 lore raw

Re: [Qemu-devel] [PATCH v5 1/5] Add hard build dependency on glib

In reply to Stefan Hajnoczi

Am 12.06.2011 um 22:46 schrieb Stefan Hajnoczi:

Quoted 80 lines

From: Anthony Liguori <[email protected]>

GLib is an extremely common library that has a portable thread implementation along with tons of other goodies.

GLib and GObject have a fantastic amount of infrastructure we can leverage in QEMU including an object oriented programming infrastructure.

Short term, it has a very nice thread pool implementation that we could leverage in something like virtio-9p. It also has a test harness implementation that this series will use.

---

Makefile        |    2 ++
Makefile.objs   |    2 ++
Makefile.target |    1 +
configure       |   13 +++++++++++++
4 files changed, 18 insertions(+), 0 deletions(-)
Makefile +2 -0
index 096480b..306cd9b 100644
@@ -106,6 +106,8 @@ audio/audio.o audio/fmodaudio.o: QEMU_CFLAGS += $ 
 (FMOD_CFLAGS)
 
 QEMU_CFLAGS+=$(CURL_CFLAGS)
 
+QEMU_CFLAGS+=$(GLIB_CFLAGS)
+

ui/cocoa.o: ui/cocoa.m

ui/sdl.o audio/sdlaudio.o ui/sdl_zoom.o baum.o: QEMU_CFLAGS += $(SDL_CFLAGS)

Makefile.objs +2 -0
index 52d8b23..a7807e8 100644
@@ -368,3 +368,5 @@ vl.o: QEMU_CFLAGS+=$(GPROF_CFLAGS)
 
 vl.o: QEMU_CFLAGS+=$(SDL_CFLAGS)
 
+vl.o: QEMU_CFLAGS+=$(GLIB_CFLAGS)
+
Makefile.target +1 -0
index b1a0f6d..0d900e2 100644
@@ -202,6 +202,7 @@ QEMU_CFLAGS += $(VNC_TLS_CFLAGS)
 QEMU_CFLAGS += $(VNC_SASL_CFLAGS)
 QEMU_CFLAGS += $(VNC_JPEG_CFLAGS)
 QEMU_CFLAGS += $(VNC_PNG_CFLAGS)
+QEMU_CFLAGS += $(GLIB_CFLAGS)
 
 # xen backend driver support

obj-i386-$(CONFIG_XEN) += xen_machine_pv.o xen_domainbuild.o

configure +0 -0
index 663b557..3697eba 100755
@@ -1767,6 +1767,18 @@ EOF

fi

##########################################

configure +2 -0
+# glib support probe
+if $pkg_config --modversion gthread-2.0 gio-2.0 > /dev/null 2>&1 ;  

then
+ glib_cflags=`$pkg_config --cflags gthread-2.0 gio-2.0 2>/dev/
null`

configure +9 -0
+    glib_libs=`$pkg_config --libs gthread-2.0 gio-2.0 2>/dev/null`
+    libs_softmmu="$glib_libs $libs_softmmu"
+    libs_tools="$glib_libs $libs_tools"
+else
+    echo "glib-2.0 required to compile QEMU"
+    exit 1
+fi
+
+##########################################
Quoted 3 lines
# kvm probe
if test "$kvm" != "no" ; then
    cat > $TMPC <<EOF

This hunk no longer applies.

Andreas

Quoted 13 lines
configure +0 -0
@@ -2923,6 +2935,7 @@ if test "$bluez" = "yes" ; then
  echo "CONFIG_BLUEZ=y" >> $config_host_mak
  echo "BLUEZ_CFLAGS=$bluez_cflags" >> $config_host_mak

fi
+echo "GLIB_CFLAGS=$glib_cflags" >> $config_host_mak if test "$xen" = "yes" ; then
echo "CONFIG_XEN=y" >> $config_host_mak
echo "CONFIG_XEN_CTRL_INTERFACE_VERSION=$xen_ctrl_version" >>
$config_host_mak

Signature · 1 line
1.7.5.3
#8 lore raw

PATCH v5 2/5 coroutine: introduce coroutines

In reply to Stefan Hajnoczi

From: 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 if coroutines are used only from threads which hold the global mutex they will never execute concurrently. This 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() and by Paolo Bonzini <[email protected]> for Windows Fibers support.

---
 Makefile.objs        |    7 ++
 coroutine-ucontext.c |  229 ++++++++++++++++++++++++++++++++++++++++++++++++++
 coroutine-win32.c    |   92 ++++++++++++++++++++
 qemu-coroutine-int.h |   48 +++++++++++
 qemu-coroutine.c     |   75 ++++++++++++++++
 qemu-coroutine.h     |   95 +++++++++++++++++++++
 trace-events         |    5 +
 7 files changed, 551 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
index a7807e8..1890944 100644
@@ -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
@@ -69,6 +75,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 +229 -0

229 lines not on this page · raw message

coroutine-win32.c new file +92 -0

92 lines not on this page · raw message

qemu-coroutine-int.h new file +48 -0

48 lines not on this page · raw message

qemu-coroutine.c new file +75 -0

75 lines not on this page · raw message

qemu-coroutine.h new file +95 -0

95 lines not on this page · raw message

trace-events +5 -0
index e0e9574..e0a4d83 100644
@@ -386,3 +386,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.5.3
#9 lore raw

Re: [Qemu-devel] [PATCH v5 2/5] coroutine: introduce coroutines

Am 12.06.2011 um 22:46 schrieb Stefan Hajnoczi:

Quoted 78 lines

From: 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 if coroutines are used only from threads which hold the global mutex they will never execute concurrently. This 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() and by Paolo Bonzini <[email protected]> for Windows Fibers support.

---
Makefile.objs | 7 ++
coroutine-ucontext.c | 229 +++++++++++++++++++++++++++++++++++++++++
+++++++++

coroutine-win32.c    |   92 ++++++++++++++++++++
qemu-coroutine-int.h |   48 +++++++++++
qemu-coroutine.c     |   75 ++++++++++++++++
qemu-coroutine.h     |   95 +++++++++++++++++++++
trace-events         |    5 +
7 files changed, 551 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

trace-events +0 -0
index e0e9574..e0a4d83 100644
@@ -386,3 +386,8 @@ disable xen_unmap_block(void* addr, unsigned  

long size) "%p, size %#lx"

# exec.c
disable qemu_put_ram_ptr(void* addr) "%p"
trace-events +3 -0
+
+# qemu-coroutine.c
+disable qemu_coroutine_enter(void *from, void *to, void *opaque)  

"from %p to %p opaque %p"

trace-events disable xen_unmap_block(void* addr, unsigned long size) "%p, size %#lx" · line 393

Quoted 2 lines
trace-events +2 -0
+disable qemu_coroutine_yield(void *from, void *to) "from %p to %p"
+disable qemu_coroutine_terminate(void *co) "self %p"

This hunk no longer applies.

Andreas

#10 lore raw

Re: [Qemu-devel] [PATCH v5 2/5] coroutine: introduce coroutines

In reply to Stefan Hajnoczi

Am 12.06.2011 um 22:46 schrieb Stefan Hajnoczi:

Quoted 87 lines

From: 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 if coroutines are used only from threads which hold the global mutex they will never execute concurrently. This 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() and by Paolo Bonzini <[email protected]> for Windows Fibers support.

---
Makefile.objs | 7 ++
coroutine-ucontext.c | 229 +++++++++++++++++++++++++++++++++++++++++
+++++++++

coroutine-win32.c    |   92 ++++++++++++++++++++
qemu-coroutine-int.h |   48 +++++++++++
qemu-coroutine.c     |   75 ++++++++++++++++
qemu-coroutine.h     |   95 +++++++++++++++++++++
trace-events         |    5 +
7 files changed, 551 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

coroutine-ucontext.c new file +9 -0
new file mode 100644
index 0000000..bcea2bd
 
+static Coroutine *coroutine_new(void)
+{
+    const size_t stack_size = 4 << 20;
+    CoroutineUContext *co;
+    ucontext_t old_uc, uc;
+    jmp_buf old_env;
+    union cc_arg arg;
+
+    /* The ucontext functions preserve signal masks which incurs a  

system call
+ * overhead. setjmp()/longjmp() does not preserve signal masks
but only
+ * works on the current stack. Since we need a way to create
and switch to
+ * a new stack, use the ucontext functions for that but
setjmp()/longjmp()

coroutine-ucontext.c line 145

Quoted 5 lines
coroutine-ucontext.c new file +5 -0
+     * for everything else.
+     */
+
+    if (getcontext(&uc) == -1) {
+        return NULL;

We figured out: on Darwin/ppc64 we run into this code path, with errno = ENOTSUP. Same for Darwin/ppc, v10.5.8.

Quoted 24 lines
coroutine-ucontext.c new file +24 -0
+    }
+
+    co = qemu_mallocz(sizeof(*co));
+    co->stack = qemu_malloc(stack_size);
+    co->base.entry_arg = &old_env; /* stash away our jmp_buf */
+
+    uc.uc_link = &old_uc;
+    uc.uc_stack.ss_sp = co->stack;
+    uc.uc_stack.ss_size = stack_size;
+    uc.uc_stack.ss_flags = 0;
+
+    arg.p = co;
+
+    makecontext(&uc, (void (*)(void))coroutine_trampoline,
+                2, arg.i[0], arg.i[1]);
+
+    /* swapcontext() in, longjmp() back out */
+    if (!setjmp(old_env)) {
+        swapcontext(&old_uc, &uc);
+    }
+    return &co->base;
+}
+
+Coroutine *qemu_coroutine_new(void)

coroutine-ucontext.c line 179

Quoted 10 lines
coroutine-ucontext.c new file +10 -0
+{
+    CoroutineThreadState *s = coroutine_get_thread_state();
+    Coroutine *co;
+
+    co = QLIST_FIRST(&s->pool);
+    if (co) {
+        QLIST_REMOVE(co, pool_next);
+        s->pool_size--;
+    } else {
+        co = coroutine_new();

Return value is not checked ...

coroutine-ucontext.c

Quoted 2 lines
coroutine-ucontext.c new file +2 -0
+    }
+    return co;

... and passed through.

Quoted 1 line

+}

Caller in test-coroutine.c doesn't check either. Maybe better abort instead of returning NULL?

Andreas

#11 lore raw

PATCH v5 3/5 coroutine: implement coroutines using gthread

In reply to Stefan Hajnoczi

From: "Aneesh Kumar K.V" <[email protected]>

On platforms that don't support makecontext(3) use gthread based coroutine implementation.

[Original patch by Aneesh, made consistent with coroutine-ucontext.c and switched to GStaticPrivate by Stefan. Tested on Linux and OpenBSD.]

---
 Makefile.objs       |    4 ++
 configure           |   16 ++++++
 coroutine-gthread.c |  131 +++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 151 insertions(+), 0 deletions(-)
 create mode 100644 coroutine-gthread.c
Makefile.objs +4 -0
index 1890944..8333f5a 100644
@@ -13,7 +13,11 @@ oslib-obj-$(CONFIG_POSIX) += oslib-posix.o qemu-thread-posix.o
 #######################################################################
 # coroutines
 coroutine-obj-y = qemu-coroutine.o
+ifeq ($(CONFIG_UCONTEXT_COROUTINE),y)
 coroutine-obj-$(CONFIG_POSIX) += coroutine-ucontext.o
+else
+coroutine-obj-$(CONFIG_POSIX) += coroutine-gthread.o
+endif
 coroutine-obj-$(CONFIG_WIN32) += coroutine-win32.o
 
 #######################################################################
configure +16 -0
index 3697eba..df63403 100755
@@ -2552,6 +2552,18 @@ if test "$trace_backend" = "dtrace"; then
 fi
 
 ##########################################
+# check if we have makecontext
+
+ucontext_coroutine=no
+cat > $TMPC << EOF
+#include <ucontext.h>
+int main(void) { makecontext(0, 0, 0); }
+EOF
+if compile_prog "" "" ; then
+    ucontext_coroutine=yes
+fi
+
+##########################################
 # End of CC checks
 # After here, no more $cc or $ld runs
 
@@ -3015,6 +3027,10 @@ if test "$rbd" = "yes" ; then
   echo "CONFIG_RBD=y" >> $config_host_mak
 fi
 
+if test "$ucontext_coroutine" = "yes" ; then
+  echo "CONFIG_UCONTEXT_COROUTINE=y" >> $config_host_mak
+fi
+
 # USB host support
 case "$usb" in
 linux)
coroutine-gthread.c new file +131 -0

131 lines not on this page · raw message

Signature · 1 line
1.7.5.3
#12 lore raw

Re: [Qemu-devel] [PATCH v5 3/5] coroutine: implement coroutines using gthread

Am 12.06.2011 um 22:46 schrieb Stefan Hajnoczi:

Quoted 38 lines

From: "Aneesh Kumar K.V" <[email protected]>

On platforms that don't support makecontext(3) use gthread based coroutine implementation.

[Original patch by Aneesh, made consistent with coroutine-ucontext.c and switched to GStaticPrivate by Stefan. Tested on Linux and OpenBSD.]

---

Makefile.objs       |    4 ++
configure           |   16 ++++++
coroutine-gthread.c |  131 ++++++++++++++++++++++++++++++++++++++++++ 
+++++++++
3 files changed, 151 insertions(+), 0 deletions(-)

create mode 100644 coroutine-gthread.c

configure +0 -0
index 3697eba..df63403 100755
@@ -2552,6 +2552,18 @@ if test "$trace_backend" = "dtrace"; then

fi

##########################################

configure +12 -0
+# check if we have makecontext
+
+ucontext_coroutine=no
+cat > $TMPC << EOF
+#include <ucontext.h>
+int main(void) { makecontext(0, 0, 0); }
+EOF
+if compile_prog "" "" ; then
+    ucontext_coroutine=yes
+fi
+
+##########################################
Quoted 3 lines

# End of CC checks
# After here, no more $cc or $ld runs

This add-on patch inserts a check for Darwin to force ucontext_coroutine=no there (getcontext() returns -1, with errno == ENOTSUP):

configure +5 -3
index c28ed7b..854f24a 100755
@@ -2479,12 +2479,14 @@ fi
 # check if we have makecontext
 
 ucontext_coroutine=no
-cat > $TMPC << EOF
+if test "$darwin" != "yes"; then
+    cat > $TMPC << EOF
 #include <ucontext.h>
 int main(void) { makecontext(0, 0, 0); }
 EOF
-if compile_prog "" "" ; then
-    ucontext_coroutine=yes
+    if compile_prog "" "" ; then
+        ucontext_coroutine=yes
+    fi
 fi
 
 ##########################################

This fixes Darwin/ppc64 (and ppc) v10.5.
Don't know whether v10.6 / i386 might have a working implementation (cc'ing Alexand{re,er}).

Andreas

Quoted 11 lines
configure +0 -0
@@ -3015,6 +3027,10 @@ if test "$rbd" = "yes" ; then
  echo "CONFIG_RBD=y" >> $config_host_mak

fi

configure +4 -0
+if test "$ucontext_coroutine" = "yes" ; then
+  echo "CONFIG_UCONTEXT_COROUTINE=y" >> $config_host_mak
+fi
+

# USB host support
case "$usb" in
linux)

#13 lore raw

Re: [Qemu-devel] [PATCH v5 3/5] coroutine: implement coroutines using gthread

Hi Andreas,

Quoted 3 lines

This fixes Darwin/ppc64 (and ppc) v10.5.
Don't know whether v10.6 / i386 might have a working implementation (cc'ing Alexand{re,er}).

In 10.6, I get the following error when I try to compile a simple getcontext():
/usr/include/ucontext.h:42:2: error: #error ucontext routines are deprecated, and require _XOPEN_SOURCE to be defined

On the other hand, if I do define _XOPEN_SOURCE, getcontext() returns 0.

Alexandre

#14 lore raw

PATCH v5 4/5 coroutine: add check-coroutine automated tests

In reply to Stefan Hajnoczi

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.

---
 .gitignore       |    1 +
 Makefile         |    3 +-
 test-coroutine.c |  162 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 165 insertions(+), 1 deletions(-)
 create mode 100644 test-coroutine.c
.gitignore +1 -0
index 08013fc..3ad334a 100644
@@ -34,6 +34,7 @@ qemu-img-cmds.h
 qemu-io
 qemu-monitor.texi
 QMP/qmp-commands.txt
+test-coroutine
 .gdbinit
 *.a
 *.aux
Makefile +2 -1
index 306cd9b..6b5899a 100644
@@ -134,7 +134,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 test-coroutine.o: $(GENERATED_HEADERS)
 
 CHECK_PROG_DEPS = qemu-malloc.o $(oslib-obj-y) $(trace-obj-y) qemu-tool.o
 
@@ -144,6 +144,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 error.o qerror.o qemu-error.o $(CHECK_PROG_DEPS)
+test-coroutine: test-coroutine.o $(coroutine-obj-y) $(CHECK_PROG_DEPS)
 
 QEMULIBS=libhw32 libhw64 libuser libdis libdis-user
 
test-coroutine.c new file +162 -0

162 lines not on this page · raw message

Signature · 1 line
1.7.5.3
#15 lore raw

Re: [Qemu-devel] [PATCH v5 4/5] coroutine: add check-coroutine automated tests

Am 12.06.2011 um 22:46 schrieb Stefan Hajnoczi:

Quoted 4 lines

To run automated tests for coroutines:

make check-coroutine
./check-coroutine

The commit message doesn't correspond to the changes, it's test-coroutine below.

$ ./test-coroutine
/basic/lifecycle: Segmentation fault

Compiles without warnings but crashes at runtime on Darwin/ppc64. It's using coroutine-ucontext.o implementation.

(gdb) run
Starting program: /Users/andreas/QEMU/qemu64/test-coroutine
warning: posix_spawn failed, trying execvp, error: 86
Reading symbols for shared libraries ++++++++++++++....................................................................... done /basic/lifecycle:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
qemu_coroutine_create (entry=0x2b10 <set_and_exit>) at /Users/andreas/QEMU/qemu/qemu-coroutine.c:23
23 co->entry = entry;
(gdb)

Andreas

Quoted 226 lines

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.

---

.gitignore       |    1 +
Makefile         |    3 +-
test-coroutine.c |  162 +++++++++++++++++++++++++++++++++++++++++++++ 
+++++++++
3 files changed, 165 insertions(+), 1 deletions(-)

create mode 100644 test-coroutine.c

.gitignore +0 -0
index 08013fc..3ad334a 100644
@@ -34,6 +34,7 @@ qemu-img-cmds.h

qemu-io
qemu-monitor.texi
QMP/qmp-commands.txt
+test-coroutine
.gdbinit
*.a
*.aux

Makefile +0 -0
index 306cd9b..6b5899a 100644
@@ -134,7 +134,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 test-coroutine.o: $(GENERATED_HEADERS)

CHECK_PROG_DEPS = qemu-malloc.o $(oslib-obj-y) $(trace-obj-y) qemu-tool.o

Makefile +0 -0
@@ -144,6 +144,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 error.o qerror.o qemu-error.o $(CHECK_PROG_DEPS) +test-coroutine: test-coroutine.o $(coroutine-obj-y) $
(CHECK_PROG_DEPS)

QEMULIBS=libhw32 libhw64 libuser libdis libdis-user

test-coroutine.c new file +9 -0
new file mode 100644
index 0000000..9e9d3c9
@@ -0,0 +1,162 @@
+/*
+ * Coroutine tests
+ *
+ * Copyright IBM, Corp. 2011
+ *
+ * Authors:
+ *  Stefan Hajnoczi    <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU LGPL, version 2  

or later.
+ * See the COPYING.LIB file in the top-level directory.
+ *
+ */

test-coroutine.c new file +150 -0
+
+#include <glib.h>
+#include "qemu-coroutine.h"
+
+/*
+ * Check that qemu_in_coroutine() works
+ */
+
+static void coroutine_fn verify_in_coroutine(void *opaque)
+{
+    g_assert(qemu_in_coroutine());
+}
+
+static void test_in_coroutine(void)
+{
+    Coroutine *coroutine;
+
+    g_assert(!qemu_in_coroutine());
+
+    coroutine = qemu_coroutine_create(verify_in_coroutine);
+    qemu_coroutine_enter(coroutine, NULL);
+}
+
+/*
+ * Check that qemu_coroutine_self() works
+ */
+
+static void coroutine_fn verify_self(void *opaque)
+{
+    g_assert(qemu_coroutine_self() == opaque);
+}
+
+static void test_self(void)
+{
+    Coroutine *coroutine;
+
+    coroutine = qemu_coroutine_create(verify_self);
+    qemu_coroutine_enter(coroutine, coroutine);
+}
+
+/*
+ * Check that coroutines may nest multiple levels
+ */
+
+typedef struct {
+    unsigned int n_enter;   /* num coroutines entered */
+    unsigned int n_return;  /* num coroutines returned */
+    unsigned int max;       /* maximum level of nesting */
+} NestData;
+
+static void coroutine_fn nest(void *opaque)
+{
+    NestData *nd = opaque;
+
+    nd->n_enter++;
+
+    if (nd->n_enter < nd->max) {
+        Coroutine *child;
+
+        child = qemu_coroutine_create(nest);
+        qemu_coroutine_enter(child, nd);
+    }
+
+    nd->n_return++;
+}
+
+static void test_nesting(void)
+{
+    Coroutine *root;
+    NestData nd = {
+        .n_enter  = 0,
+        .n_return = 0,
+        .max      = 128,
+    };
+
+    root = qemu_coroutine_create(nest);
+    qemu_coroutine_enter(root, &nd);
+
+    /* Must enter and return from max nesting level */
+    g_assert_cmpint(nd.n_enter, ==, nd.max);
+    g_assert_cmpint(nd.n_return, ==, nd.max);
+}
+
+/*
+ * Check that yield/enter transfer control correctly
+ */
+
+static void coroutine_fn yield_5_times(void *opaque)
+{
+    bool *done = opaque;
+    int i;
+
+    for (i = 0; i < 5; i++) {
+        qemu_coroutine_yield();
+    }
+    *done = true;
+}
+
+static void test_yield(void)
+{
+    Coroutine *coroutine;
+    bool done = false;
+    int i = -1; /* one extra time to return from coroutine */
+
+    coroutine = qemu_coroutine_create(yield_5_times);
+    while (!done) {
+        qemu_coroutine_enter(coroutine, &done);
+        i++;
+    }
+    g_assert_cmpint(i, ==, 5); /* coroutine must yield 5 times */
+}
+
+/*
+ * Check that creation, enter, and return work
+ */
+
+static void coroutine_fn set_and_exit(void *opaque)
+{
+    bool *done = opaque;
+
+    *done = true;
+}
+
+static void test_lifecycle(void)
+{
+    Coroutine *coroutine;
+    bool done = false;
+
+    /* Create, enter, and return from coroutine */
+    coroutine = qemu_coroutine_create(set_and_exit);
+    qemu_coroutine_enter(coroutine, &done);
+    g_assert(done); /* expect done to be true (first time) */
+
+    /* Repeat to check that no state affects this test */
+    done = false;
+    coroutine = qemu_coroutine_create(set_and_exit);
+    qemu_coroutine_enter(coroutine, &done);
+    g_assert(done); /* expect done to be true (second time) */
+}
+
+int main(int argc, char **argv)
+{
+    g_test_init(&argc, &argv, NULL);
+    g_test_add_func("/basic/lifecycle", test_lifecycle);
+    g_test_add_func("/basic/yield", test_yield);
+    g_test_add_func("/basic/nesting", test_nesting);
+    g_test_add_func("/basic/self", test_self);
+    g_test_add_func("/basic/in_coroutine", test_in_coroutine);
+    return g_test_run();
+}
Signature · 1 line
1.7.5.3
#16 lore raw

Re: [Qemu-devel] [PATCH v5 4/5] coroutine: add check-coroutine automated tests

Am 25.06.2011 um 16:11 schrieb Andreas Färber:

Quoted 14 lines

Am 12.06.2011 um 22:46 schrieb Stefan Hajnoczi:

Quoted 4 lines

To run automated tests for coroutines:

make check-coroutine
./check-coroutine

The commit message doesn't correspond to the changes, it's test-coroutine below.

$ ./test-coroutine
/basic/lifecycle: Segmentation fault

Compiles without warnings but crashes at runtime on Darwin/ppc64. It's using coroutine-ucontext.o implementation.

Quoted 12 lines

(gdb) run
Starting program: /Users/andreas/QEMU/qemu64/test-coroutine
warning: posix_spawn failed, trying execvp, error: 86
Reading symbols for shared libraries +++++++++++++
+
....................................................................... done /basic/lifecycle:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
qemu_coroutine_create (entry=0x2b10 <set_and_exit>) at /Users/andreas/QEMU/qemu/qemu-coroutine.c:23
23 co->entry = entry;
(gdb)

Commenting out CONFIG_UCONTEXT_COROUTINE=y in config-host.mak to force the coroutine-gthread.o implementation, this does not happen:

$ ./test-coroutine
/basic/lifecycle: OK
/basic/yield: OK
/basic/nesting: OK
/basic/self: OK
/basic/in_coroutine: OK

Andreas

#17 lore raw

Re: [Qemu-devel] [PATCH v5 4/5] coroutine: add check-coroutine automated tests

In reply to Andreas Färber

Am 25.06.2011 um 16:11 schrieb Andreas Färber:

Quoted 14 lines

Am 12.06.2011 um 22:46 schrieb Stefan Hajnoczi:

Quoted 4 lines

To run automated tests for coroutines:

make check-coroutine
./check-coroutine

The commit message doesn't correspond to the changes, it's test-coroutine below.

$ ./test-coroutine
/basic/lifecycle: Segmentation fault

Compiles without warnings but crashes at runtime on Darwin/ppc64. It's using coroutine-ucontext.o implementation.

Quoted 12 lines

(gdb) run
Starting program: /Users/andreas/QEMU/qemu64/test-coroutine
warning: posix_spawn failed, trying execvp, error: 86
Reading symbols for shared libraries +++++++++++++
+
....................................................................... done /basic/lifecycle:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
qemu_coroutine_create (entry=0x2b10 <set_and_exit>) at /Users/andreas/QEMU/qemu/qemu-coroutine.c:23
23 co->entry = entry;
(gdb)

(gdb) i r

r0             0x3690	13968
r1             0x7fff5fbff1e0	140734799802848
r2             0x7fff70231870	140735074736240
r3             0x0	0
r4             0x10080be00	4303404544
r5             0x0	0
r6             0x2	2
r7             0x0	0
r8             0x8	8
r9             0x0	0
r10            0x7fff80f14fac	140735356686252
r11            0x7fff70237940	140735074761024
r12            0x7fff80f14fa0	140735356686240
r13            0x7fff7028fde8	140735075122664
r14            0x0	0
r15            0x0	0
r16            0x0	0
r17            0x100240e94	4297330324
r18            0x100539040	4300443712
r19            0x100609400	4301296640
r20            0x0	0
r21            0x0	0
r22            0x100609b60	4301298528
r23            0x100240e94	4297330324
r24            0x100240e94	4297330324
r25            0x0	0
r26            0x0	0
r27            0x100205d78	4297088376
r28            0x7fff70231870	140735074736240
r29            0x2b10	11024
r30            0x2b10	11024
r31            0x0	0
pc             0x3690	13968
ps             0x900000000200f030	10376293541495238704
cr             0x24022222	604119586
lr             0x3690	13968
ctr            0x7fff80f14fa0	140735356686240
xer            0x20000000	536870912
mq             0x0	0
fpscr          0x82000000	2181038080
vscr           0x10000	65536
vrsave         0x0	0
(gdb) x/10i ($pc-8)
0x3688 <qemu_coroutine_create+40>:	li      r0,0
0x368c <qemu_coroutine_create+44>:	bl      0x3ca0 <qemu_coroutine_new>
0x3690 <qemu_coroutine_create+48>:	std     r29,0(r3)
0x3694 <qemu_coroutine_create+52>:	nop
0x3698 <qemu_coroutine_create+56>:	nop
0x369c <qemu_coroutine_create+60>:	nop
0x36a0 <qemu_coroutine_create+64>:	ld      r0,120(r1)
0x36a4 <qemu_coroutine_create+68>:	ld      r2,0(r28)
0x36a8 <qemu_coroutine_create+72>:	xor.    r0,r0,r2
0x36ac <qemu_coroutine_create+76>:	li      r2,0

(gdb)

#18 lore raw

PATCH v5 5/5 coroutine: add check-coroutine --benchmark-lifecycle

In reply to Stefan Hajnoczi

Add 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.

---
 test-coroutine.c |   30 ++++++++++++++++++++++++++++++
 1 files changed, 30 insertions(+), 0 deletions(-)
test-coroutine.c +30 -0
index 9e9d3c9..bf9f3e9 100644
@@ -150,6 +150,33 @@ static void test_lifecycle(void)
     g_assert(done); /* expect done to be true (second time) */
 }
 
+/*
+ * Lifecycle benchmark
+ */
+
+static void coroutine_fn empty_coroutine(void *opaque)
+{
+    /* Do nothing */
+}
+
+static void perf_lifecycle(void)
+{
+    Coroutine *coroutine;
+    unsigned int i, max;
+    double duration;
+
+    max = 1000000;
+
+    g_test_timer_start();
+    for (i = 0; i < max; i++) {
+        coroutine = qemu_coroutine_create(empty_coroutine);
+        qemu_coroutine_enter(coroutine, NULL);
+    }
+    duration = g_test_timer_elapsed();
+
+    g_test_message("Lifecycle %u iterations: %f s\n", max, duration);
+}
+
 int main(int argc, char **argv)
 {
     g_test_init(&argc, &argv, NULL);
@@ -158,5 +185,8 @@ int main(int argc, char **argv)
     g_test_add_func("/basic/nesting", test_nesting);
     g_test_add_func("/basic/self", test_self);
     g_test_add_func("/basic/in_coroutine", test_in_coroutine);
+    if (g_test_perf()) {
+        g_test_add_func("/perf/lifecycle", perf_lifecycle);
+    }
     return g_test_run();
 }
Signature · 1 line
1.7.5.3
#19 lore raw
In reply to Stefan Hajnoczi
Quoted 76 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 second patch.  The fourth 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.

v5:
 * GThread-based implementation for platforms without makecontext(3) (Aneesh Kumar K.V <[email protected]>)
 * Switch to gtester test framework

v4:
 * Windows Fibers support (Paolo Bonzini <[email protected]>)
 * Return-after-setjmp() fix (Aneesh Kumar K.V <[email protected]>)
 * Re-entrancy for multi-threaded coroutines support
 * qemu-coroutine.h cleanup and documentation

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

Aneesh Kumar K.V (1):
 coroutine: implement coroutines using gthread

Anthony Liguori (1):
 Add hard build dependency on glib

Kevin Wolf (1):
 coroutine: introduce coroutines

Stefan Hajnoczi (2):
 coroutine: add check-coroutine automated tests
 coroutine: add check-coroutine --benchmark-lifecycle

 .gitignore           |    1 +
 Makefile             |    5 +-
 Makefile.objs        |   13 +++
 Makefile.target      |    1 +
 configure            |   29 +++++++
 coroutine-gthread.c  |  131 ++++++++++++++++++++++++++++ coroutine-ucontext.c |  229 ++++++++++++++++++++++++++++++++++++++++++++++++++ coroutine-win32.c    |   92 ++++++++++++++++++++ qemu-coroutine-int.h |   48 +++++++++++

 qemu-coroutine.c     |   75 ++++++++++++++++
 qemu-coroutine.h     |   95 +++++++++++++++++++++
 test-coroutine.c     |  192 ++++++++++++++++++++++++++++++++++++++++++
 trace-events         |    5 +
 13 files changed, 915 insertions(+), 1 deletions(-)
Quoted 7 lines

 create mode 100644 coroutine-gthread.c
 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
 create mode 100644 test-coroutine.c

Any objections to merging this?

Stefan