Skip to contentSkip to conversation

Coroutines for better asynchronous programming

PATCH Superseded Stefan Hajnoczi 5 participants 15 messages May 12, 2011 – May 13, 2011 Kbuild

v2 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v2 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 will follow shortly.

Other areas of QEMU that could take advantage of coroutines include the VNC server, migration, and qemu-tools.

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

 Makefile             |    3 +-
 Makefile.objs        |    7 ++
 check-coroutine.c    |  238 ++++++++++++++++++++++++++++++++++++++++++++++++++
 coroutine-ucontext.c |   73 +++++++++++++++
 coroutine-win32.c    |   57 ++++++++++++
 qemu-coroutine-int.h |   55 ++++++++++++
 qemu-coroutine.c     |  168 +++++++++++++++++++++++++++++++++++
 qemu-coroutine.h     |   91 +++++++++++++++++++
 trace-events         |    5 +
 vl.c                 |    2 +
 10 files changed, 698 insertions(+), 1 deletions(-)
#1 lore raw

PATCH v2 1/4 coroutine: introduce coroutines

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 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 |   73 +++++++++++++++++++++++++++++
 coroutine-win32.c    |   57 +++++++++++++++++++++++
 qemu-coroutine-int.h |   53 +++++++++++++++++++++
 qemu-coroutine.c     |  125 ++++++++++++++++++++++++++++++++++++++++++++++++++
 qemu-coroutine.h     |   82 +++++++++++++++++++++++++++++++++
 trace-events         |    5 ++
 7 files changed, 402 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 9d8851e..cba6c2b 100644
@@ -11,6 +11,12 @@ oslib-obj-$(CONFIG_WIN32) += oslib-win32.o
 oslib-obj-$(CONFIG_POSIX) += oslib-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 +73 -0

73 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 +82 -0

82 lines not on this page · raw message

trace-events +5 -0
index 4f965e2..2d4db05 100644
@@ -361,3 +361,8 @@ disable milkymist_uart_pulse_irq_tx(void) "Pulse IRQ TX"
 # hw/milkymist-vgafb.c
 disable milkymist_vgafb_memory_read(uint32_t addr, uint32_t value) "addr %08x value %08x"
 disable milkymist_vgafb_memory_write(uint32_t addr, uint32_t value) "addr %08x value %08x"
+
+# qemu-coroutine.c
+qemu_coroutine_enter(void *from, void *to, void *opaque) "from %p to %p opaque %p"
+qemu_coroutine_yield(void *from, void *to) "from %p to %p"
+qemu_coroutine_terminate(void *co) "self %p"
Signature · 1 line
1.7.4.4
#2 lore raw

Re: [Qemu-devel] [PATCH v2 1/4] coroutine: introduce coroutines

Quoted 103 lines · 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 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 |   73 +++++++++++++++++++++++++++++ coroutine-win32.c    |   57 +++++++++++++++++++++++ qemu-coroutine-int.h |   53 +++++++++++++++++++++ qemu-coroutine.c     |  125 ++++++++++++++++++++++++++++++++++++++++++++++++++ qemu-coroutine.h     |   82 +++++++++++++++++++++++++++++++++ trace-events         |    5 ++

 7 files changed, 402 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 +0 -0
index 9d8851e..cba6c2b 100644
@@ -11,6 +11,12 @@ oslib-obj-$(CONFIG_WIN32) += oslib-win32.o

 oslib-obj-$(CONFIG_POSIX) += oslib-posix.o

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

Makefile.objs +6 -0
+# 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

Makefile.objs +0 -0
@@ -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 +9 -0
new file mode 100644
index 0000000..3b14ebf
@@ -0,0 +1,73 @@
+/*
+ * ucontext coroutine initialization code
+ *
+ * Copyright (C) 2006  Anthony Liguori <[email protected]>
+ * Copyright (C) 2011  Kevin Wolf <[email protected]>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either

coroutine-ucontext.c line 19

Quoted 10 lines
coroutine-ucontext.c new file +10 -0
+ * version 2.0 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA

Please use the web link version.

coroutine-ucontext.c line 22

Quoted 3 lines
coroutine-ucontext.c new file +3 -0
+ */
+
+/* XXX Is there a nicer way to disable glibc's stack check for longjmp? */

What is the problem?

Quoted 196 lines
coroutine-ucontext.c new file +51 -0
+#ifdef _FORTIFY_SOURCE
+#undef _FORTIFY_SOURCE
+#endif
+#include <setjmp.h>
+#include <stdint.h>
+#include <ucontext.h>
+#include "qemu-coroutine-int.h"
+
+static Coroutine *new_coroutine;
+
+static void continuation_trampoline(void)
+{
+    Coroutine *co = new_coroutine;
+
+    /* Initialize longjmp environment and switch back to
+     * qemu_coroutine_init_env() in the old ucontext. */
+    if (!setjmp(co->env)) {
+        return;
+    }
+
+    while (true) {
+        co->entry(co->data);
+        if (!setjmp(co->env)) {
+            longjmp(co->caller->env, COROUTINE_TERMINATE);
+        }
+    }
+}
+
+int qemu_coroutine_init_env(Coroutine *co, size_t stack_size)
+{
+    ucontext_t old_uc, uc;
+
+    /* Create a new ucontext for switching to the coroutine stack and setting
+     * up a longjmp environment. */
+    if (getcontext(&uc) == -1) {
+        return -errno;
+    }
+
+    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;
+
+    new_coroutine = co;
+    makecontext(&uc, (void *)continuation_trampoline, 0);
+
+    /* Initialize the longjmp environment */
+    swapcontext(&old_uc, &uc);
+
+    return 0;
+}
coroutine-win32.c new file +57 -0
new file mode 100644
index 0000000..99141dd
@@ -0,0 +1,57 @@
+/*
+ * Win32 coroutine initialization code
+ *
+ * Copyright (c) 2011 Kevin Wolf <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "qemu-coroutine-int.h"
+
+static void __attribute__((used)) trampoline(Coroutine *co)
+{
+    if (!setjmp(co->env)) {
+        return;
+    }
+
+    while (true) {
+        co->entry(co->data);
+        if (!setjmp(co->env)) {
+            longjmp(co->caller->env, COROUTINE_TERMINATE);
+        }
+    }
+}
+
+int qemu_coroutine_init_env(Coroutine *co, size_t stack_size)
+{
+#ifdef __i386__
+    asm volatile(
+        "mov %%esp, %%ebx;"
+        "mov %0, %%esp;"
+        "pushl %1;"
+        "call _trampoline;"
+        "mov %%ebx, %%esp;"
+        : : "r" (co->stack + stack_size), "r" (co) : "ebx"
+    );
+#else
+    #error This host architecture is not supported for win32
+#endif
+
+    return 0;
+}
qemu-coroutine-int.h new file +53 -0
new file mode 100644
index 0000000..71c6ee9
@@ -0,0 +1,53 @@
+/*
+ * Coroutine internals
+ *
+ * Copyright (c) 2011 Kevin Wolf <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef QEMU_COROUTINE_INT_H
+#define QEMU_COROUTINE_INT_H
+
+#include <setjmp.h>
+#include "qemu-common.h"
+#include "qemu-queue.h"
+#include "qemu-coroutine.h"
+
+enum {
+    /* setjmp() return values */
+    COROUTINE_YIELD = 1,
+    COROUTINE_TERMINATE = 2,
+};
+
+struct Coroutine {
+    struct Coroutine *caller;
+
+    char *stack;
+
+    /* 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);
+
+#endif
qemu-coroutine.c new file +17 -0
new file mode 100644
index 0000000..80bed14
@@ -0,0 +1,125 @@
+/*
+ * QEMU coroutines
+ *
+ * Copyright IBM, Corp. 2011
+ *
+ * Authors:
+ *  Stefan Hajnoczi    <[email protected]>
+ *  Kevin Wolf         <[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.
+ *
+ */
+
+/* XXX Is there a nicer way to disable glibc's stack check for longjmp? */
+#ifdef _FORTIFY_SOURCE
+#undef _FORTIFY_SOURCE

qemu-coroutine.c line 27

Quoted 10 lines
qemu-coroutine.c new file +10 -0
+#endif
+#include <setjmp.h>
+
+#include "trace.h"
+#include "qemu-queue.h"
+#include "qemu-common.h"
+#include "qemu-coroutine.h"
+#include "qemu-coroutine-int.h"
+
+static __thread Coroutine leader;
$ cat thread.c
static __thread int sigusr1_wfd;
$ gcc thread.c -c -pthread
thread.c:1: error: thread-local storage not supported for this target
$ gcc -v
Reading specs from
/usr/bin/../lib/gcc-lib/sparc64-unknown-openbsd4.9/4.2.1/specs
Target: sparc64-unknown-openbsd4.9
Configured with: OpenBSD/sparc64 system compiler
Thread model: posix
gcc version 4.2.1 20070719
Quoted 194 lines
qemu-coroutine.c new file +98 -0
+static __thread Coroutine *current;
+
+static void coroutine_terminate(Coroutine *co)
+{
+    trace_qemu_coroutine_terminate(co);
+    qemu_free(co->stack);
+    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)
+{
+    Coroutine *co;
+
+    co = coroutine_new();
+    co->entry = entry;
+
+    return co;
+}
+
+Coroutine *coroutine_fn qemu_coroutine_self(void)
+{
+    if (current == NULL) {
+        current = &leader;
+    }
+
+    return current;
+}
+
+bool qemu_in_coroutine(void)
+{
+    return qemu_coroutine_self() != &leader;
+}
+
+static void *coroutine_swap(Coroutine *from, Coroutine *to, void *opaque)
+{
+    int ret;
+    void *to_data;
+
+    to->data = opaque;
+
+    ret = setjmp(from->env);
+    switch (ret) {
+    case COROUTINE_YIELD:
+        return from->data;
+    case COROUTINE_TERMINATE:
+        current = to->caller;
+        to_data = to->data;
+        coroutine_terminate(to);
+        return to_data;
+    default:
+        /* Switch to called coroutine */
+        current = to;
+        longjmp(to->env, COROUTINE_YIELD);
+        return NULL;
+    }
+}
+
+void qemu_coroutine_enter(Coroutine *co, void *opaque)
+{
+    Coroutine *self = qemu_coroutine_self();
+
+    trace_qemu_coroutine_enter(self, co, opaque);
+
+    if (co->caller) {
+        fprintf(stderr, "Co-routine re-entered recursively\n");
+        abort();
+    }
+
+    co->caller = self;
+    coroutine_swap(self, co, opaque);
+}
+
+void *coroutine_fn qemu_coroutine_yield(void)
+{
+    Coroutine *self = qemu_coroutine_self();
+    Coroutine *to = self->caller;
+
+    trace_qemu_coroutine_yield(self, self->caller);
+
+    if (!to) {
+        fprintf(stderr, "Co-routine is yielding to no one\n");
+        abort();
+    }
+
+    self->caller = NULL;
+    return coroutine_swap(self, to, NULL);
+}
qemu-coroutine.h new file +82 -0
new file mode 100644
index 0000000..b79b4bf
@@ -0,0 +1,82 @@
+/*
+ * QEMU coroutine implementation
+ *
+ * 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.
+ *
+ */
+
+#ifndef QEMU_COROUTINE_H
+#define QEMU_COROUTINE_H
+
+#include <stdbool.h>
+
+/**
+ * Mark a function that executes in coroutine context
+ *
+ * Functions that execute in coroutine context cannot be called directly from
+ * normal functions.  In the future it would be nice to enable compiler or
+ * static checker support for catching such errors.  This annotation might make
+ * it possible and in the meantime it serves as documentation.
+ *
+ * For example:
+ *
+ *   static void coroutine_fn foo(void) {
+ *       ....
+ *   }
+ */
+#define coroutine_fn
+
+typedef struct Coroutine Coroutine;
+
+/**
+ * Coroutine entry point
+ *
+ * When the coroutine is entered for the first time, opaque is passed in as an
+ * argument.
+ *
+ * When this function returns, the coroutine is destroyed automatically and
+ * execution continues in the caller who last entered the coroutine.
+ */
+typedef void coroutine_fn CoroutineEntry(void *opaque);
+
+/**
+ * Create a new coroutine
+ *
+ * Use qemu_coroutine_enter() to actually transfer control to the coroutine.
+ */
+Coroutine *qemu_coroutine_create(CoroutineEntry *entry);
+
+/**
+ * Transfer control to a coroutine
+ *
+ * The opaque argument is made available to the coroutine either as the entry
+ * function argument if this is the first time a new coroutine is entered, or
+ * as the return value from qemu_coroutine_yield().
+ */
+void qemu_coroutine_enter(Coroutine *coroutine, void *opaque);
+
+/**
+ * Transfer control back to a coroutine's caller
+ *
+ * The return value is the argument passed back in from the next
+ * qemu_coroutine_enter().
+ */
+void *coroutine_fn qemu_coroutine_yield(void);
+
+/**
+ * Get the currently executing coroutine
+ */
+Coroutine *coroutine_fn qemu_coroutine_self(void);
+
+/**
+ * Return whether or not currently inside a coroutine
+ */
+bool qemu_in_coroutine(void);
+
+#endif /* QEMU_COROUTINE_H */
trace-events +0 -0
index 4f965e2..2d4db05 100644
@@ -361,3 +361,8 @@ disable milkymist_uart_pulse_irq_tx(void) "Pulse IRQ TX"
  # hw/milkymist-vgafb.c

 disable milkymist_vgafb_memory_read(uint32_t addr, uint32_t value) "addr %08x value %08x" disable milkymist_vgafb_memory_write(uint32_t addr, uint32_t value) "addr %08x value %08x"

trace-events disable milkymist_uart_pulse_irq_tx(void) "Pulse IRQ TX" · line 368

Quoted 5 lines
trace-events +5 -0
+
+# qemu-coroutine.c
+qemu_coroutine_enter(void *from, void *to, void *opaque) "from %p to %p opaque %p"
+qemu_coroutine_yield(void *from, void *to) "from %p to %p"
+qemu_coroutine_terminate(void *co) "self %p"

Not disabled?

#3 lore raw

Re: [Qemu-devel] [PATCH v2 1/4] coroutine: introduce coroutines

Quoted 21 lines · Blue Swirl
Quoted 19 lines · Stefan Hajnoczi
coroutine-ucontext.c new file +13 -0
new file mode 100644
index 0000000..3b14ebf
@@ -0,0 +1,73 @@
+/*
+ * ucontext coroutine initialization code
+ *
+ * Copyright (C) 2006  Anthony Liguori <[email protected]>
+ * Copyright (C) 2011  Kevin Wolf <[email protected]>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.0 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
Quoted 8 lines

coroutine-ucontext.c line 19

Quoted 6 lines
coroutine-ucontext.c new file +6 -0
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA

Please use the web link version.

Will update in v3.

Quoted 5 lines

coroutine-ucontext.c line 22

Quoted 3 lines
coroutine-ucontext.c new file +3 -0
+ */
+
+/* XXX Is there a nicer way to disable glibc's stack check for longjmp? */

What is the problem?

Kevin?

Quoted 13 lines

coroutine-ucontext.c line 23

Quoted 1 line
coroutine-ucontext.c new file +1 -0
+static __thread Coroutine leader;
$ cat thread.c
static __thread int sigusr1_wfd;
$ gcc thread.c -c -pthread
thread.c:1: error: thread-local storage not supported for this target
$ gcc -v
Reading specs from
/usr/bin/../lib/gcc-lib/sparc64-unknown-openbsd4.9/4.2.1/specs
Target: sparc64-unknown-openbsd4.9
Configured with: OpenBSD/sparc64 system compiler
Thread model: posix
gcc version 4.2.1 20070719

We had the thread-local variables in as part of the gtk-vnc history of this code. In QEMU we don't need it:

"Note that coroutines never execute concurrently and should only be used from threads which hold the global mutex."

So I will remove the thread-local attribute. Thank you for testing that platform.

Quoted 7 lines
Quoted 7 lines
trace-events +0 -0
index 4f965e2..2d4db05 100644
@@ -361,3 +361,8 @@ disable milkymist_uart_pulse_irq_tx(void) "Pulse IRQ TX"
  # hw/milkymist-vgafb.c

 disable milkymist_vgafb_memory_read(uint32_t addr, uint32_t value) "addr %08x value %08x"

Quoted 8 lines

trace-events disable milkymist_uart_pulse_irq_tx(void) "Pulse IRQ TX" · line 368

Quoted 6 lines

 disable milkymist_vgafb_memory_write(uint32_t addr, uint32_t value) "addr %08x value %08x"

trace-events +5 -0
+
+# qemu-coroutine.c
+qemu_coroutine_enter(void *from, void *to, void *opaque) "from %p to %p opaque %p"
+qemu_coroutine_yield(void *from, void *to) "from %p to %p"
+qemu_coroutine_terminate(void *co) "self %p"

Not disabled?

Good catch.

Stefan

#4 lore raw

Re: [Qemu-devel] [PATCH v2 1/4] coroutine: introduce coroutines

Am 12.05.2011 21:22, schrieb Stefan Hajnoczi:

Quoted 33 lines · Blue Swirl
Quoted 21 lines
Quoted 19 lines · Stefan Hajnoczi
coroutine-ucontext.c new file +13 -0
new file mode 100644
index 0000000..3b14ebf
@@ -0,0 +1,73 @@
+/*
+ * ucontext coroutine initialization code
+ *
+ * Copyright (C) 2006  Anthony Liguori <[email protected]>
+ * Copyright (C) 2011  Kevin Wolf <[email protected]>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.0 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
Quoted 8 lines

coroutine-ucontext.c line 19

Quoted 6 lines
coroutine-ucontext.c new file +6 -0
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA

Please use the web link version.

Will update in v3.

Quoted 7 lines
Quoted 5 lines

coroutine-ucontext.c line 22

Quoted 3 lines
coroutine-ucontext.c new file +3 -0
+ */
+
+/* XXX Is there a nicer way to disable glibc's stack check for longjmp? */

What is the problem?

Kevin?

I don't remember the details of the mechanism, but with _FORTIFY_SOURCE glibc has some check in longjmp that doesn't like stack switches. If you uncomment the #undef, you should be able to reproduce the abort().

Kevin

#5 lore raw

PATCH v2 2/4 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.

---
 Makefile          |    3 +-
 check-coroutine.c |  188 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 190 insertions(+), 1 deletions(-)
 create mode 100644 check-coroutine.c
Makefile +2 -1
index 67c0268..27ec6a1 100644
@@ -130,7 +130,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)
 
@@ -140,6 +140,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
#6 lore raw

PATCH v2 3/4 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.

---
 check-coroutine.c |   48 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 48 insertions(+), 0 deletions(-)
check-coroutine.c +48 -0
index f65ac2e..5a42c49 100644
@@ -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
#7 lore raw

PATCH v2 4/4 coroutine: pool coroutines to speed up creation

In reply to Stefan Hajnoczi

This 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

---
 check-coroutine.c    |    2 ++
 qemu-coroutine-int.h |    2 ++
 qemu-coroutine.c     |   49 ++++++++++++++++++++++++++++++++++++++++++++++---
 qemu-coroutine.h     |    9 +++++++++
 vl.c                 |    2 ++
 5 files changed, 61 insertions(+), 3 deletions(-)
check-coroutine.c +2 -0
index 5a42c49..223c50c 100644
@@ -218,6 +218,8 @@ int main(int argc, char **argv)
     };
     int i;
 
+    qemu_coroutine_init();
+
     if (argc == 3 && strcmp(argv[1], "--benchmark-lifecycle") == 0) {
         benchmark_lifecycle(argv[2]);
         return EXIT_SUCCESS;
qemu-coroutine-int.h +2 -0
index 71c6ee9..b264881 100644
@@ -45,6 +45,8 @@ struct Coroutine {
     void *data;
     CoroutineEntry *entry;
 
+    QLIST_ENTRY(Coroutine) pool_next;
+
     jmp_buf env;
 };
 
qemu-coroutine.c +46 -3

72 lines not on this page · raw message

qemu-coroutine.h +9 -0
index b79b4bf..0fae0a4 100644
@@ -17,6 +17,15 @@
 #include <stdbool.h>
 
 /**
+ * Initialize coroutine implementation
+ *
+ * This function should be called when the program is starting up.  It installs
+ * an atexit(3) handler which will free pooled coroutines when the program
+ * exits.  This keeps valgrind output clean.
+ */
+void qemu_coroutine_init(void);
+
+/**
  * Mark a function that executes in coroutine context
  *
  * Functions that execute in coroutine context cannot be called directly from
vl.c +2 -0
index 6b9a2f6..7092c9f 100644
@@ -145,6 +145,7 @@ int main(int argc, char **argv)
 #include "qemu-config.h"
 #include "qemu-objects.h"
 #include "qemu-options.h"
+#include "qemu-coroutine.h"
 #ifdef CONFIG_VIRTFS
 #include "fsdev/qemu-fsdev.h"
 #endif
@@ -1975,6 +1976,7 @@ int main(int argc, char **argv, char **envp)
     init_clocks();
 
     qemu_cache_utils_init(envp);
+    qemu_coroutine_init();
 
     QLIST_INIT (&vm_change_state_head);
     os_setup_early_signal_handling();
Signature · 1 line
1.7.4.4
#8 lore raw

Re: [Qemu-devel] [PATCH v2 4/4] coroutine: pool coroutines to speed up creation

terAm 12.05.2011 11:54, schrieb Stefan Hajnoczi:

Quoted 25 lines

This 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

---
 check-coroutine.c    |    2 ++
 qemu-coroutine-int.h |    2 ++
 qemu-coroutine.c     |   49 ++++++++++++++++++++++++++++++++++++++++++++++---
 qemu-coroutine.h     |    9 +++++++++
 vl.c                 |    2 ++
 5 files changed, 61 insertions(+), 3 deletions(-)
check-coroutine.c +0 -0
index 5a42c49..223c50c 100644

check-coroutine.c int main(int argc, char **argv) · line 221

Quoted 4 lines
check-coroutine.c +1 -0
@@ -218,6 +218,8 @@ int main(int argc, char **argv)
     };
     int i;
 
+    qemu_coroutine_init();

Can we use module_init instead of adding an explicit call to main()? This would prevent forgetting to add it in qemu-img and qemu-io like in this patch.

Kevin

#9 lore raw

Re: [Qemu-devel] [PATCH v2 4/4] coroutine: pool coroutines to speed up creation

Quoted 29 lines · Kevin Wolf

terAm 12.05.2011 11:54, schrieb Stefan Hajnoczi:

Quoted 28 lines

This 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

---
 check-coroutine.c    |    2 ++
 qemu-coroutine-int.h |    2 ++
 qemu-coroutine.c     |   49 ++++++++++++++++++++++++++++++++++++++++++++++--- qemu-coroutine.h     |    9 +++++++++
 vl.c                 |    2 ++

 5 files changed, 61 insertions(+), 3 deletions(-)
check-coroutine.c +0 -0
index 5a42c49..223c50c 100644
@@ -218,6 +218,8 @@ int main(int argc, char **argv)
      };
      int i;
 
Quoted 5 lines

check-coroutine.c int main(int argc, char **argv) · line 221

Quoted 1 line
check-coroutine.c +1 -0
+    qemu_coroutine_init();

Can we use module_init instead of adding an explicit call to main()? This would prevent forgetting to add it in qemu-img and qemu-io like in this patch.

module_init what? :) qemu-img/qemu-io only init MODULE_INIT_BLOCK so we'd have to modify them anyway.

I don't want to add qemu-img/qemu-io things yet because we don't have a block layer user for coroutines yet. The qcow2 patches should contain these changes.

Stefan

#10 lore raw

Re: [Qemu-devel] [PATCH v2 4/4] coroutine: pool coroutines to speed up creation

Am 12.05.2011 12:22, schrieb Stefan Hajnoczi:

Quoted 30 lines · Kevin Wolf
Quoted 29 lines

terAm 12.05.2011 11:54, schrieb Stefan Hajnoczi:

Quoted 28 lines

This 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

---
 check-coroutine.c    |    2 ++
 qemu-coroutine-int.h |    2 ++
 qemu-coroutine.c     |   49 ++++++++++++++++++++++++++++++++++++++++++++++---
 qemu-coroutine.h     |    9 +++++++++
 vl.c                 |    2 ++
 5 files changed, 61 insertions(+), 3 deletions(-)
check-coroutine.c +0 -0
index 5a42c49..223c50c 100644
@@ -218,6 +218,8 @@ int main(int argc, char **argv)
     };
     int i;
 
Quoted 8 lines
Quoted 5 lines

check-coroutine.c int main(int argc, char **argv) · line 221

Quoted 1 line
check-coroutine.c +1 -0
+    qemu_coroutine_init();

Can we use module_init instead of adding an explicit call to main()? This would prevent forgetting to add it in qemu-img and qemu-io like in this patch.

module_init what? :) qemu-img/qemu-io only init MODULE_INIT_BLOCK so we'd have to modify them anyway.

Right... I was thinking of block, but in fact coroutines are not limited to the block layer, so we would abuse it.

Quoted 3 lines

I don't want to add qemu-img/qemu-io things yet because we don't have a block layer user for coroutines yet. The qcow2 patches should contain these changes.

I hope we won't forget it. A missing atexit isn't a very obvious bug.

Kevin

#11 lore raw

Re: [Qemu-devel] [PATCH v2 4/4] coroutine: pool coroutines to speed up creation

Quoted 5 lines · Kevin Wolf
Quoted 3 lines

I don't want to add qemu-img/qemu-io things yet because we don't have a block layer user for coroutines yet. The qcow2 patches should contain these changes.

I hope we won't forget it. A missing atexit isn't a very obvious bug.

I was going to reply that this atexit is actually useless, since memory is freed automatically at exit?

Paolo

#12 lore raw

Re: [Qemu-devel] [PATCH v2 4/4] coroutine: pool coroutines to speed up creation

Quoted 10 lines · Paolo Bonzini
Quoted 6 lines · Kevin Wolf
Quoted 4 lines

I don't want to add qemu-img/qemu-io things yet because we don't have a block layer user for coroutines yet.  The qcow2 patches should contain these changes.

I hope we won't forget it. A missing atexit isn't a very obvious bug.

I was going to reply that this atexit is actually useless, since memory is freed automatically at exit?

It's just for completeness to make tools like valgrind happy. Sure, the kernel will reclaim memory and we're just burning CPU by freeing this stuff ;).

Stefan

#13 lore raw

Re: [Qemu-devel] [PATCH v2 4/4] coroutine: pool coroutines to speed up creation

Quoted 3 lines · Stefan Hajnoczi

It's just for completeness to make tools like valgrind happy. Sure, the kernel will reclaim memory and we're just burning CPU by freeing this stuff;).

But valgrind will not complain about reachable memory still allocated at exit, at least not with the default command-line options.

Paolo

#14 lore raw

Re: [Qemu-devel] [PATCH v2 4/4] coroutine: pool coroutines to speed up creation

Quoted 8 lines · Paolo Bonzini
Quoted 4 lines · Stefan Hajnoczi

It's just for completeness to make tools like valgrind happy.  Sure, the kernel will reclaim memory and we're just burning CPU by freeing this stuff;).

But valgrind will not complain about reachable memory still allocated at exit, at least not with the default command-line options.

/me is outsmarted by valgrind

Then I will remove pool freeing in v3.

Stefan