Skip to contentSkip to conversation

libxl: New event API

PATCH Superseded Ian Jackson 2 participants 31 messages Jan 13, 2012 – Jan 25, 2012

v7 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v7 cover libxl: New event API

This series has now been tested. It includes bugfixes and all the comments which people have made and which I said I would address.

These should be fairly uncontroversial:

 2/9  ocaml, libxl: support "private" fields
 4/9  libxl: introduce libxl_fd_set_nonblock, rationalise _cloexec
 7/9  libxl: New convenience macro CONTAINER_OF

These are the meat:

 1/9  libxl: New API for providing OS events to libxl
 3/9  libxl: New event generation API
 5/9  libxl: Permit multithreaded event waiting
 6/9  libxl: Asynchronous/long-running operation infrastructure
 8/9  libxl: Introduce libxl__ev_devstate
 9/9  libxl: Convert to asynchronous: device removal
#1 lore raw

PATCH v7 1/9 libxl: New API for providing OS events to libxl

We provide a new set of functions and related structures
libxl_osevent_*
which are to be used by event-driven applications to receive information from libxl about which fds libxl is interested in, and what timeouts libxl is waiting for, and to pass back to libxl information about which fds are readable/writeable etc., and which timeouts have occurred. Ie, low-level events.

In this patch, this new machinery is still all unused. Callers will appear in the next patch in the series, which introduces a new API for applications to receive high-level events about actual domains etc.

---
 tools/libxl/Makefile         |    2 +-
 tools/libxl/libxl.c          |   30 ++
 tools/libxl/libxl.h          |    6 +
 tools/libxl/libxl_event.c    |  750 ++++++++++++++++++++++++++++++++++++++++++
 tools/libxl/libxl_event.h    |  205 ++++++++++++
 tools/libxl/libxl_internal.h |  277 +++++++++++++++-
 6 files changed, 1267 insertions(+), 3 deletions(-)
 create mode 100644 tools/libxl/libxl_event.c
 create mode 100644 tools/libxl/libxl_event.h
tools/libxl/Makefile +1 -1
index 3c3661b..b58c43e 100644
@@ -49,7 +49,7 @@ LIBXL_LIBS += -lyajl
 LIBXL_OBJS = flexarray.o libxl.o libxl_create.o libxl_dm.o libxl_pci.o \
 			libxl_dom.o libxl_exec.o libxl_xshelp.o libxl_device.o \
 			libxl_internal.o libxl_utils.o libxl_uuid.o libxl_json.o \
-			libxl_qmp.o $(LIBXL_OBJS-y)
+			libxl_qmp.o libxl_event.o $(LIBXL_OBJS-y)
 LIBXL_OBJS += _libxl_types.o libxl_flask.o _libxl_types_internal.o
 
 $(LIBXL_OBJS): CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenguest) $(CFLAGS_libxenstore) $(CFLAGS_libblktapctl)
tools/libxl/libxl.c +30 -0
index 169fc97..413b684 100644
@@ -45,6 +45,16 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,
      * only as an initialiser, not as an expression. */
     memcpy(&ctx->lock, &mutex_value, sizeof(ctx->lock));
 
+    ctx->osevent_hooks = 0;
+
+    ctx->fd_rindex = 0;
+    LIBXL_LIST_INIT(&ctx->efds);
+    LIBXL_TAILQ_INIT(&ctx->etimes);
+
+    ctx->watch_slots = 0;
+    LIBXL_SLIST_INIT(&ctx->watch_freeslots);
+    libxl__ev_fd_init(&ctx->watch_efd);
+
     if ( stat(XENSTORE_PID_FILE, &stat_buf) != 0 ) {
         LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "Is xenstore daemon running?\n"
                      "failed to stat %s", XENSTORE_PID_FILE);
@@ -79,9 +89,29 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,
 int libxl_ctx_free(libxl_ctx *ctx)
 {
     if (!ctx) return 0;
+
+    int i;
+    GC_INIT(ctx);
+
+    /* Deregister all libxl__ev_KINDs: */
+
+    for (i = 0; i < ctx->watch_nslots; i++)
+        assert(!libxl__watch_slot_contents(gc, i));
+    libxl__ev_fd_deregister(gc, &ctx->watch_efd);
+
+    /* Now there should be no more events requested from the application: */
+
+    assert(LIBXL_LIST_EMPTY(&ctx->efds));
+    assert(LIBXL_TAILQ_EMPTY(&ctx->etimes));
+
     if (ctx->xch) xc_interface_close(ctx->xch);
     libxl_version_info_dispose(&ctx->version_info);
     if (ctx->xsh) xs_daemon_close(ctx->xsh);
+
+    free(ctx->fd_rindex);
+    free(ctx->watch_slots);
+
+    GC_FREE;
     free(ctx);
     return 0;
 }
tools/libxl/libxl.h +6 -0
index 723eac2..b067724 100644
@@ -137,6 +137,7 @@
 #include <xen/sysctl.h>
 
 #include <libxl_uuid.h>
+#include <_libxl_list.h>
 
 typedef uint8_t libxl_mac[6];
 #define LIBXL_MAC_FMT "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx"
@@ -223,6 +224,9 @@ enum {
     ERROR_GUEST_TIMEDOUT = -8,
     ERROR_TIMEDOUT = -9,
     ERROR_NOPARAVIRT = -10,
+    ERROR_NOT_READY = -11,
+    ERROR_OSEVENT_REG_FAIL = -12,
+    ERROR_BUFFERFULL = -13,
 };
 
 #define LIBXL_VERSION 0
@@ -648,6 +652,8 @@ const char *libxl_xenpaging_dir_path(void);
 /* misc */
 int libxl_fd_set_cloexec(int fd);
 
+#include <libxl_event.h>
+
 #endif /* LIBXL_H */
 
 /*
tools/libxl/libxl_event.c new file +750 -0

750 lines not on this page · raw message

tools/libxl/libxl_event.h new file +205 -0

205 lines not on this page · raw message

tools/libxl/libxl_internal.h +275 -2

323 lines not on this page · raw message

Signature · 1 line
1.7.2.5
Acked-by on v7 1/9
#2 lore raw

Re: [PATCH 1/9] libxl: New API for providing OS events to libxl

Quoted 23 lines · Ian Jackson

We provide a new set of functions and related structures
libxl_osevent_*
which are to be used by event-driven applications to receive information from libxl about which fds libxl is interested in, and what timeouts libxl is waiting for, and to pass back to libxl information about which fds are readable/writeable etc., and which timeouts have occurred. Ie, low-level events.

In this patch, this new machinery is still all unused. Callers will appear in the next patch in the series, which introduces a new API for applications to receive high-level events about actual domains etc.

---
 tools/libxl/Makefile         |    2 +-
 tools/libxl/libxl.c          |   30 ++
 tools/libxl/libxl.h          |    6 +
 tools/libxl/libxl_event.c    |  750 ++++++++++++++++++++++++++++++++++++++++++
 tools/libxl/libxl_event.h    |  205 ++++++++++++
 tools/libxl/libxl_internal.h |  277 +++++++++++++++-
 6 files changed, 1267 insertions(+), 3 deletions(-)
 create mode 100644 tools/libxl/libxl_event.c
 create mode 100644 tools/libxl/libxl_event.h

[...]

Quoted 6 lines
tools/libxl/libxl_internal.h +2 -0
@@ -109,6 +110,71 @@ _hidden void libxl__log(libxl_ctx *ctx, xentoollog_level msglevel, int errnoval,
 
      /* these functions preserve errno (saving and restoring) */
 
+typedef struct libxl__gc libxl__gc;
+typedef struct libxl__egc libxl__egc;

tools/libxl/libxl_internal.h _hidden void libxl__log(libxl_ctx *ctx, xentoollog_level msglevel, int errnoval, · line 124

Quoted 10 lines
tools/libxl/libxl_internal.h +10 -0
+
+typedef struct libxl__ev_fd libxl__ev_fd;
+typedef void libxl__ev_fd_callback(libxl__egc *egc, libxl__ev_fd *ev,
+                                   int fd, short events, short revents);
+struct libxl__ev_fd {
+    /* caller should include this in their own struct */
+    /* read-only for caller, who may read only when registered: */
+    int fd;
+    short events;
+    libxl__ev_fd_callback *func;

Are there actually cases where a caller would want to read these?

The most obvious case would be in the callback but it already gets given all three there.

Not suggesting we disallow this I'm just curious.

Quoted 4 lines
tools/libxl/libxl_internal.h +4 -0
+    /* remainder is private for libxl__ev_fd... */
+    LIBXL_LIST_ENTRY(libxl__ev_fd) entry;
+    void *for_app_reg;
+};

[...]

Quoted 6 lines

+ * int libxl__ev_KIND_register(libxl__gc *gc, libxl__ev_KIND *GEN,
+ * libxl__ev_KIND_callback *FUNC,
+ * DETAILS);

+ *      On entry *GEN must be in state Undefined or Idle.
+ *      Returns a libxl error code; on error return *GEN is Idle.
+ *      On successful return *GEN is Active and FUNC wil be

will

Quoted 3 lines
+ *      called by the event machinery in future.  FUNC will
+ *      not be called from within the call to _register.
+ *      FUNC will be called with the context locked (with CTX_LOCK).

[...]

#3 lore raw

Re: [PATCH 1/9] libxl: New API for providing OS events to libxl

Ian Campbell writes ("Re: [Xen-devel] [PATCH 1/9] libxl: New API for providing OS events to libxl"):

Quoted 8 lines · Ian Jackson

tools/libxl/libxl_internal.h _hidden void libxl__log(libxl_ctx *ctx, xentoollog_level msglevel, int errnoval, · line 124

Quoted 6 lines
tools/libxl/libxl_internal.h +6 -0
+struct libxl__ev_fd {
+    /* caller should include this in their own struct */
+    /* read-only for caller, who may read only when registered: */
+    int fd;
+    short events;
+    libxl__ev_fd_callback *func;
Quoted 6 lines

Are there actually cases where a caller would want to read these?

The most obvious case would be in the callback but it already gets given all three there.

Not suggesting we disallow this I'm just curious.

This is a change from my previous version of this series. When writing the device removal code I found myself wanting to read the path member of a libxl__ev_xswatch:

+static void devstate_timeout(libxl__egc *egc, libxl__ev_time *ev,
+ const struct timeval *requested_abs)
+{

+    EGC_GC;
+    libxl__ev_devstate *ds = CONTAINER_OF(ev, *ds, timeout);
+    LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d "
+               " timed out", ds->watch.path, ds->wanted);
                              ^^^^^^^^^^^^^^

+ libxl__ev_devstate_cancel(gc, ds);
+ ds->callback(egc, ds, ERROR_TIMEDOUT);
+}

So my options were:
0. Not print the path, rendering the message almost useless
1. Copy the path an extra time, pointlessly
2. Relax the rules about the contents of libxl__ev_xswatch, making a special exception for this particular struct
3. Relax the rules about the contents of libxl__ev_* generally
4. Change the API of libxl__ev_* so that the caller always writes the fd, path, etc.

Of these 3 seemed best. I considered 4.; but the result would be that libxl__ev_KIND_register wouldn't take the arguments specifying what to wait for, and that seemed a step too far. Particularly since needing to read inside the struct isn't all that common.

Quoted 1 line

Thanks,
Ian.

#4 lore raw

PATCH v7 2/9 ocaml, libxl: support "private" fields

In reply to Ian Jackson

The changeset
24378:b4365e2c2595 libxl: idl: support new "private" type attribute
is not complete. Actually using this feature does not work because the ocaml idl generator does not know about it.

So add that support.

---
 tools/ocaml/libs/xl/genwrap.py |    8 ++++++++
 1 files changed, 8 insertions(+), 0 deletions(-)
tools/ocaml/libs/xl/genwrap.py +8 -0
index 5f8639a..61abecf 100644
@@ -91,6 +91,8 @@ def gen_ocaml_ml(ty, interface, indent=""):
             s += "\t{\n"
             
         for f in ty.fields:
+            if f.type.private:
+                continue
             x = ocaml_instance_of(f.type, f.name)
             x = x.replace("\n", "\n\t\t")
             s += "\t\t" + x + ";\n"
@@ -146,6 +148,8 @@ def c_val(ty, c, o, indent="", parent = None):
     elif isinstance(ty, libxltypes.Aggregate) and (parent is None):
         n = 0
         for f in ty.fields:
+            if f.type.private:
+                continue
             s += "%s\n" % c_val(f.type, "%s->%s" % (c, f.name), "Field(%s, %d)" % (o,n), parent="%s->" % (c))
             n = n + 1
     else:
@@ -210,6 +214,8 @@ def ocaml_Val(ty, o, c, indent="", parent = None):
         
         n = 0
         for f in ty.fields:
+            if f.type.private:
+                continue
             s += "\n"
             s += "\t%s\n" % ocaml_Val(f.type, "%s_field" % ty.rawname, "%s->%s" % (c,f.name), parent="%s->" % c)
             s += "\tStore_field(%s, %d, %s);\n" % (o, n, "%s_field" % ty.rawname)
@@ -288,6 +294,8 @@ if __name__ == '__main__':
     cinc.write(autogen_header("/*", "*/"))
 
     for ty in types:
+        if ty.private:
+            continue
         #sys.stdout.write(" TYPE    %-20s " % ty.rawname)
         ml.write(gen_ocaml_ml(ty, False))
         ml.write("\n")
Signature · 1 line
1.7.2.5
Acked-by on v7 2/9
#5 lore raw

Re: [PATCH 2/9] ocaml, libxl: support "private" fields

Quoted 8 lines · Ian Jackson

The changeset
24378:b4365e2c2595 libxl: idl: support new "private" type attribute
is not complete. Actually using this feature does not work because the ocaml idl generator does not know about it.

So add that support.

Quoted 44 lines
---
 tools/ocaml/libs/xl/genwrap.py |    8 ++++++++
 1 files changed, 8 insertions(+), 0 deletions(-)
tools/ocaml/libs/xl/genwrap.py +8 -0
index 5f8639a..61abecf 100644
@@ -91,6 +91,8 @@ def gen_ocaml_ml(ty, interface, indent=""):
             s += "\t{\n"
 
         for f in ty.fields:
+            if f.type.private:
+                continue
             x = ocaml_instance_of(f.type, f.name)
             x = x.replace("\n", "\n\t\t")
             s += "\t\t" + x + ";\n"
@@ -146,6 +148,8 @@ def c_val(ty, c, o, indent="", parent = None):
     elif isinstance(ty, libxltypes.Aggregate) and (parent is None):
         n = 0
         for f in ty.fields:
+            if f.type.private:
+                continue
             s += "%s\n" % c_val(f.type, "%s->%s" % (c, f.name), "Field(%s, %d)" % (o,n), parent="%s->" % (c))
             n = n + 1
     else:
@@ -210,6 +214,8 @@ def ocaml_Val(ty, o, c, indent="", parent = None):
 
         n = 0
         for f in ty.fields:
+            if f.type.private:
+                continue
             s += "\n"
             s += "\t%s\n" % ocaml_Val(f.type, "%s_field" % ty.rawname, "%s->%s" % (c,f.name), parent="%s->" % c)
             s += "\tStore_field(%s, %d, %s);\n" % (o, n, "%s_field" % ty.rawname)
@@ -288,6 +294,8 @@ if __name__ == '__main__':
     cinc.write(autogen_header("/*", "*/"))
 
     for ty in types:
+        if ty.private:
+            continue
         #sys.stdout.write(" TYPE    %-20s " % ty.rawname)
         ml.write(gen_ocaml_ml(ty, False))
         ml.write("\n")
#6 lore raw

PATCH v7 3/9 libxl: New event generation API

In reply to Ian Jackson

Replace the existing API for retrieving high-level events (events about domains, etc.) from libxl with a new one.

This changes the definition and semantics of the `libxl_event' structure, and replaces the calls for obtaining information about domain death and disk eject events.

This is an incompatible change, sorry. The alternative was to try to provide both the previous horrid API and the new one, and would also involve never using the name `libxl_event' for the new interface.

The new "libxl_event" structure is blacklisted in the ocaml bindings for two reasons:
- It has a field name "type" (which is a keyword in ocaml); the ocaml idl generator should massage this field name on output, to "type_" perhaps.
- The ocaml idl generator does not support KeyedUnion.

---
 tools/libxl/libxl.c            |  329 +++++++++++++++++++++++++++++-----------
 tools/libxl/libxl.h            |   55 +------
 tools/libxl/libxl_event.c      |  236 ++++++++++++++++++++++++++---
 tools/libxl/libxl_event.h      |  183 ++++++++++++++++++++++-
 tools/libxl/libxl_internal.h   |   77 +++++++++-
 tools/libxl/libxl_types.idl    |   34 ++++-
 tools/libxl/xl_cmdimpl.c       |  270 +++++++++++++++++++--------------
 tools/ocaml/libs/xl/genwrap.py |    1 +
 8 files changed, 908 insertions(+), 277 deletions(-)
tools/libxl/libxl.c +241 -88
index 413b684..19ff12c 100644
@@ -45,8 +45,11 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,
      * only as an initialiser, not as an expression. */
     memcpy(&ctx->lock, &mutex_value, sizeof(ctx->lock));
 
+    LIBXL_TAILQ_INIT(&ctx->occurred);
+
     ctx->osevent_hooks = 0;
 
+    ctx->fd_polls = 0;
     ctx->fd_rindex = 0;
     LIBXL_LIST_INIT(&ctx->efds);
     LIBXL_TAILQ_INIT(&ctx->etimes);
@@ -55,6 +58,9 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,
     LIBXL_SLIST_INIT(&ctx->watch_freeslots);
     libxl__ev_fd_init(&ctx->watch_efd);
 
+    LIBXL_TAILQ_INIT(&ctx->death_list);
+    libxl__ev_xswatch_init(&ctx->death_watch);
+
     if ( stat(XENSTORE_PID_FILE, &stat_buf) != 0 ) {
         LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "Is xenstore daemon running?\n"
                      "failed to stat %s", XENSTORE_PID_FILE);
@@ -86,6 +92,20 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,
     return rc;
 }
 
+static void free_disable_deaths(libxl__gc *gc,
+                                struct libxl__evgen_domain_death_list *l) {
+    libxl_evgen_domain_death *death;
+    while ((death = LIBXL_TAILQ_FIRST(l)))
+        libxl__evdisable_domain_death(gc, death);
+}
+
+static void discard_events(struct libxl__event_list *l) {
+    /* doesn't bother unlinking from the list, so l is corrupt on return */
+    libxl_event *ev;
+    LIBXL_TAILQ_FOREACH(ev, l, link)
+        libxl_event_free(0, ev);
+}
+
 int libxl_ctx_free(libxl_ctx *ctx)
 {
     if (!ctx) return 0;
@@ -95,6 +115,13 @@ int libxl_ctx_free(libxl_ctx *ctx)
 
     /* Deregister all libxl__ev_KINDs: */
 
+    free_disable_deaths(gc, &CTX->death_list);
+    free_disable_deaths(gc, &CTX->death_reported);
+
+    libxl_evgen_disk_eject *eject;
+    while ((eject = LIBXL_LIST_FIRST(&CTX->disk_eject_evgens)))
+        libxl__evdisable_disk_eject(gc, eject);
+
     for (i = 0; i < ctx->watch_nslots; i++)
         assert(!libxl__watch_slot_contents(gc, i));
     libxl__ev_fd_deregister(gc, &ctx->watch_efd);
@@ -108,9 +135,12 @@ int libxl_ctx_free(libxl_ctx *ctx)
     libxl_version_info_dispose(&ctx->version_info);
     if (ctx->xsh) xs_daemon_close(ctx->xsh);
 
+    free(ctx->fd_polls);
     free(ctx->fd_rindex);
     free(ctx->watch_slots);
 
+    discard_events(&ctx->occurred);
+
     GC_FREE;
     free(ctx);
     return 0;
@@ -646,117 +676,176 @@ int libxl_domain_reboot(libxl_ctx *ctx, uint32_t domid)
     return ret;
 }
 
-int libxl_get_wait_fd(libxl_ctx *ctx, int *fd)
-{
-    *fd = xs_fileno(ctx->xsh);
-    return 0;
-}
+static void domain_death_xswatch_callback(libxl__egc *egc, libxl__ev_xswatch *w,
+                                        const char *wpath, const char *epath) {
+    EGC_GC;
+    libxl_evgen_domain_death *evg;
+    uint32_t domid;
+    int rc;
 
-int libxl_wait_for_domain_death(libxl_ctx *ctx, uint32_t domid, libxl_waiter *waiter)
-{
-    waiter->path = strdup("@releaseDomain");
-    if (asprintf(&(waiter->token), "%d", LIBXL_EVENT_TYPE_DOMAIN_DEATH) < 0)
-        return -1;
-    if (!xs_watch(ctx->xsh, waiter->path, waiter->token))
-        return -1;
-    return 0;
-}
+    CTX_LOCK;
 
-int libxl_wait_for_disk_ejects(libxl_ctx *ctx, uint32_t guest_domid, libxl_device_disk *disks, int num_disks, libxl_waiter *waiter)
-{
-    GC_INIT(ctx);
-    int i, rc = -1;
-    uint32_t domid = libxl_get_stubdom_id(ctx, guest_domid);
+    evg = LIBXL_TAILQ_FIRST(&CTX->death_list);
+    if (!evg) goto out;
 
-    if (!domid)
-        domid = guest_domid;
+    domid = evg->domid;
 
-    for (i = 0; i < num_disks; i++) {
-        if (asprintf(&(waiter[i].path), "%s/device/vbd/%d/eject",
-                     libxl__xs_get_dompath(gc, domid),
-                     libxl__device_disk_dev_number(disks[i].vdev,
-                                                   NULL, NULL)) < 0)
-            goto out;
-        if (asprintf(&(waiter[i].token), "%d", LIBXL_EVENT_TYPE_DISK_EJECT) < 0)
+    for (;;) {
+        int nentries = LIBXL_TAILQ_NEXT(evg, entry) ? 200 : 1;
+        xc_domaininfo_t domaininfos[nentries];
+        const xc_domaininfo_t *got = domaininfos, *gotend;
+
+        rc = xc_domain_getinfolist(CTX->xch, domid, nentries, domaininfos);
+        if (rc == -1) {
+            LIBXL__EVENT_DISASTER(egc, "xc_domain_getinfolist failed while"
+                                  " processing @releaseDomain watch event",
+                                  errno, 0);
             goto out;
-        xs_watch(ctx->xsh, waiter[i].path, waiter[i].token);
+        }
+        gotend = &domaininfos[rc];
+
+        for (;;) {
+            if (!evg)
+                goto all_reported;
+
+            if (!rc || got->domain > evg->domid) {
+                /* ie, the list doesn't contain evg->domid any more so
+                 * the domain has been destroyed */
+                libxl_evgen_domain_death *evg_next;
+
+                libxl_event *ev = NEW_EVENT(egc, DOMAIN_DESTROY, evg->domid);
+                if (!ev) goto out;
+
+                libxl__event_occurred(egc, ev);
+
+                evg->death_reported = 1;
+                evg_next = LIBXL_TAILQ_NEXT(evg, entry);
+                LIBXL_TAILQ_REMOVE(&CTX->death_list, evg, entry);
+                LIBXL_TAILQ_INSERT_HEAD(&CTX->death_reported, evg, entry);
+                evg = evg_next;
+
+                continue;
+            }
+            
+            if (got == gotend)
+                break;
+
+            if (got->domain < evg->domid) {
+                got++;
+                continue;
+            }
+
+            assert(evg->domid == got->domain);
+
+            if (!evg->shutdown_reported &&
+                (got->flags & XEN_DOMINF_shutdown)) {
+                libxl_event *ev = NEW_EVENT(egc, DOMAIN_SHUTDOWN, got->domain);
+                if (!ev) goto out;
+                
+                ev->u.domain_shutdown.shutdown_reason =
+                    (got->flags >> XEN_DOMINF_shutdownshift) &
+                    XEN_DOMINF_shutdownmask;
+                libxl__event_occurred(egc, ev);
+
+                evg->shutdown_reported = 1;
+            }
+            evg = LIBXL_TAILQ_NEXT(evg, entry);
+        }
+
+        assert(rc); /* rc==0 results in us eating all evgs and quitting */
+        domid = gotend[-1].domain;
     }
-    rc = 0;
-out:
-    GC_FREE;
-    return rc;
+ all_reported:
+ out:
+
+    CTX_UNLOCK;
 }
 
-int libxl_get_event(libxl_ctx *ctx, libxl_event *event)
-{
-    unsigned int num;
-    char **events = xs_read_watch(ctx->xsh, &num);
-    if (num != 2) {
-        free(events);
-        return ERROR_FAIL;
+int libxl_evenable_domain_death(libxl_ctx *ctx, uint32_t domid,
+                libxl_ev_user user, libxl_evgen_domain_death **evgen_out) {
+    GC_INIT(ctx);
+    libxl_evgen_domain_death *evg, *evg_search;
+    int rc;
+    
+    CTX_LOCK;
+
+    evg = malloc(sizeof(*evg));  if (!evg) { rc = ERROR_NOMEM; goto out; }
+    memset(evg, 0, sizeof(*evg));
+    evg->domid = domid;
+    evg->user = user;
+
+    LIBXL_TAILQ_INSERT_SORTED(&ctx->death_list, entry, evg, evg_search, ,
+                              evg->domid > evg_search->domid);
+
+    if (!libxl__ev_xswatch_isregistered(&ctx->death_watch)) {
+        rc = libxl__ev_xswatch_register(gc, &ctx->death_watch,
+                        domain_death_xswatch_callback, "@releaseDomain");
+        if (rc) { libxl__evdisable_domain_death(gc, evg); goto out; }
     }
-    event->path = strdup(events[XS_WATCH_PATH]);
-    event->token = strdup(events[XS_WATCH_TOKEN]);
-    event->type = atoi(event->token);
-    free(events);
-    return 0;
-}
 
-int libxl_stop_waiting(libxl_ctx *ctx, libxl_waiter *waiter)
-{
-    if (!xs_unwatch(ctx->xsh, waiter->path, waiter->token))
-        return ERROR_FAIL;
-    else
-        return 0;
-}
+    *evgen_out = evg;
+    rc = 0;
 
-int libxl_free_event(libxl_event *event)
-{
-    free(event->path);
-    free(event->token);
-    return 0;
-}
+ out:
+    CTX_UNLOCK;
+    return rc;
+};
 
-int libxl_free_waiter(libxl_waiter *waiter)
-{
-    free(waiter->path);
-    free(waiter->token);
-    return 0;
-}
+void libxl__evdisable_domain_death(libxl__gc *gc,
+                                   libxl_evgen_domain_death *evg) {
+    CTX_LOCK;
 
-int libxl_event_get_domain_death_info(libxl_ctx *ctx, uint32_t domid, libxl_event *event, libxl_dominfo *info)
-{
-    if (libxl_domain_info(ctx, info, domid) < 0)
-        return 0;
+    if (!evg->death_reported)
+        LIBXL_TAILQ_REMOVE(&CTX->death_list, evg, entry);
+    else
+        LIBXL_TAILQ_REMOVE(&CTX->death_reported, evg, entry);
 
-    if (info->running || (!info->shutdown && !info->dying))
-        return ERROR_INVAL;
+    free(evg);
 
-    return 1;
+    if (!LIBXL_TAILQ_FIRST(&CTX->death_list) &&
+        libxl__ev_xswatch_isregistered(&CTX->death_watch))
+        libxl__ev_xswatch_deregister(gc, &CTX->death_watch);
+
+    CTX_UNLOCK;
 }
 
-int libxl_event_get_disk_eject_info(libxl_ctx *ctx, uint32_t domid, libxl_event *event, libxl_device_disk *disk)
-{
+void libxl_evdisable_domain_death(libxl_ctx *ctx,
+                                  libxl_evgen_domain_death *evg) {
     GC_INIT(ctx);
-    char *path;
+    libxl__evdisable_domain_death(gc, evg);
+    GC_FREE;
+}
+
+static void disk_eject_xswatch_callback(libxl__egc *egc, libxl__ev_xswatch *w,
+                                        const char *wpath, const char *epath) {
+    EGC_GC;
+    libxl_evgen_disk_eject *evg = (void*)w;
     char *backend;
     char *value;
     char backend_type[BACKEND_STRING_SIZE+1];
 
-    value = libxl__xs_read(gc, XBT_NULL, event->path);
+    value = libxl__xs_read(gc, XBT_NULL, wpath);
 
-    if (!value || strcmp(value,  "eject")) {
-        GC_FREE;
-        return 0;
+    if (!value || strcmp(value,  "eject"))
+        return;
+
+    if (libxl__xs_write(gc, XBT_NULL, wpath, "")) {
+        LIBXL__EVENT_DISASTER(egc, "xs_write failed acknowledging eject",
+                              errno, LIBXL_EVENT_TYPE_DISK_EJECT);
+        return;
     }
 
-    path = strdup(event->path);
-    path[strlen(path) - 6] = '\0';
-    backend = libxl__xs_read(gc, XBT_NULL, libxl__sprintf(gc, "%s/backend", path));
+    libxl_event *ev = NEW_EVENT(egc, DISK_EJECT, evg->domid);
+    libxl_device_disk *disk = &ev->u.disk_eject.disk;
+    
+    backend = libxl__xs_read(gc, XBT_NULL,
+                             libxl__sprintf(gc, "%.*s/backend",
+                                            (int)strlen(wpath)-6, wpath));
 
     sscanf(backend,
-            "/local/domain/%d/backend/%" TOSTRING(BACKEND_STRING_SIZE) "[a-z]/%*d/%*d",
-            &disk->backend_domid, backend_type);
+            "/local/domain/%d/backend/%" TOSTRING(BACKEND_STRING_SIZE)
+           "[a-z]/%*d/%*d",
+           &disk->backend_domid, backend_type);
     if (!strcmp(backend_type, "tap") || !strcmp(backend_type, "vbd")) {
         disk->backend = LIBXL_DISK_BACKEND_TAP;
     } else if (!strcmp(backend_type, "qdisk")) {
@@ -765,19 +854,83 @@ int libxl_event_get_disk_eject_info(libxl_ctx *ctx, uint32_t domid, libxl_event
         disk->backend = LIBXL_DISK_BACKEND_UNKNOWN;
     }
 
-    disk->pdev_path = strdup("");
+    disk->pdev_path = strdup(""); /* xxx fixme malloc failure */
     disk->format = LIBXL_DISK_FORMAT_EMPTY;
     /* this value is returned to the user: do not free right away */
-    disk->vdev = xs_read(ctx->xsh, XBT_NULL, libxl__sprintf(gc, "%s/dev", backend), NULL);
+    disk->vdev = xs_read(CTX->xsh, XBT_NULL,
+                         libxl__sprintf(gc, "%s/dev", backend), NULL);
     disk->removable = 1;
     disk->readwrite = 0;
     disk->is_cdrom = 1;
 
-    free(path);
+    libxl__event_occurred(egc, ev);
+}
+
+int libxl_evenable_disk_eject(libxl_ctx *ctx, uint32_t guest_domid,
+                              const char *vdev, libxl_ev_user user,
+                              libxl_evgen_disk_eject **evgen_out) {
+    GC_INIT(ctx);
+    CTX_LOCK;
+    int rc;
+    char *path;
+    libxl_evgen_disk_eject *evg = NULL;
+
+    evg = malloc(sizeof(*evg));  if (!evg) { rc = ERROR_NOMEM; goto out; }
+    memset(evg, 0, sizeof(*evg));
+    evg->user = user;
+    evg->domid = guest_domid;
+    LIBXL_LIST_INSERT_HEAD(&CTX->disk_eject_evgens, evg, entry);
+
+    evg->vdev = strdup(vdev);
+    if (!evg->vdev) { rc = ERROR_NOMEM; goto out; }
+
+    uint32_t domid = libxl_get_stubdom_id(ctx, guest_domid);
+
+    if (!domid)
+        domid = guest_domid;
+
+    path = libxl__sprintf(gc, "%s/device/vbd/%d/eject",
+                 libxl__xs_get_dompath(gc, domid),
+                 libxl__device_disk_dev_number(vdev, NULL, NULL));
+    if (!path) { rc = ERROR_NOMEM; goto out; }
+
+    rc = libxl__ev_xswatch_register(gc, &evg->watch,
+                                    disk_eject_xswatch_callback, path);
+    if (rc) goto out;
+
+    *evgen_out = evg;
+    CTX_UNLOCK;
     GC_FREE;
-    return 1;
+    return 0;
+
+ out:
+    if (evg)
+        libxl__evdisable_disk_eject(gc, evg);
+    CTX_UNLOCK;
+    GC_FREE;
+    return rc;
+}
+
+void libxl__evdisable_disk_eject(libxl__gc *gc, libxl_evgen_disk_eject *evg) {
+    CTX_LOCK;
+
+    LIBXL_LIST_REMOVE(evg, entry);
+
+    if (libxl__ev_xswatch_isregistered(&evg->watch))
+        libxl__ev_xswatch_deregister(gc, &evg->watch);
+
+    free(evg->vdev);
+    free(evg);
+
+    CTX_UNLOCK;
 }
 
+void libxl_evdisable_disk_eject(libxl_ctx *ctx, libxl_evgen_disk_eject *evg) {
+    GC_INIT(ctx);
+    libxl__evdisable_disk_eject(gc, evg);
+    GC_FREE;
+}    
+
 int libxl_domain_destroy(libxl_ctx *ctx, uint32_t domid)
 {
     GC_INIT(ctx);
tools/libxl/libxl.h +9 -46

79 lines not on this page · raw message

tools/libxl/libxl_event.c +218 -18

287 lines not on this page · raw message

tools/libxl/libxl_event.h +179 -4

195 lines not on this page · raw message

tools/libxl/libxl_internal.h +74 -3

133 lines not on this page · raw message

tools/libxl/libxl_types.idl +29 -5
index 574dec7..a6dac79 100644
@@ -75,11 +75,6 @@ libxl_action_on_shutdown = Enumeration("action_on_shutdown", [
     (6, "COREDUMP_RESTART"),
     ])
 
-libxl_event_type = Enumeration("event_type", [
-    (1, "DOMAIN_DEATH"),
-    (2, "DISK_EJECT"),
-    ])
-
 libxl_button = Enumeration("button", [
     (1, "POWER"),
     (2, "SLEEP"),
@@ -395,3 +390,32 @@ libxl_sched_sedf = Struct("sched_sedf", [
     ("extratime", integer),
     ("weight", integer),
     ], dispose_fn=None)
+
+libxl_event_type = Enumeration("event_type", [
+    (1, "DOMAIN_SHUTDOWN"),
+    (2, "DOMAIN_DESTROY"),
+    (3, "DISK_EJECT"),
+    ])
+
+libxl_ev_user = UInt(64)
+
+libxl_ev_link = Builtin("ev_link", passby=PASS_BY_REFERENCE, private=True)
+
+libxl_event = Struct("event",[
+    ("link",     libxl_ev_link,0),
+     # for use by libxl; caller may use this once the event has been
+     #   returned by libxl_event_{check,wait}
+    ("domid",    libxl_domid),
+    ("domuuid",  libxl_uuid),
+    ("for_user", libxl_ev_user),
+    ("type",     libxl_event_type),
+    ("u", KeyedUnion(None, libxl_event_type, "type",
+          [("domain_shutdown", Struct(None, [
+                                             ("shutdown_reason", uint8),
+                                      ])),
+           ("domain_destroy", Struct(None, [])),
+           ("disk_eject", Struct(None, [
+                                        ("vdev", string),
+                                        ("disk", libxl_device_disk),
+                                 ])),
+           ]))])
tools/libxl/xl_cmdimpl.c +157 -113

354 lines not on this page · raw message

tools/ocaml/libs/xl/genwrap.py +1 -0
index 61abecf..5a02e8f 100644
@@ -273,6 +273,7 @@ if __name__ == '__main__':
         "device_model_info",
         "vcpuinfo",
         "topologyinfo",
+        "event",
         ]
 
     for t in blacklist:
Signature · 1 line
1.7.2.5
#7 lore raw

Re: [PATCH 3/9] libxl: New event generation API

Quoted 35 lines · Ian Jackson

Replace the existing API for retrieving high-level events (events about domains, etc.) from libxl with a new one.

This changes the definition and semantics of the `libxl_event' structure, and replaces the calls for obtaining information about domain death and disk eject events.

This is an incompatible change, sorry. The alternative was to try to provide both the previous horrid API and the new one, and would also involve never using the name `libxl_event' for the new interface.

The new "libxl_event" structure is blacklisted in the ocaml bindings for two reasons:
- It has a field name "type" (which is a keyword in ocaml); the ocaml idl generator should massage this field name on output, to "type_" perhaps.
- The ocaml idl generator does not support KeyedUnion.

---
 tools/libxl/libxl.c            |  329 +++++++++++++++++++++++++++++-----------
 tools/libxl/libxl.h            |   55 +------
 tools/libxl/libxl_event.c      |  236 ++++++++++++++++++++++++++---
 tools/libxl/libxl_event.h      |  183 ++++++++++++++++++++++-
 tools/libxl/libxl_internal.h   |   77 +++++++++-
 tools/libxl/libxl_types.idl    |   34 ++++-
 tools/libxl/xl_cmdimpl.c       |  270 +++++++++++++++++++--------------
 tools/ocaml/libs/xl/genwrap.py |    1 +
 8 files changed, 908 insertions(+), 277 deletions(-)
tools/libxl/libxl.c +0 -0
index 413b684..19ff12c 100644

tools/libxl/libxl.c int libxl_ctx_free(libxl_ctx *ctx) · line 123

Quoted 9 lines
tools/libxl/libxl.c +6 -0
@@ -95,6 +115,13 @@ int libxl_ctx_free(libxl_ctx *ctx)
 
     /* Deregister all libxl__ev_KINDs: */
 
+    free_disable_deaths(gc, &CTX->death_list);
+    free_disable_deaths(gc, &CTX->death_reported);
+
+    libxl_evgen_disk_eject *eject;
+    while ((eject = LIBXL_LIST_FIRST(&CTX->disk_eject_evgens)))
+        libxl__evdisable_disk_eject(gc, eject);

Why a helper for deaths but not ejects?

[...]

Quoted 36 lines
tools/libxl/libxl_event.c +0 -0
index ec66340..621a7cc 100644
 
 
 /*
tools/libxl/libxl_event.h +24 -0
index 63ef65e..0e83800 100644
 
+#define LIBXL_EVENTMASK_ALL (~(unsigned long)0)
+
+typedef int libxl_event_predicate(const libxl_event*, void *user);
+  /* Return value is 0 if the event is unwanted or non-0 if it is.
+   * Predicates are not allowed to fail.
+   */
+
+int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r,
+                      unsigned long typemask,
+                      libxl_event_predicate *predicate, void *predicate_user);
+  /* Searches for an event, already-happened, which matches typemask
+   * and predicate.  predicate==0 matches any event.
+   * libxl_event_check returns the event, which must then later be
+   * freed by the caller using libxl_event_free.
+   *
+   * Returns ERROR_NOT_READY if no such event has happened.
+   */
+
+int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r,
+                     unsigned long typemask,
+                     libxl_event_predicate *predicate, void *predicate_user);
+  /* Like libxl_event_check but blocks if no suitable events are
+   * available, until some are.  Uses libxl_osevent_beforepoll/
+   * _afterpoll so may be inefficient if very many domains are being

tools/libxl/libxl_event.h line 62

Quoted 10 lines
tools/libxl/libxl_event.h +10 -0
+   * handled by a single program.
+   */
+
+void libxl_event_free(libxl_ctx *ctx, libxl_event *event);
+
+
+/* Alternatively or additionally, the application may also use this: */
+
+typedef struct libxl_event_hooks {
+    uint64_t event_occurs_mask;

libxl_event_{wait,check} and LIBXL_EVENTMASK_ALL have an unsigned long mask. Are they not the same set of bits?

[...]

Quoted 5 lines

+ * The user value is returned in the generated events and may be
+ * used by the caller for whatever it likes. The type ev_user is
+ * guaranteed to be an unsigned integer type which is at least
+ * as big as uint64_t and is also guaranteed to be big enough to
+ * contain any intptr_t value.

Does anything actually guarantee that sizeof(uint64_t) > sizeof(intptr_t)? I'm sure it's true in practice and I'm happy to rely on it. Just interested.

Quoted 5 lines

+ *[...]

+ * Applications should ensure that they eventually retrieve every
+ * event using libxl_event_check or libxl_event_wait, since events
+ * which occur but are not retreived by the application will be queued

retrieved

Quoted 4 lines

+ * inside libxl indefinitely. libxl_event_check/_wait may be O(n)
+ * where n is the number of queued events which do not match the
+ * criteria specified in the arguments to check/wait.
+ */

[...]

Quoted 6 lines
tools/libxl/libxl_types.idl +0 -0
index 574dec7..a6dac79 100644
@@ -395,3 +390,32 @@ libxl_sched_sedf = Struct("sched_sedf", [
     ("extratime", integer),

tools/libxl/libxl_types.idl libxl_sched_sedf = Struct("sched_sedf", [ · line 400

Quoted 10 lines
tools/libxl/libxl_types.idl +8 -0
     ("weight", integer),
     ], dispose_fn=None)
+
+libxl_event_type = Enumeration("event_type", [
+    (1, "DOMAIN_SHUTDOWN"),
+    (2, "DOMAIN_DESTROY"),
+    (3, "DISK_EJECT"),
+    ])
+
+libxl_ev_user = UInt(64)

The other option here would be Builtin(...) and an entry in the builtin table in the wrapper generator.

Arguably the idl could be improved by causing Number() to have a width field. Currently it has a signedness and width is a property of UInt but the latter could be pushed up the hierarchy.

You'd still end up with
FOO = Number("FOO", width=X)
which isn't really much better.

Or the ocaml generate could handle Number as the biggest int.

Hrm. None of that seems all that much better than what you have. Chalk it up to potential future work.

tools/libxl/libxl_types.idl libxl_sched_sedf = Struct("sched_sedf", [ · line 405

Quoted 4 lines
tools/libxl/libxl_types.idl +4 -0
+libxl_ev_link = Builtin("ev_link", passby=PASS_BY_REFERENCE, private=True)
+
+libxl_event = Struct("event",[
+    ("link",     libxl_ev_link,0),

This "0" == "const=False" which is the default. I don't think it is necessary.

[...]

Quoted 9 lines
tools/libxl/xl_cmdimpl.c +0 -0
index 8c30de1..e292bfc 100644
@@ -1702,92 +1729,106 @@ start:
     }
     LOG("Waiting for domain %s (domid %d) to die [pid %ld]",
         d_config.c_info.name, domid, (long)getpid());

[...]

Quoted 3 lines
tools/libxl/xl_cmdimpl.c +2 -0
+    ret = libxl_evenable_domain_death(ctx, domid, 0, &deathw);
+    if (ret) goto out;

[...]

tools/libxl/xl_cmdimpl.c start: · line 1737

Quoted 2 lines
tools/libxl/xl_cmdimpl.c +2 -0
+    if (!diskws) {
+        diskws = xmalloc(sizeof(*diskws) * d_config.num_disks);

I didn't see this getting freed on the exit path.

tools/libxl/xl_cmdimpl.c start: · line 1745

Quoted 8 lines
tools/libxl/xl_cmdimpl.c +8 -0
+        for (i = 0; i < d_config.num_disks; i++)
+            diskws[i] = NULL;
+    }
+    for (i = 0; i < d_config.num_disks; i++) {
+        ret = libxl_evenable_disk_eject(ctx, domid, d_config.disks[i].vdev,
+                                        0, &diskws[i]);
+        if (ret) goto out;
+    }

This is all (I think) safe for num_disks == 0 but why waste the effort?

Incidentally we have libxl_device_disk.removable which might be an opportunity to optimise? Assuming it is meaningful in that way. I think in reality only emulated CD-ROM devices ever generate this event but perhaps exposing that in the API overcomplicates things.

[...]

Ian.

#8 lore raw

Re: [PATCH 3/9] libxl: New event generation API

Ian Campbell writes ("Re: [Xen-devel] [PATCH 3/9] libxl: New event generation API"):

Quoted 9 lines · Ian Jackson

tools/libxl/libxl.c int libxl_ctx_free(libxl_ctx *ctx) · line 123

Quoted 6 lines
tools/libxl/libxl.c +6 -0
+    free_disable_deaths(gc, &CTX->death_list);
+    free_disable_deaths(gc, &CTX->death_reported);
+
+    libxl_evgen_disk_eject *eject;
+    while ((eject = LIBXL_LIST_FIRST(&CTX->disk_eject_evgens)))
+        libxl__evdisable_disk_eject(gc, eject);

Why a helper for deaths but not ejects?

Because the deaths function needs to be called twice, once for each of two lists.

Quoted 5 lines

tools/libxl/libxl_event.h line 62

Quoted 2 lines
tools/libxl/libxl_event.h +2 -0
+typedef struct libxl_event_hooks {
+    uint64_t event_occurs_mask;

libxl_event_{wait,check} and LIBXL_EVENTMASK_ALL have an unsigned long mask. Are they not the same set of bits?

This is a mistake. I'll change it to 64 everywhere.

Quoted 9 lines
Quoted 5 lines

+ * The user value is returned in the generated events and may be
+ * used by the caller for whatever it likes. The type ev_user is
+ * guaranteed to be an unsigned integer type which is at least
+ * as big as uint64_t and is also guaranteed to be big enough to
+ * contain any intptr_t value.

Does anything actually guarantee that sizeof(uint64_t) > sizeof(intptr_t)? I'm sure it's true in practice and I'm happy to rely on it. Just interested.

No, nothing does. If we port this code to a platform where pointers are more than 64 bits, we will need to change the type of this field (to make it be an intptr_t or some other type).

Quoted 4 lines
Quoted 1 line

+libxl_ev_user = UInt(64)

The other option here would be Builtin(...) and an entry in the builtin table in the wrapper generator.

As I say, that prevents the ocaml idl generator from knowing that the type is 64 bits and so prevents it from using the right ocaml type.

Quoted 7 lines

Arguably the idl could be improved by causing Number() to have a width field. Currently it has a signedness and width is a property of UInt but the latter could be pushed up the hierarchy.

You'd still end up with
FOO = Number("FOO", width=X)
which isn't really much better.

Indeed.

Quoted 1 line

Or the ocaml generate could handle Number as the biggest int.

That's a bit wasteful.

Quoted 2 lines

Hrm. None of that seems all that much better than what you have. Chalk it up to potential future work.

Right.

Quoted 7 lines

tools/libxl/libxl_types.idl libxl_sched_sedf = Struct("sched_sedf", [ · line 405

Quoted 4 lines
tools/libxl/libxl_types.idl +4 -0
+libxl_ev_link = Builtin("ev_link", passby=PASS_BY_REFERENCE, private=True)
+
+libxl_event = Struct("event",[
+    ("link",     libxl_ev_link,0),

This "0" == "const=False" which is the default. I don't think it is necessary.

This is a leftover from when there was an in-idl comment parameter. I will remove it.

Quoted 9 lines

[...]

Quoted 3 lines
(quoted diff) +2 -0
+    ret = libxl_evenable_domain_death(ctx, domid, 0, &deathw);
+    if (ret) goto out;

[...]

tools/libxl/xl_cmdimpl.c start: · line 1737

Quoted 2 lines
tools/libxl/xl_cmdimpl.c +2 -0
+    if (!diskws) {
+        diskws = xmalloc(sizeof(*diskws) * d_config.num_disks);

I didn't see this getting freed on the exit path.

This is deliberate. Why bother freeing things when the process is about to exit.

Quoted 10 lines

tools/libxl/xl_cmdimpl.c start: · line 1745

Quoted 8 lines
tools/libxl/xl_cmdimpl.c +8 -0
+        for (i = 0; i < d_config.num_disks; i++)
+            diskws[i] = NULL;
+    }
+    for (i = 0; i < d_config.num_disks; i++) {
+        ret = libxl_evenable_disk_eject(ctx, domid, d_config.disks[i].vdev,
+                                        0, &diskws[i]);
+        if (ret) goto out;
+    }

This is all (I think) safe for num_disks == 0 but why waste the effort?

I'm not sure I follow. Do you think I should put an if() round it, testing whether d_config.num_disks is nonzero ?

In which case by "effort" do you mean computer effort ? Surely you can't mean that because this performance detail of this code is entirely irrelevant. But you can't mean human effort in the code because adding the test would be additional code to write, read, understand and maintain ...

Quoted 4 lines

Incidentally we have libxl_device_disk.removable which might be an opportunity to optimise? Assuming it is meaningful in that way. I think in reality only emulated CD-ROM devices ever generate this event but perhaps exposing that in the API overcomplicates things.

Optimise to save on pointless xenstore watches you mean ?

Ian.

#9 lore raw

Re: [PATCH 3/9] libxl: New event generation API

Quoted 10 lines · Ian Jackson

Ian Campbell writes ("Re: [Xen-devel] [PATCH 3/9] libxl: New event generation API"):

Quoted 6 lines · Ian Jackson
Quoted 2 lines

+libxl_ev_user = UInt(64)

The other option here would be Builtin(...) and an entry in the builtin table in the wrapper generator.

As I say, that prevents the ocaml idl generator from knowing that the type is 64 bits and so prevents it from using the right ocaml type.

The ocaml type of a "builtin" is supplied by the builtin table in the generator. However:

[...]

Quoted 4 lines
Quoted 2 lines

Hrm. None of that seems all that much better than what you have. Chalk it up to potential future work.

Right.

ACK.

Quoted 4 lines
Quoted 4 lines

[...]

Quoted 3 lines
(quoted diff) +2 -0
+    ret = libxl_evenable_domain_death(ctx, domid, 0, &deathw);
+    if (ret) goto out;
Quoted 8 lines
Quoted 5 lines

[...]

tools/libxl/xl_cmdimpl.c start: · line 1737

Quoted 2 lines
tools/libxl/xl_cmdimpl.c +2 -0
+    if (!diskws) {
+        diskws = xmalloc(sizeof(*diskws) * d_config.num_disks);

I didn't see this getting freed on the exit path.

This is deliberate. Why bother freeing things when the process is about to exit.

Usually I agree.

However xl is intended as a libxl testbed as well as a toolstack in its own right and it is useful to be able to run tools such as valgrind on it to detect leaks in the library, but this requires not having too many "false positives" in xl.

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
tools/libxl/xl_cmdimpl.c +8 -0
+        for (i = 0; i < d_config.num_disks; i++)
+            diskws[i] = NULL;
+    }
+    for (i = 0; i < d_config.num_disks; i++) {
+        ret = libxl_evenable_disk_eject(ctx, domid, d_config.disks[i].vdev,
+                                        0, &diskws[i]);
+        if (ret) goto out;
+    }
Quoted 4 lines
Quoted 1 line

This is all (I think) safe for num_disks == 0 but why waste the effort?

I'm not sure I follow. Do you think I should put an if() round it, testing whether d_config.num_disks is nonzero ?

I did but then I read the below which is entirely correct.

Quoted 6 lines

In which case by "effort" do you mean computer effort ? Surely you can't mean that because this performance detail of this code is entirely irrelevant. But you can't mean human effort in the code because adding the test would be additional code to write, read, understand and maintain ...

Quoted 6 lines
Quoted 4 lines

Incidentally we have libxl_device_disk.removable which might be an opportunity to optimise? Assuming it is meaningful in that way. I think in reality only emulated CD-ROM devices ever generate this event but perhaps exposing that in the API overcomplicates things.

Optimise to save on pointless xenstore watches you mean ?

That and event overhead generally of having the events registered and being tracked etc. In the common case we probably have 1 disk and 1 cdrom so we've effectively doubled the amount of stuff we're dealing with -- whether this becomes significant e.g. on a system with 100+ VMs I'm not sure.

Ian.

#10 lore raw

Re: [PATCH 3/9] libxl: New event generation API

Ian Campbell writes ("Re: [Xen-devel] [PATCH 3/9] libxl: New event generation API"):

Quoted 5 lines · Ian Jackson
Quoted 4 lines

Ian Campbell writes ("Re: [Xen-devel] [PATCH 3/9] libxl: New event generation API"):

Quoted 3 lines · Ian Jackson
Quoted 2 lines

+ ret = libxl_evenable_domain_death(ctx, domid, 0, &deathw);

...

Quoted 7 lines
Quoted 6 lines
Quoted 3 lines
Quoted 1 line

+ diskws = xmalloc(sizeof(*diskws) * d_config.num_disks);

I didn't see this getting freed on the exit path.

This is deliberate. Why bother freeing things when the process is about to exit.

Quoted 6 lines

Usually I agree.

However xl is intended as a libxl testbed as well as a toolstack in its own right and it is useful to be able to run tools such as valgrind on it to detect leaks in the library, but this requires not having too many "false positives" in xl.

Hmm, true. OK, I will clean up these evgens.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

Incidentally we have libxl_device_disk.removable which might be an opportunity to optimise? Assuming it is meaningful in that way. I think in reality only emulated CD-ROM devices ever generate this event but perhaps exposing that in the API overcomplicates things.

Quoted 7 lines
Quoted 1 line

Optimise to save on pointless xenstore watches you mean ?

That and event overhead generally of having the events registered and being tracked etc. In the common case we probably have 1 disk and 1 cdrom so we've effectively doubled the amount of stuff we're dealing with -- whether this becomes significant e.g. on a system with 100+ VMs I'm not sure.

OK, it's an easy enough test to add. I'll do so.

Ian.

#11 lore raw

PATCH v7 4/9 libxl: introduce libxl_fd_set_nonblock, rationalise _cloexec

In reply to Ian Jackson

We want a function for setting fds to nonblocking, so introduce one.

This is a very similar requirement to that for libxl_fd_set_cloexec, so make it common with that.

While we're at it, fix a few deficiences that make this latter function less desirable than it could be:
* Change the return from 0/-1 (like a syscall) to a libxl error code
* Take a boolean parameter for turning the flag on and off
* Log on error (and so, take a ctx for this purpose)

Change callers of libxl_fd_set_cloexec to notice errors. (Although, such errors are highly unlikely.)

---
 tools/libxl/libxl.c      |   33 ++++++++++++++++++++++++++-------
 tools/libxl/libxl.h      |    7 ++++++-
 tools/libxl/libxl_qmp.c  |    3 ++-
 tools/libxl/xl_cmdimpl.c |    3 ++-
 4 files changed, 36 insertions(+), 10 deletions(-)
tools/libxl/libxl.c +26 -7
index 19ff12c..c68c165 100644
@@ -3655,19 +3655,38 @@ int libxl_cpupool_movedomain(libxl_ctx *ctx, uint32_t poolid, uint32_t domid)
     return 0;
 }
 
-int libxl_fd_set_cloexec(int fd)
+static int fd_set_flags(libxl_ctx *ctx, int fd,
+                        int fcntlgetop, int fcntlsetop, const char *fl,
+                        int flagmask, int set_p)
 {
-    int flags = 0;
+    int flags, r;
 
-    if ((flags = fcntl(fd, F_GETFD)) == -1) {
-        flags = 0;
+    flags = fcntl(fd, fcntlgetop);
+    if (flags == -1) {
+        LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "fcntl(,F_GET%s) failed",fl);
+        return ERROR_FAIL;
     }
-    if ((flags & FD_CLOEXEC)) {
-        return 0;
+
+    if (set_p)
+        flags |= flagmask;
+    else
+        flags &= ~flagmask;
+
+    r = fcntl(fd, fcntlsetop, flags);
+    if (r == -1) {
+        LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "fcntl(,F_SET%s) failed",fl);
+        return ERROR_FAIL;
     }
-    return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
+
+    return 0;
 }
 
+int libxl_fd_set_cloexec(libxl_ctx *ctx, int fd, int cloexec)
+  { return fd_set_flags(ctx,fd, F_GETFD,F_SETFD,"FD", FD_CLOEXEC, cloexec); }
+
+int libxl_fd_set_nonblock(libxl_ctx *ctx, int fd, int nonblock)
+  { return fd_set_flags(ctx,fd, F_GETFL,F_SETFL,"FL", O_NONBLOCK, nonblock); }
+
 /*
  * Local variables:
  * mode: C
tools/libxl/libxl.h +6 -1
index 4d3391f..e32881b 100644
@@ -613,7 +613,12 @@ const char *libxl_run_dir_path(void);
 const char *libxl_xenpaging_dir_path(void);
 
 /* misc */
-int libxl_fd_set_cloexec(int fd);
+
+/* Each of these sets or clears the flag according to whether the
+ * 2nd parameter is nonzero.  On failure, they log, and
+ * return ERROR_FAIL, but also leave errno valid. */
+int libxl_fd_set_cloexec(libxl_ctx *ctx, int fd, int cloexec);
+int libxl_fd_set_nonblock(libxl_ctx *ctx, int fd, int nonblock);
 
 #include <libxl_event.h>
 
tools/libxl/libxl_qmp.c +2 -1
index 61d9769..1ee82ae 100644
@@ -324,7 +324,8 @@ static int qmp_open(libxl__qmp_handler *qmp, const char *qmp_socket_path,
     if (fcntl(qmp->qmp_fd, F_SETFL, flags | O_NONBLOCK) == -1) {
         return -1;
     }
-    libxl_fd_set_cloexec(qmp->qmp_fd);
+    ret = libxl_fd_set_cloexec(qmp->ctx, qmp->qmp_fd, 1);
+    if (ret) return -1;
 
     memset(&qmp->addr, 0, sizeof (&qmp->addr));
     qmp->addr.sun_family = AF_UNIX;
tools/libxl/xl_cmdimpl.c +2 -1
index e292bfc..c2b7a1e 100644
@@ -1495,7 +1495,8 @@ static int create_domain(struct domain_create *dom_info)
             restore_fd = migrate_fd;
         } else {
             restore_fd = open(restore_file, O_RDONLY);
-            libxl_fd_set_cloexec(restore_fd);
+            rc = libxl_fd_set_cloexec(ctx, restore_fd, 1);
+            if (rc) return rc;
         }
 
         CHK_ERRNO( libxl_read_exactly(ctx, restore_fd, &hdr,
Signature · 1 line
1.7.2.5
#12 lore raw

PATCH v7 5/9 libxl: Permit multithreaded event waiting

In reply to Ian Jackson

Previously, the context would be locked whenever we were waiting in libxl's own call to poll (waiting for operating system events).

This would mean that multiple simultaneous calls to libxl_event_wait in different threads with different parameters would not work properly.

If we simply unlock the context, it would be possible for another thread to discover the occurrence of the event we were waiting for, without us even waking up, and we would remain in poll. So we need a way to wake up other threads: a pipe, one for each thread in poll.

We also need to move some variables from globals in the ctx to be per-polling-thread.

---
 tools/libxl/libxl.c          |   18 +++-
 tools/libxl/libxl_event.c    |  196 ++++++++++++++++++++++++++++++++++--------
 tools/libxl/libxl_internal.h |   50 ++++++++++-
 3 files changed, 218 insertions(+), 46 deletions(-)
tools/libxl/libxl.c +14 -4
index c68c165..9890d79 100644
@@ -49,8 +49,9 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,
 
     ctx->osevent_hooks = 0;
 
-    ctx->fd_polls = 0;
-    ctx->fd_rindex = 0;
+    LIBXL_LIST_INIT(&ctx->pollers_event);
+    LIBXL_LIST_INIT(&ctx->pollers_idle);
+
     LIBXL_LIST_INIT(&ctx->efds);
     LIBXL_TAILQ_INIT(&ctx->etimes);
 
@@ -61,6 +62,9 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,
     LIBXL_TAILQ_INIT(&ctx->death_list);
     libxl__ev_xswatch_init(&ctx->death_watch);
 
+    rc = libxl__poller_init(ctx, &ctx->poller_app);
+    if (rc) goto out;
+
     if ( stat(XENSTORE_PID_FILE, &stat_buf) != 0 ) {
         LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "Is xenstore daemon running?\n"
                      "failed to stat %s", XENSTORE_PID_FILE);
@@ -135,8 +139,14 @@ int libxl_ctx_free(libxl_ctx *ctx)
     libxl_version_info_dispose(&ctx->version_info);
     if (ctx->xsh) xs_daemon_close(ctx->xsh);
 
-    free(ctx->fd_polls);
-    free(ctx->fd_rindex);
+    libxl__poller_dispose(&ctx->poller_app);
+    assert(LIBXL_LIST_EMPTY(&ctx->pollers_event));
+    libxl__poller *poller, *poller_tmp;
+    LIBXL_LIST_FOREACH_SAFE(poller, &ctx->pollers_idle, entry, poller_tmp) {
+        libxl__poller_dispose(poller);
+        free(poller);
+    }
+
     free(ctx->watch_slots);
 
     discard_events(&ctx->occurred);
tools/libxl/libxl_event.c +158 -38

320 lines not on this page · raw message

tools/libxl/libxl_internal.h +46 -4

68 lines not on this page · raw message

Signature · 1 line
1.7.2.5
#13 lore raw

Re: [PATCH 5/9] libxl: Permit multithreaded event waiting

Quoted 7 lines · Ian Jackson

Previously, the context would be locked whenever we were waiting in libxl's own call to poll (waiting for operating system events).

This would mean that multiple simultaneous calls to libxl_event_wait in different threads with different parameters would not work properly.

Quoted 7 lines

If we simply unlock the context, it would be possible for another thread to discover the occurrence of the event we were waiting for, without us even waking up, and we would remain in poll. So we need a way to wake up other threads: a pipe, one for each thread in poll.

We also need to move some variables from globals in the ctx to be per-polling-thread.

I don't think this relates to this patch, just that the mention of multithreaded waiting brought it to mind. What are the intended semantics of two calls to libxl_event_wait with overlapping event masks?

Do we expect that the caller must have called the appropriate evenables twice such that both waits get an event (possibly discriminate via the predicate)?

Presumably we want to ensure that one of the waits doesn't sleep for ever.

How does this interact with events generated via the hooks mechanism? Do we always deliver to the explicit wait in preference?

Quoted 7 lines
---
 tools/libxl/libxl.c          |   18 +++-
 tools/libxl/libxl_event.c    |  196 ++++++++++++++++++++++++++++++++++--------
 tools/libxl/libxl_internal.h |   50 ++++++++++-
 3 files changed, 218 insertions(+), 46 deletions(-)

[...]

Quoted 27 lines
tools/libxl/libxl_event.c +6 -6
index 621a7cc..82889f6 100644
@@ -542,30 +542,39 @@ static int beforepoll_internal(libxl__gc *gc, int *nfds_io,
                 maxfd = efd->fd + 1;
         }
         /* make sure our array is as big as *nfds_io */
-        if (CTX->fd_rindex_allocd < maxfd) {
+        if (poller->fd_rindex_allocd < maxfd) {
             assert(maxfd < INT_MAX / sizeof(int) / 2);
-            int *newarray = realloc(CTX->fd_rindex, sizeof(int) * maxfd);
+            int *newarray = realloc(poller->fd_rindex, sizeof(int) * maxfd);
             if (!newarray) { rc = ERROR_NOMEM; goto out; }
-            memset(newarray + CTX->fd_rindex_allocd, 0,
-                   sizeof(int) * (maxfd - CTX->fd_rindex_allocd));
-            CTX->fd_rindex = newarray;
-            CTX->fd_rindex_allocd = maxfd;
+            memset(newarray + poller->fd_rindex_allocd, 0,
+                   sizeof(int) * (maxfd - poller->fd_rindex_allocd));
+            poller->fd_rindex = newarray;
+            poller->fd_rindex_allocd = maxfd;
         }
     }
 
     int used = 0;

[...]

tools/libxl/libxl_event.c static int beforepoll_internal(libxl__gc *gc, int *nfds_io, · line 567

Quoted 11 lines
tools/libxl/libxl_event.c +11 -0
+
+#define REQUIRE_FD(req_fd, req_events, efd) do{                 \
+        if ((req_events)) {                                     \
+            if (used < *nfds_io) {                              \
+                fds[used].fd = (req_fd);                        \
+                fds[used].events = (req_events);                \
+                fds[used].revents = 0;                          \
+                assert((req_fd) < poller->fd_rindex_allocd);    \
+                poller->fd_rindex[(req_fd)] = used;             \
+            }                                                   \
+            used++;                                             \

Used is expected to be in the calling context? IOC -- this is defined temporarily within a function, the diff context (which I've now trimmed) confused me.

Does this actually add anything above doing

	LIBXL_LIST_FOREACH(...) {
		/* the body of require_fd */
	}

?

Quoted 13 lines
tools/libxl/libxl_event.c +10 -0
+        }                                                       \
+    }while(0)
+
+    LIBXL_LIST_FOREACH(efd, &CTX->efds, entry)
+        REQUIRE_FD(efd->fd, efd->events, efd);
+
+    REQUIRE_FD(poller->wakeup_pipe[0], POLLIN, 0);
+
+#undef REQUIRE_FD
+
     rc = used <= *nfds_io ? 0 : ERROR_BUFFERFULL;
 
     *nfds_io = used;

[...]

Quoted 15 lines
tools/libxl/libxl_event.c +2 -1
@@ -630,22 +640,31 @@ static int afterpoll_check_fd(libxl_ctx *ctx,
     return revents;
 }
 
-static void afterpoll_internal(libxl__egc *egc,
+static void afterpoll_internal(libxl__egc *egc, libxl__poller *poller,
                                int nfds, const struct pollfd *fds,
                                struct timeval now)
 {
     EGC_GC;
     libxl__ev_fd *efd;
 
+
     LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) {
         if (!efd->events)

tools/libxl/libxl_event.c static int afterpoll_check_fd(libxl_ctx *ctx, · line 661

Quoted 10 lines
tools/libxl/libxl_event.c +3 -1
             continue;
 
-        int revents = afterpoll_check_fd(CTX,fds,nfds, efd->fd,efd->events);
+        int revents = afterpoll_check_fd(poller,fds,nfds, efd->fd,efd->events);
         if (revents)
             efd->func(egc, efd, efd->fd, efd->events, revents);
     }
 
+    if (afterpoll_check_fd(poller,fds,nfds, poller->wakeup_pipe[0],POLLIN)) {
+        char buf[256];

Is it (theoretically) possible to have more than 256 events pending?

Quoted 9 lines
tools/libxl/libxl_event.c +6 -0
+        int r = read(poller->wakeup_pipe[0], buf, sizeof(buf));
+        if (r < 0)
+            if (errno != EINTR && errno != EWOULDBLOCK)
+                LIBXL__EVENT_DISASTER(egc, "read wakeup", errno, 0);
+    }
+
     for (;;) {
         libxl__ev_time *etime = LIBXL_TAILQ_FIRST(&CTX->etimes);
         if (!etime)

[...]

Quoted 22 lines
tools/libxl/libxl_event.c +17 -1
@@ -858,7 +880,94 @@ int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r,
     return rc;
 }
 
-static int eventloop_iteration(libxl__egc *egc) {
+/*
+ * Manipulation of pollers
+ */
+
+int libxl__poller_init(libxl_ctx *ctx, libxl__poller *p)
+{
+    int r, rc;
+    p->fd_polls = 0;
+    p->fd_rindex = 0;
+
+    r = pipe(p->wakeup_pipe);
+    if (r) {
+        LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot create poller pipe");
+        rc = ERROR_FAIL;
+        goto out;
+    }
+

tools/libxl/libxl_event.c int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r, · line 909

Quoted 10 lines
tools/libxl/libxl_event.c +10 -0
+    rc = libxl_fd_set_nonblock(ctx, p->wakeup_pipe[0], 1);
+    if (rc) goto out;
+
+    rc = libxl_fd_set_nonblock(ctx, p->wakeup_pipe[1], 1);
+    if (rc) goto out;
+
+    return 0;
+
+ out:
+    libxl__poller_dispose(p);

The dispose function checks for fd > 0 before closing but if you take the first goto out (pipe failed) then wake_pipe[{0,1}] are still undefined?

tools/libxl/libxl_event.c int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r, · line 916

Quoted 7 lines
tools/libxl/libxl_event.c +7 -0
+    return rc;
+}
+
+void libxl__poller_dispose(libxl__poller *p)
+{
+    if (p->wakeup_pipe[1] > 0) close(p->wakeup_pipe[1]);
+    if (p->wakeup_pipe[0] > 0) close(p->wakeup_pipe[0]);

Strictly speaking 0 is a valid value for an open fd.

I once saw a bug (in gzip iirc) where, because stdin had inadvertently been closed, a dup() of some sort returned 0 but the subsequent checks were for >0 rather than >=. Slightly unusual case but it took an age (for someone else...) to debug.

Quoted 9 lines
tools/libxl/libxl_event.c +9 -0
+    free(p->fd_polls);
+    free(p->fd_rindex);
+}
+
+libxl__poller *libxl__poller_get(libxl_ctx *ctx)
+{
+    /* must be called with ctx locked */
+    int rc;
+

tools/libxl/libxl_event.c int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r, · line 935

Quoted 10 lines
tools/libxl/libxl_event.c +10 -0
+    libxl__poller *p = LIBXL_LIST_FIRST(&ctx->pollers_idle);
+    if (p)
+        return p;
+
+    p = malloc(sizeof(*p));
+    if (!p) {
+        LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot allocate poller");
+        return 0;
+    }
+    memset(p, 0, sizeof(*p));

Hrm, I guess this is where p->wakeup_pipe gets initialised. Likewise the call to _init in ctx_alloc is preceded by a memset. Not entirely obvious but I guess its ok. (initialising to -1 in _init would solve both this and the 0-is-a-valid-fd)

Quoted 10 lines
tools/libxl/libxl_event.c +10 -0
+
+    rc = libxl__poller_init(ctx, p);
+    if (rc) return NULL;
+
+    return p;
+}
+
+void libxl__poller_put(libxl_ctx *ctx, libxl__poller *p)
+{
+    LIBXL_LIST_INSERT_HEAD(&ctx->pollers_idle, p, entry);

tools/libxl/libxl_event.c int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r, · line 955

Quoted 10 lines
tools/libxl/libxl_event.c +10 -0
+}
+
+void libxl__poller_wakeup(libxl__egc *egc, libxl__poller *p)
+{
+    static const char buf[1] = "";
+
+    for (;;) {
+        int r = write(p->wakeup_pipe[1], buf, 1);
+        if (r==1) return;
+        assert(r==-1);

There's no possibility of r == 0 here?

tools/libxl/libxl_event.c int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r, · line 957

Quoted 2 lines
tools/libxl/libxl_event.c +2 -0
+        if (errno == EINTR) continue;
+        if (errno == EWOULDBLOCK) return;

write(2) says that both EWOULDBLOCK and EAGAIN are valid returns for a non-blocking fd and may have different values so apps should check for both.

Quoted 16 lines
tools/libxl/libxl_event.c +13 -0
+        LIBXL__EVENT_DISASTER(egc, "cannot poke watch pipe", errno, 0);
+        return;
+    }
+}
+
+/*
+ * Main event loop iteration
+ */
+
+static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {
+    /* The CTX must be locked EXACTLY ONCE so that this function
+     * can unlock it when it polls.
+     */
     EGC_GC;
     int rc;
     struct timeval now;

[...]

tools/libxl/libxl_event.c static int eventloop_iteration(libxl__egc *egc) { · line 1017

Quoted 7 lines
tools/libxl/libxl_event.c +2 -1
@@ -900,7 +1013,8 @@ static int eventloop_iteration(libxl__egc *egc) {
     rc = libxl__gettimeofday(gc, &now);
     if (rc) goto out;
 
-    afterpoll_internal(egc, CTX->fd_polls_allocd, CTX->fd_polls, now);
+    afterpoll_internal(egc, poller,
+                       poller->fd_polls_allocd, poller->fd_polls, now);

Can this function be simplified to take just (egc, poller, now)? Likewise beforepoll_internal?

Quoted 28 lines
tools/libxl/libxl_event.c +0 -0
     CTX_UNLOCK;
 
 
tools/libxl/libxl_internal.h +16 -0
index edb73eb..53d2462 100644
@@ -205,6 +205,33 @@ struct libxl__evgen_disk_eject {
 _hidden void
 libxl__evdisable_disk_eject(libxl__gc*, libxl_evgen_disk_eject*);
 
+typedef struct libxl__poller libxl__poller;
+struct libxl__poller {
+    /*
+     * These are used to allow other threads to wake up a thread which
+     * may be stuck in poll, because whatever it was waiting for
+     * hadn't happened yet.  Threads which generate events will write
+     * a byte to each pipe.  A thread which is waiting will empty its
+     * own pipe, and put its poller on the pollers_event list, before
+     * releasing the ctx lock and going into poll; when it comes out
+     * of poll it will take the poller off the pollers_event list.
+     *
+     * When a thread is done with a poller it should put it onto
+     * pollers_idle, where it can be reused later.
+     *
+     * The "poller_app" is never idle, but is sometimes on
+     * pollers_event.

tools/libxl/libxl_internal.h struct libxl__evgen_disk_eject { · line 233

Quoted 10 lines
tools/libxl/libxl_internal.h +10 -0
+     */
+    LIBXL_LIST_ENTRY(libxl__poller) entry;
+
+    struct pollfd *fd_polls;
+    int fd_polls_allocd;
+
+    int fd_rindex_allocd;
+    int *fd_rindex; /* see libxl_osevent_beforepoll */
+
+    int wakeup_pipe[2]; /* 0 means no fd allocated */

Or does it ;-)

tools/libxl/libxl_internal.h struct libxl__ctx { · line 265

Quoted 13 lines
tools/libxl/libxl_internal.h +2 -4
+};
 
 struct libxl__ctx {
     xentoollog_logger *lg;
@@ -235,10 +262,9 @@ struct libxl__ctx {
       /* See the comment for OSEVENT_HOOK_INTERN in libxl_event.c
        * for restrictions on the use of the osevent fields. */
 
-    struct pollfd *fd_polls;
-    int fd_polls_allocd;
-    int fd_rindex_allocd;
-    int *fd_rindex; /* see libxl_osevent_beforepoll */
+    libxl__poller poller_app; /* libxl_osevent_beforepoll and _afterpoll */

This presumably means that an app can only use before/afterpoll from one thread at a time. Hardly an onerous requirement but worth noting perhaps?

Could also check that pooler_app.entry is not currently on a list?

tools/libxl/libxl_internal.h _hidden void libxl__event_disaster(libxl__egc*, const char *msg, int errnoval, · line 553

Quoted 10 lines
tools/libxl/libxl_internal.h +3 -0
+    LIBXL_LIST_HEAD(, libxl__poller) pollers_event, pollers_idle;
+
     LIBXL_LIST_HEAD(, libxl__ev_fd) efds;
     LIBXL_TAILQ_HEAD(, libxl__ev_time) etimes;
 
@@ -524,6 +550,22 @@ _hidden void libxl__event_disaster(libxl__egc*, const char *msg, int errnoval,
     libxl__event_disaster(egc, msg, errnoval, type, __FILE__,__LINE__,__func__)
 
 
+/* Fills in, or disposes of, the resources held by, a poller whose

That third comma read weirdly to me.

tools/libxl/libxl_internal.h _hidden void libxl__event_disaster(libxl__egc*, const char *msg, int errnoval, · line 554

Quoted 1 line
tools/libxl/libxl_internal.h +1 -0
+ * space the caller has allocated.  ctx must be locked. */

init doesn't appear to do anything which needs a lock?

tools/libxl/libxl_internal.h _hidden void libxl__event_disaster(libxl__egc*, const char *msg, int errnoval, · line 567

Quoted 13 lines
tools/libxl/libxl_internal.h +13 -0
+int libxl__poller_init(libxl_ctx *ctx, libxl__poller *p);
+void libxl__poller_dispose(libxl__poller *p);
+
+/* Obtain a fresh poller from malloc or the idle list, and put it
+ * away again afterwards.  _get can fail, returning NULL.
+ * ctx must be locked. */
+libxl__poller *libxl__poller_get(libxl_ctx *ctx);
+void libxl__poller_put(libxl_ctx *ctx, libxl__poller *p);
+
+/* Notifies whoever is polling using p that they should wake up.
+ * ctx must be locked. */
+void libxl__poller_wakeup(libxl__egc *egc, libxl__poller *p);
+

Ian.

#14 lore raw

Re: [PATCH 5/9] libxl: Permit multithreaded event waiting

Ian Campbell writes ("Re: [Xen-devel] [PATCH 5/9] libxl: Permit multithreaded event waiting"):

Quoted 7 lines · Ian Jackson
Quoted 2 lines

We also need to move some variables from globals in the ctx to be per-polling-thread.

I don't think this relates to this patch, just that the mention of multithreaded waiting brought it to mind. What are the intended semantics of two calls to libxl_event_wait with overlapping event masks?

You get each event exactly once, via one of the (possibly several) suitable libxl_event_wait calls.

Quoted 3 lines

Do we expect that the caller must have called the appropriate evenables twice such that both waits get an event (possibly discriminate via the predicate)?

No. Well, I guess the caller could do that by divvying up the ev_user space between the two calls, but it would be a very perverse thing to do.

Quoted 2 lines

Presumably we want to ensure that one of the waits doesn't sleep for ever.

Yes, that's what the wakeup pipe is for.

Quoted 2 lines

How does this interact with events generated via the hooks mechanism? Do we always deliver to the explicit wait in preference?

No. As the doc comment for libxl_event_register_callbacks says:

* Arranges that libxl will henceforth call event_occurs for any
* events whose type is set in event_occurs_mask, rather than
* queueing the event for retrieval by libxl_event_check/wait.
* Events whose bit is clear in mask are not affected.

So if you ask for callbacks you don't get the events via wait.

Ian.

#15 lore raw

PATCH v7 6/9 libxl: Asynchronous/long-running operation infrastructure

In reply to Ian Jackson

Provide a new set of machinery for writing public libxl functions which may take a long time. The application gets to decide whether they want the function to be synchronous, or whether they'd prefer to get a callback, or an event, when the operation is complete.

User(s) of this machinery will be introduced in later patch(es).

---
 tools/libxl/libxl.h          |   50 ++++++++++++
 tools/libxl/libxl_event.c    |  183 ++++++++++++++++++++++++++++++++++++++++++
 tools/libxl/libxl_internal.h |  112 ++++++++++++++++++++++++++
 tools/libxl/libxl_types.idl  |    4 +
 4 files changed, 349 insertions(+), 0 deletions(-)
tools/libxl/libxl.h +50 -0
index e32881b..416d6e8 100644
@@ -235,8 +235,58 @@ enum {
     ERROR_NOT_READY = -11,
     ERROR_OSEVENT_REG_FAIL = -12,
     ERROR_BUFFERFULL = -13,
+    ERROR_ASYNC_INPROGRESS = -14,
 };
 
+
+/*
+ * Some libxl operations can take a long time.  These functions take a
+ * parameter to control their concurrency:
+ *     libxl_asyncop_how *ao_how
+ *
+ * If ao_how==NULL, the function will be synchronous.
+ *
+ * If ao_how!=NULL, the function will set the operation going, and
+ * if this is successful will return ERROR_ASYNCH_INPROGRESS.
+ *
+ * If ao_how->callback!=NULL, the callback will be called when the
+ * operation completes.  The same rules as for libxl_event_hooks
+ * apply, including the reentrancy rules and the possibility of
+ * "disaster", except that libxl calls ao_how->callback instead of
+ * libxl_event_hooks.event_occurs.
+ *
+ * If ao_how->callback==NULL, a libxl_event will be generated which
+ * can be obtained from libxl_event_wait or libxl_event_check.  The
+ * event will have type OPERATION_COMPLETE (which is not used
+ * elsewhere).
+ *
+ * Note that it is possible for an asynchronous operation which is to
+ * result in a callback to complete during its initiating function
+ * call.  In this case the initating function will return
+ * ERROR_ASYNCH_INPROGRESS, even though by the time it returns the
+ * operation is complete and the callback has already happened.
+ *
+ * The application must set and use ao_how->for_event (which will be
+ * copied into libxl_event.for_user) or ao_how->for_callback (passed
+ * to the callback) to determine which operation finished, and it must
+ * of course check the rc value for errors.
+ *
+ * *ao_how does not need to remain valid after the initiating function
+ * returns.
+ *
+ * Callbacks may occur on any thread in which the application calls
+ * libxl.
+ */
+
+typedef struct {
+    void (*callback)(libxl_ctx *ctx, int rc, void *for_callback);
+    union {
+        libxl_ev_user for_event; /* used if callback==NULL */
+        void *for_callback; /* passed to callback */
+    } u;
+} libxl_asyncop_how;
+
+
 #define LIBXL_VERSION 0
 
 typedef struct {
tools/libxl/libxl_event.c +183 -0

199 lines not on this page · raw message

tools/libxl/libxl_internal.h +112 -0

142 lines not on this page · raw message

tools/libxl/libxl_types.idl +4 -0
index a6dac79..325bb21 100644
@@ -395,6 +395,7 @@ libxl_event_type = Enumeration("event_type", [
     (1, "DOMAIN_SHUTDOWN"),
     (2, "DOMAIN_DESTROY"),
     (3, "DISK_EJECT"),
+    (4, "OPERATION_COMPLETE"),
     ])
 
 libxl_ev_user = UInt(64)
@@ -418,4 +419,7 @@ libxl_event = Struct("event",[
                                         ("vdev", string),
                                         ("disk", libxl_device_disk),
                                  ])),
+           ("operation_complete", Struct(None, [
+                                        ("rc", integer),
+                                 ])),
            ]))])
Signature · 1 line
1.7.2.5
#16 lore raw

Re: [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure

Quoted 6 lines · Ian Jackson

Provide a new set of machinery for writing public libxl functions which may take a long time. The application gets to decide whether they want the function to be synchronous, or whether they'd prefer to get a callback, or an event, when the operation is complete.

User(s) of this machinery will be introduced in later patch(es).

You've done device removal, do you have a list of other things which should use this? (perhaps with an associated list of people's names...)

Quoted 20 lines
---
 tools/libxl/libxl.h          |   50 ++++++++++++
 tools/libxl/libxl_event.c    |  183 ++++++++++++++++++++++++++++++++++++++++++
 tools/libxl/libxl_internal.h |  112 ++++++++++++++++++++++++++
 tools/libxl/libxl_types.idl  |    4 +
 4 files changed, 349 insertions(+), 0 deletions(-)
tools/libxl/libxl.h +1 -0
index e32881b..416d6e8 100644
@@ -235,8 +235,58 @@ enum {
     ERROR_NOT_READY = -11,
     ERROR_OSEVENT_REG_FAIL = -12,
     ERROR_BUFFERFULL = -13,
+    ERROR_ASYNC_INPROGRESS = -14,
 };
 

tools/libxl/libxl.h enum { · line 250

Quoted 10 lines
tools/libxl/libxl.h +10 -0
+
+/*
+ * Some libxl operations can take a long time.  These functions take a
+ * parameter to control their concurrency:
+ *     libxl_asyncop_how *ao_how
+ *
+ * If ao_how==NULL, the function will be synchronous.
+ *
+ * If ao_how!=NULL, the function will set the operation going, and
+ * if this is successful will return ERROR_ASYNCH_INPROGRESS.

There's an extra H here compared with the actual symbol name (I think the symbol is right).

Is there a possibility that libxl might decide that the operation isn't actually going to take all the long and do things synchronously, returning normal success (e.g. 0)? Is that the reason for the separate return code for this "I did what you asked me" case?

Can we drop the ERROR_ prefix? I know that's inconsistent with the other return codes but those actually are errors.

tools/libxl/libxl.h enum { · line 254

Quoted 4 lines
tools/libxl/libxl.h +4 -0
+ *
+ * If ao_how->callback!=NULL, the callback will be called when the
+ * operation completes.  The same rules as for libxl_event_hooks
+ * apply, including the reentrancy rules and the possibility of

^ (see above/below) -- depending on how these comments end up
relative to each other.

tools/libxl/libxl.h enum {

Quoted 5 lines
tools/libxl/libxl.h +5 -0
+ * "disaster", except that libxl calls ao_how->callback instead of
+ * libxl_event_hooks.event_occurs.
+ *
+ * If ao_how->callback==NULL, a libxl_event will be generated which
+ * can be obtained from libxl_event_wait or libxl_event_check.

Or be delivered via event_occurs?

tools/libxl/libxl.h enum { · line 265

Quoted 7 lines
tools/libxl/libxl.h +6 -0
  The
+ * event will have type OPERATION_COMPLETE (which is not used
+ * elsewhere).
+ *
+ * Note that it is possible for an asynchronous operation which is to
+ * result in a callback to complete during its initiating function
+ * call.  In this case the initating function will return

initiating

tools/libxl/libxl.h enum { · line 266

Quoted 1 line
tools/libxl/libxl.h +1 -0
+ * ERROR_ASYNCH_INPROGRESS, even though by the time it returns the

Another stray H.

Quoted 9 lines
tools/libxl/libxl.h +9 -0
+ * operation is complete and the callback has already happened.
+ *
+ * The application must set and use ao_how->for_event (which will be
+ * copied into libxl_event.for_user) or ao_how->for_callback (passed
+ * to the callback) to determine which operation finished, and it must
+ * of course check the rc value for errors.
+ *
+ * *ao_how does not need to remain valid after the initiating function
+ * returns.

tools/libxl/libxl.h enum { · line 285

Quoted 10 lines
tools/libxl/libxl.h +10 -0
+ *
+ * Callbacks may occur on any thread in which the application calls
+ * libxl.
+ */
+
+typedef struct {
+    void (*callback)(libxl_ctx *ctx, int rc, void *for_callback);
+    union {
+        libxl_ev_user for_event; /* used if callback==NULL */
+        void *for_callback; /* passed to callback */

Why void * for one bit of "closure" but an explicit uint64_t for the other. I nearly commented on the use of uint64_t previously -- void *, or perhaps (u)intptr_t is more normal.

Quoted 76 lines
tools/libxl/libxl.h +4 -0
+    } u;
+} libxl_asyncop_how;
+
+
 #define LIBXL_VERSION 0
 

typedef struct {

tools/libxl/libxl_event.c +50 -0
index 82889f6..b99049a 100644
@@ -771,10 +771,21 @@ static void egc_run_callbacks(libxl__egc *egc)
 {
     EGC_GC;
     libxl_event *ev, *ev_tmp;
+
     LIBXL_TAILQ_FOREACH_SAFE(ev, &egc->occurred_for_callback, link, ev_tmp) {
         LIBXL_TAILQ_REMOVE(&egc->occurred_for_callback, ev, link);
         CTX->event_hooks->event_occurs(CTX->event_hooks_user, ev);
     }
+
+    libxl__ao *ao, *ao_tmp;
+    LIBXL_TAILQ_FOREACH_SAFE(ao, &egc->aos_for_callback,
+                             entry_for_callback, ao_tmp) {
+        LIBXL_TAILQ_REMOVE(&egc->aos_for_callback, ao, entry_for_callback);
+        ao->how.callback(CTX, ao->rc, ao->how.u.for_callback);
+        ao->notified = 1;
+        if (!ao->in_initiator)
+            libxl__ao__destroy(CTX, ao);
+    }
 }
 
 void libxl__egc_cleanup(libxl__egc *egc)
@@ -1061,6 +1072,178 @@ int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r,
     return rc;
 }
 
+
+
+/*
+ * The two possible state flow of an ao:
+ *
+ * Completion before initiator return:
+ *
+ *     Initiator thread                       Possible other threads
+ *
+ *   * ao_create allocates memory and
+ *     initialises the struct
+ *
+ *   * the initiator function does its
+ *     work, setting up various internal
+ *     asynchronous operations -----------> * asynchronous operations
+ *                                            start to take place and
+ *                                            might cause ao completion
+ *                                                |
+ *   * initiator calls ao_complete:               |
+ *     - if synchronous, run event loop           |
+ *       until the ao completes                   |
+ *                              - ao completes on some thread
+ *                              - completing thread releases the lock
+ *                     <--------------'
+ *     - ao_complete takes the lock
+ *     - destroy the ao
+ *
+ *
+ * Completion after initiator return (asynch. only):
+ *
+ *
+ *     Initiator thread                       Possible other threads
+ *
+ *   * ao_create allocates memory and
+ *     initialises the struct
+ *
+ *   * the initiator function does its
+ *     work, setting up various internal
+ *     asynchronous operations -----------> * asynchronous operations

tools/libxl/libxl_event.c int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r, · line 1123

Quoted 10 lines
tools/libxl/libxl_event.c +10 -0
+ *                                            start to take place and
+ *                                            might cause ao completion
+ *                                                |
+ *   * initiator calls ao_complete:               |
+ *     - observes event not net done,             |
+ *     - returns to caller                        |
+ *                                                |
+ *                              - ao completes on some thread
+ *                              - generate the event or call the callback
+ *                              - destroy the ao

Where does ao_inprogress fit into these diagrams?

tools/libxl/libxl_event.c int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r, · line 1126

Quoted 3 lines
tools/libxl/libxl_event.c +3 -0
+ */
+
+void libxl__ao__destroy(libxl_ctx *ctx, libxl__ao *ao) {

CODING_STYLE wants these braces on the next line (a bunch more follow)

Quoted 28 lines
tools/libxl/libxl_event.c +28 -0
+    if (!ao) return;
+    if (ao->poller) libxl__poller_put(ctx, ao->poller);
+    ao->magic = LIBXL__AO_MAGIC_DESTROYED;
+    libxl__free_all(&ao->gc);
+    free(ao);
+}
+
+void libxl__ao_abort(libxl__ao *ao) {
+    AO_GC;
+    assert(ao->magic == LIBXL__AO_MAGIC);
+    assert(ao->in_initiator);
+    assert(!ao->complete);
+    libxl__ao__destroy(CTX, ao);
+}
+
+void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc) {
+    assert(ao->magic == LIBXL__AO_MAGIC);
+    assert(!ao->complete);
+    ao->complete = 1;
+    ao->rc = rc;
+
+    if (ao->poller) {
+        assert(ao->in_initiator);
+        libxl__poller_wakeup(egc, ao->poller);
+    } else if (ao->how.callback) {
+        LIBXL_TAILQ_INSERT_TAIL(&egc->aos_for_callback, ao, entry_for_callback);
+    } else {
+        libxl_event *ev;

tools/libxl/libxl_event.c int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r, · line 1164

Quoted 10 lines
tools/libxl/libxl_event.c +10 -0
+        ev = NEW_EVENT(egc, OPERATION_COMPLETE, ao->domid);
+        if (ev) {
+            ev->for_user = ao->how.u.for_event;
+            ev->u.operation_complete.rc = ao->rc;
+            libxl__event_occurred(egc, ev);
+        }
+        ao->notified = 1;
+    }
+    if (!ao->in_initiator && ao->notified)
+        libxl__ao__destroy(libxl__gc_owner(&egc->gc), ao);

You added a helper for this libxl__gc_owner(&egc..) construct.

tools/libxl/libxl_event.c int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r, · line 1171

Quoted 7 lines
tools/libxl/libxl_event.c +7 -0
+}
+
+libxl__ao *libxl__ao_create(libxl_ctx *ctx, uint32_t domid,
+                            const libxl_asyncop_how *how) {
+    libxl__ao *ao;
+
+    ao = calloc(sizeof(*ao),1);

calloc is actually (nmemb, size). I'm sure it doesn't really matter though.

Quoted 44 lines
tools/libxl/libxl_event.c +44 -0
+    if (!ao) goto out;
+
+    ao->magic = LIBXL__AO_MAGIC;
+    ao->in_initiator = 1;
+    ao->poller = 0;
+    ao->domid = domid;
+    LIBXL_INIT_GC(ao->gc, ctx);
+
+    if (how) {
+        ao->how = *how;
+    } else {
+        ao->poller = libxl__poller_get(ctx);
+        if (!ao->poller) goto out;
+    }
+    return ao;
+
+ out:
+    if (ao) libxl__ao__destroy(ctx, ao);
+    return NULL;
+}
+
+int libxl__ao_inprogress(libxl__ao *ao) {
+    AO_GC;
+    int rc;
+
+    assert(ao->magic == LIBXL__AO_MAGIC);
+    assert(ao->in_initiator);
+
+    if (ao->poller) {
+        /* Caller wants it done synchronously. */
+        /* We use a fresh gc, so that we can free things
+         * each time round the loop. */
+        libxl__egc egc;
+        LIBXL_INIT_EGC(egc,CTX);
+
+        for (;;) {
+            assert(ao->magic == LIBXL__AO_MAGIC);
+
+            if (ao->complete) {
+                rc = ao->rc;
+                ao->notified = 1;
+                break;
+            }
+

tools/libxl/libxl_event.c int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r, · line 1225

Quoted 10 lines
tools/libxl/libxl_event.c +10 -0
+            rc = eventloop_iteration(&egc,ao->poller);
+            if (rc) {
+                /* Oh dear, this is quite unfortunate. */
+                LIBXL__LOG(CTX, LIBXL__LOG_ERROR, "Error waiting for"
+                           " event during long-running operation (rc=%d)", rc);
+                sleep(1);
+                /* It's either this or return ERROR_I_DONT_KNOW_WHETHER
+                 * _THE_THING_YOU_ASKED_FOR_WILL_BE_DONE_LATER_WHEN
+                 * _YOU_DIDNT_EXPECT_IT, since we don't have any kind of
+                 * cancellation ability. */

Does this constitute a "disaster" (in the special hook sense)?

Quoted 28 lines
tools/libxl/libxl_event.c +21 -0
+            }
+
+            CTX_UNLOCK;
+            libxl__egc_cleanup(&egc);
+            CTX_LOCK;
+        }
+    } else {
+        rc = ERROR_ASYNC_INPROGRESS;
+    }
+
+    ao->in_initiator = 0;
+
+    if (ao->notified) {
+        assert(ao->complete);
+        libxl__ao__destroy(CTX,ao);
+    }
+
+    return rc;
+}
+
+
 /*
  * Local variables:
  * mode: C
tools/libxl/libxl_internal.h +0 -0
index 53d2462..594b9fb 100644

[...]

Quoted 5 lines
tools/libxl/libxl_internal.h +1 -0
@@ -1123,6 +1144,97 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);
 
 
 /*
+ * Machinery for asynchronous operations ("ao")

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1157

Quoted 10 lines
tools/libxl/libxl_internal.h +10 -0
+ *
+ * All "slow" functions (includes anything that might block on a
+ * guest or an external script) need to use the asynchronous
+ * operation ("ao") machinery.  The function should take a parameter
+ * const libxl_asyncop_how *ao_how and must start with a call to
+ * AO_INITIATOR_ENTRY.  These functions MAY NOT be called from
+ * outside libxl, because they can cause reentrancy callbacks.
+ *
+ * No functions called internally within libxl should ever return
+ * ERROR_ASYNCH_INPROGRESS.

Aitch.

Quoted 27 lines
tools/libxl/libxl_internal.h +27 -0
+ *
+ * Lifecycle of an ao:
+ *
+ * - Created by libxl__ao_create (or the AO_CREATE convenience macro).
+ *
+ * - After creation, can be used by code which implements
+ *   the operation as follows:
+ *      - the ao's gc, for allocating memory for the lifetime
+ *        of the operation (possibly with the help of the AO_GC
+ *        macro to introduce the gc into scope)
+ *      - the ao itself may be passed about to sub-functions
+ *        so that they can stash it away etc.
+ *      - in particular, the ao pointer must be stashed in some
+ *        per-operation structure which is also passed as a user
+ *        pointer to the internal event generation request routines
+ *        libxl__evgen_FOO, so that at some point a CALLBACK will be
+ *        made when the operation is complete.
+ *
+ * - If initiation is successful, the initiating function needs
+ *   to run libxl__ao_inprogress right before unlocking and
+ *   returning, and return whatever it returns (AO_INPROGRESS macro).
+ *
+ * - If the initiation is unsuccessful, the initiating function must
+ *   call libxl__ao_abort before unlocking and returning whatever
+ *   error code is appropriate (AO_ABORT macro).
+ *
+ * - Later, some callback function, whose callback has been requested

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1194

Quoted 10 lines
tools/libxl/libxl_internal.h +10 -0
+ *   directly or indirectly, should call libxl__ao_complete (with the
+ *   ctx locked, as it will generally already be in any event callback
+ *   function).  This must happen exactly once for each ao (and not if
+ *   the ao has been destroyed, obviously), and it may not happen
+ *   until libxl__ao_inprogress has been called on the ao.
+ *
+ * - Note that during callback functions, two gcs are available:
+ *    - The one in egc, whose lifetime is only this callback
+ *    - The one in ao, whose lifetime is the asynchronous operation
+ *   Usually callback function should use GET_CONTAINING_STRUCT

Now called CONTAINER_OF

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1203

Quoted 9 lines
tools/libxl/libxl_internal.h +9 -0
+ *   to obtain its own structure, containing a pointer to the ao,
+ *   and then use the gc from that ao.
+ */
+
+#define AO_CREATE(ctx, domid, ao_how)                           \
+    libxl__ao *ao = libxl__ao_create(ctx, domid, ao_how);       \
+    if (!ao) return ERROR_NOMEM;                                \
+    AO_GC;                                                      \
+    CTX_LOCK;

Where does the unlock which balances this come from? The only unlock I see in this patch is the temporary drop in libxl__ao_inprogress which is matched by another lock.

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1208

Quoted 5 lines
tools/libxl/libxl_internal.h +5 -0
+
+#define AO_INPROGRESS do{                                       \
+        libxl_ctx *ao__ctx = libxl__gc_owner(&ao->gc);          \
+        int ao__rc = libxl__ao_inprogress(ao);                  \
+        libxl__ctx_lock(ao__ctx); /* gc is now invalid */       \

Is this supposed to be unlock answering my question above? Likewise in ABORT?

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1210

Quoted 2 lines
tools/libxl/libxl_internal.h +2 -0
+        return ao__rc;                                          \
+   }while(0)

Can we arrange for AO_INPROGRESS and AO_ABORT to return the rc? So it would become

	return AO_INPROGRESS;

Is the ({stuff,stuff,stuff,val}) syntax a gcc-ism?

Quoted 6 lines
tools/libxl/libxl_internal.h +6 -0
+
+
+#define AO_ABORT(rc) do{                                        \
+        libxl_ctx *ao__ctx = libxl__gc_owner(&ao->gc);          \
+        assert(rc);                                             \
+        assert(rc != ERROR_ASYNC_INPROGRESS);                   \

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1226

Quoted 10 lines
tools/libxl/libxl_internal.h +10 -0
+        libxl__ao_abort(ao);                                    \
+        libxl__ctx_lock(ao__ctx); /* gc is now invalid */       \
+        return (rc);                                            \
+    }while(0)
+
+#define AO_GC                                   \
+    libxl__gc *const gc = &ao->gc
+
+
+/* All of these MUST be called with the ctx locked.

Except libxl__ao_create? at least according to the implementation of AO_CREATE which takes the lock after.

Quoted 42 lines
tools/libxl/libxl_internal.h +11 -0
+ * libxl__ao_inprogress MUST be called with the ctx locked exactly once. */
+_hidden libxl__ao *libxl__ao_create(libxl_ctx*, uint32_t domid,
+                                    const libxl_asyncop_how*);
+_hidden int libxl__ao_inprogress(libxl__ao *ao);
+_hidden void libxl__ao_abort(libxl__ao *ao);
+_hidden void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc);
+
+/* For use by ao machinery ONLY */
+_hidden void libxl__ao__destroy(libxl_ctx*, libxl__ao *ao);
+
+/*
  * Convenience macros.
  */
 
tools/libxl/libxl_types.idl +4 -1
index a6dac79..325bb21 100644
@@ -395,6 +395,7 @@ libxl_event_type = Enumeration("event_type", [
     (1, "DOMAIN_SHUTDOWN"),
     (2, "DOMAIN_DESTROY"),
     (3, "DISK_EJECT"),
+    (4, "OPERATION_COMPLETE"),
     ])
 
 libxl_ev_user = UInt(64)
@@ -418,4 +419,7 @@ libxl_event = Struct("event",[
                                         ("vdev", string),
                                         ("disk", libxl_device_disk),
                                  ])),
+           ("operation_complete", Struct(None, [
+                                        ("rc", integer),
+                                 ])),
            ]))])
--

1.7.2.5

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xensource.com/xen-devel

#17 lore raw

Re: [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure

Thanks for the thorough review.

Ian Campbell writes ("Re: [Xen-devel] [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure"):

Quoted 2 lines

You've done device removal, do you have a list of other things which should use this? (perhaps with an associated list of people's names...)

No, I don't have such a list, but offhand:
domain creation (bootloader, etc.)
qmp
device attach
domain destruction
bootloader
vncviewer exec (or vncviewer parameter fetching - api should change)
(these may overlap).

Quoted 7 lines
Quoted 4 lines

+ * If ao_how==NULL, the function will be synchronous.
+ *
+ * If ao_how!=NULL, the function will set the operation going, and
+ * if this is successful will return ERROR_ASYNCH_INPROGRESS.

There's an extra H here compared with the actual symbol name (I think the symbol is right).

Fixed everywhere.

Quoted 4 lines

Is there a possibility that libxl might decide that the operation isn't actually going to take all the long and do things synchronously, returning normal success (e.g. 0)? Is that the reason for the separate return code for this "I did what you asked me" case?

No, even if the operation completes quickly, the same exit path is taken. So if you ask for a callback or an event, you get that even if the callback or event happened before your initiating function returns. As I say:

* Note that it is possible for an asynchronous operation which is to
* result in a callback to complete during its initiating function
* call. In this case the initating function will return
* ERROR_ASYNC_INPROGRESS, even though by the time it returns the
* operation is complete and the callback has already happened.

If ao_how is non-NULL then these functions cannot return 0. If it is NULL they cannot return ASYNC_INPROGRESS.

I chose to use a new exit status because it seemed safer but that's a matter of taste and if you prefer I could return 0 for that case.

Quoted 2 lines

Can we drop the ERROR_ prefix? I know that's inconsistent with the other return codes but those actually are errors.

I guess we could but isn't this going to become a proper IDL enum at some point ?

Quoted 7 lines
Quoted 4 lines

+ *
+ * If ao_how->callback!=NULL, the callback will be called when the
+ * operation completes. The same rules as for libxl_event_hooks
+ * apply, including the reentrancy rules and the possibility of

^ (see above/below) -- depending on how these comments end up
relative to each other.

It's actually in a different file. I'll add a cross-reference.

Quoted 7 lines
Quoted 5 lines

+ * "disaster", except that libxl calls ao_how->callback instead of
+ * libxl_event_hooks.event_occurs.
+ *
+ * If ao_how->callback==NULL, a libxl_event will be generated which
+ * can be obtained from libxl_event_wait or libxl_event_check.

Or be delivered via event_occurs?

Yes, in principle, although that would be a silly thing to ask for. Why would you want your ao completions delivered via some central callback function just so that you could split them up again ?

Quoted 3 lines
Quoted 1 line

+ * call. In this case the initating function will return

initiating

Fixed.

Quoted 9 lines

tools/libxl/libxl.h enum { · line 285

Quoted 5 lines
tools/libxl/libxl.h +5 -0
+typedef struct {
+    void (*callback)(libxl_ctx *ctx, int rc, void *for_callback);
+    union {
+        libxl_ev_user for_event; /* used if callback==NULL */
+        void *for_callback; /* passed to callback */

Why void * for one bit of "closure" but an explicit uint64_t for the other. I nearly commented on the use of uint64_t previously -- void *, or perhaps (u)intptr_t is more normal.

The context value in an event needs to be marshallable to a foreign language or a foreign process. So it can't be a pointer. Or at least, it has to be a type which can contain integers as well as pointers, and an integer type is better for that.

The context value for a callback function can be a void* because you don't ever need to "marshal" the "callback", or if you do you can wrap up the context appropriately.

Quoted 1 line
Quoted 1 line

+ * Completion after initiator return (asynch. only):

...

Quoted 9 lines
Quoted 7 lines
+ *   * initiator calls ao_complete:               |
+ *     - observes event not net done,             |
+ *     - returns to caller                        |
+ *                                                |
+ *                              - ao completes on some thread
+ *                              - generate the event or call the callback
+ *                              - destroy the ao

Where does ao_inprogress fit into these diagrams?

There's a mistake in the diagrams: where it says on the left "initiator calls ao_complete" it should read "... ao_inprogress", and likewise for "ao_complete takes the lock". I will fix this.

Quoted 5 lines

Review

Quoted 3 lines

+ */

(quoted diff) +2 -0
+
+void libxl__ao__destroy(libxl_ctx *ctx, libxl__ao *ao) {

CODING_STYLE wants these braces on the next line (a bunch more follow)

Oh yes, will fix.

Quoted 17 lines
Quoted 17 lines
tools/libxl/libxl_event.c +17 -0
+void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc) {
+    assert(ao->magic == LIBXL__AO_MAGIC);
+    assert(!ao->complete);
+    ao->complete = 1;
+    ao->rc = rc;
+
+    if (ao->poller) {
+        assert(ao->in_initiator);
+        libxl__poller_wakeup(egc, ao->poller);
+    } else if (ao->how.callback) {
+        LIBXL_TAILQ_INSERT_TAIL(&egc->aos_for_callback, ao, entry_for_callback);
+    } else {
+        libxl_event *ev;
+        ev = NEW_EVENT(egc, OPERATION_COMPLETE, ao->domid);
+        if (ev) {
+            ev->for_user = ao->how.u.for_event;
+            ev->u.operation_complete.rc = ao->rc;
Quoted 8 lines

tools/libxl/libxl_event.c int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r, · line 1164

Quoted 6 lines
tools/libxl/libxl_event.c +6 -0
+            libxl__event_occurred(egc, ev);
+        }
+        ao->notified = 1;
+    }
+    if (!ao->in_initiator && ao->notified)
+        libxl__ao__destroy(libxl__gc_owner(&egc->gc), ao);

You added a helper for this libxl__gc_owner(&egc..) construct.

You mean EGC_GC and CTX. I don't think that's a good idea here because it obscures exactly what's going on. In particular, there are two gcs here - the ao's and the egc's - and one of them may be about to evaporate.

Quoted 4 lines
Quoted 1 line

+ ao = calloc(sizeof(*ao),1);

calloc is actually (nmemb, size). I'm sure it doesn't really matter though.

I'll fix it though.

Quoted 11 lines

tools/libxl/libxl_event.c int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r, · line 1225

Quoted 10 lines
tools/libxl/libxl_event.c +10 -0
+            rc = eventloop_iteration(&egc,ao->poller);
+            if (rc) {
+                /* Oh dear, this is quite unfortunate. */
+                LIBXL__LOG(CTX, LIBXL__LOG_ERROR, "Error waiting for"
+                           " event during long-running operation (rc=%d)", rc);
+                sleep(1);
+                /* It's either this or return ERROR_I_DONT_KNOW_WHETHER
+                 * _THE_THING_YOU_ASKED_FOR_WILL_BE_DONE_LATER_WHEN
+                 * _YOU_DIDNT_EXPECT_IT, since we don't have any kind of
+                 * cancellation ability. */
Quoted 1 line

Does this constitute a "disaster" (in the special hook sense)?

No, disaster just lets us say that some events may be lost and an ao completion might not be an event. disaster doesn't let us randomly store up ongoing activity and have it happen when not expected. For example, a caller asking a synchronous operation does not expect to get an error code and then have the operation continue in the background anyway.

Quoted 3 lines
Quoted 1 line

+ * Usually callback function should use GET_CONTAINING_STRUCT

Now called CONTAINER_OF

Fixed. Sometimes I wish the compiler could look into comments and spot when I've done this kind of thing.

Quoted 5 lines
Quoted 5 lines

+ * to obtain its own structure, containing a pointer to the ao,
+ * and then use the gc from that ao.
+ */

tools/libxl/libxl_internal.h +2 -0
+
+#define AO_CREATE(ctx, domid, ao_how)                           \
Quoted 8 lines

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1203

Quoted 4 lines
tools/libxl/libxl_internal.h +4 -0
+    libxl__ao *ao = libxl__ao_create(ctx, domid, ao_how);       \
+    if (!ao) return ERROR_NOMEM;                                \
+    AO_GC;                                                      \
+    CTX_LOCK;

Where does the unlock which balances this come from? The only unlock I see in this patch is the temporary drop in libxl__ao_inprogress which is matched by another lock.

The AO_INPROGRESS macro is supposed to unlock it, but locks it again by mistake. Well spotted.

Quoted 7 lines

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1208

Quoted 4 lines
tools/libxl/libxl_internal.h +4 -0
+#define AO_INPROGRESS do{                                       \
+        libxl_ctx *ao__ctx = libxl__gc_owner(&ao->gc);          \
+        int ao__rc = libxl__ao_inprogress(ao);                  \
+        libxl__ctx_lock(ao__ctx); /* gc is now invalid */       \

Is this supposed to be unlock answering my question above? Likewise in ABORT?

Yes. Indeed the comment above agrees:

* - If initiation is successful, the initiating function needs
* to run libxl__ao_inprogress right before unlocking and
* returning, and return whatever it returns (AO_INPROGRESS macro).
*
* - If the initiation is unsuccessful, the initiating function must
* call libxl__ao_abort before unlocking and returning whatever
* error code is appropriate (AO_ABORT macro).

Quoted 6 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+        return ao__rc;                                          \
+   }while(0)

Can we arrange for AO_INPROGRESS and AO_ABORT to return the rc? So it would become

        return AO_INPROGRESS;

That would be possible. I wasn't sure whether to do it like that. Note that AO_CREATE already might return; doing it the way I have it now seems more symmetrical.

But perhaps it would make things clearer to have the return outside the macro.

Quoted 1 line

Is the ({stuff,stuff,stuff,val}) syntax a gcc-ism?

Yes. But I don't think that should stop us if we prefer it.

Quoted 4 lines
Quoted 1 line

+/* All of these MUST be called with the ctx locked.

Except libxl__ao_create? at least according to the implementation of AO_CREATE which takes the lock after.

libxl_ao__create calls libxl__poller_get which needs to be called with the lock held. Well spotted.

Thanks,
Ian.

#18 lore raw

Re: [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure

Quoted 6 lines · Ian Jackson

Thanks for the thorough review.

Ian Campbell writes ("Re: [Xen-devel] [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure"):

Quoted 2 lines

You've done device removal, do you have a list of other things which should use this? (perhaps with an associated list of people's names...)

Quoted 8 lines

No, I don't have such a list, but offhand:
domain creation (bootloader, etc.)
qmp
device attach
domain destruction
bootloader
vncviewer exec (or vncviewer parameter fetching - api should change)
(these may overlap).

Thanks.

Quoted 10 lines
Quoted 4 lines

Is there a possibility that libxl might decide that the operation isn't actually going to take all the long and do things synchronously, returning normal success (e.g. 0)? Is that the reason for the separate return code for this "I did what you asked me" case?

No, even if the operation completes quickly, the same exit path is taken. So if you ask for a callback or an event, you get that even if the callback or event happened before your initiating function returns. As I say:

Quoted 5 lines

* Note that it is possible for an asynchronous operation which is to
* result in a callback to complete during its initiating function
* call. In this case the initating function will return
* ERROR_ASYNC_INPROGRESS, even though by the time it returns the
* operation is complete and the callback has already happened.

Thanks, I think I simply hadn't got to that comment when I wrote the question.

If this is a direct cut-n-paste then presumably there is a patch somewhere where "initiating" is spelled "initating" as above. Hah, I've just spotted where I pointed it out last time and you corrected it below... At least I'm consistent.

Quoted 5 lines

If ao_how is non-NULL then these functions cannot return 0. If it is NULL they cannot return ASYNC_INPROGRESS.

I chose to use a new exit status because it seemed safer but that's a matter of taste and if you prefer I could return 0 for that case.

I'm undecided (plus it seems a bit like bikeshedding). I certainly prefer either 0 or {LIBXL_}ASYNC_IN_PROGRESS to ERROR_ASYNC_IN_PROGRESS though.

Quoted 5 lines
Quoted 2 lines

Can we drop the ERROR_ prefix? I know that's inconsistent with the other return codes but those actually are errors.

I guess we could but isn't this going to become a proper IDL enum at some point ?

At which point it would become LIBXL_ERROR_{FOOS} and LIBXL_ASYNC_IN_PROGRESS?

[...]

Quoted 11 lines
Quoted 7 lines
Quoted 5 lines

+ * "disaster", except that libxl calls ao_how->callback instead of
+ * libxl_event_hooks.event_occurs.
+ *
+ * If ao_how->callback==NULL, a libxl_event will be generated which
+ * can be obtained from libxl_event_wait or libxl_event_check.

Or be delivered via event_occurs?

Yes, in principle, although that would be a silly thing to ask for. Why would you want your ao completions delivered via some central callback function just so that you could split them up again ?

True.

Quoted 13 lines
Quoted 3 lines
Quoted 1 line

+ * call. In this case the initating function will return

initiating

Fixed.

Quoted 6 lines
Quoted 5 lines
tools/libxl/libxl.h +5 -0
+typedef struct {
+    void (*callback)(libxl_ctx *ctx, int rc, void *for_callback);
+    union {
+        libxl_ev_user for_event; /* used if callback==NULL */
+        void *for_callback; /* passed to callback */
Quoted 8 lines
Quoted 3 lines

Why void * for one bit of "closure" but an explicit uint64_t for the other. I nearly commented on the use of uint64_t previously -- void *, or perhaps (u)intptr_t is more normal.

The context value in an event needs to be marshallable to a foreign language or a foreign process. So it can't be a pointer. Or at least, it has to be a type which can contain integers as well as pointers, and an integer type is better for that.

Fair enough.

Quoted 15 lines

The context value for a callback function can be a void* because you don't ever need to "marshal" the "callback", or if you do you can wrap up the context appropriately.

Quoted 1 line
Quoted 1 line

+ * Completion after initiator return (asynch. only):

...

Quoted 8 lines
Quoted 7 lines
+ *   * initiator calls ao_complete:               |
+ *     - observes event not net done,             |
+ *     - returns to caller                        |
+ *                                                |
+ *                              - ao completes on some thread
+ *                              - generate the event or call the callback
+ *                              - destroy the ao
Quoted 5 lines
Quoted 1 line

Where does ao_inprogress fit into these diagrams?

There's a mistake in the diagrams: where it says on the left "initiator calls ao_complete" it should read "... ao_inprogress", and likewise for "ao_complete takes the lock". I will fix this.

Thanks. While rereading with that substitution (and finding that it made sense) I noticed:
+ * * initiator calls ao_complete: |
+ * - observes event not net done, |

You want s/net/yet/.

Quoted 26 lines
Quoted 17 lines
Quoted 17 lines
tools/libxl/libxl_event.c +17 -0
+void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc) {
+    assert(ao->magic == LIBXL__AO_MAGIC);
+    assert(!ao->complete);
+    ao->complete = 1;
+    ao->rc = rc;
+
+    if (ao->poller) {
+        assert(ao->in_initiator);
+        libxl__poller_wakeup(egc, ao->poller);
+    } else if (ao->how.callback) {
+        LIBXL_TAILQ_INSERT_TAIL(&egc->aos_for_callback, ao, entry_for_callback);
+    } else {
+        libxl_event *ev;
+        ev = NEW_EVENT(egc, OPERATION_COMPLETE, ao->domid);
+        if (ev) {
+            ev->for_user = ao->how.u.for_event;
+            ev->u.operation_complete.rc = ao->rc;
Quoted 8 lines

tools/libxl/libxl_event.c int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r, · line 1164

Quoted 6 lines
tools/libxl/libxl_event.c +6 -0
+            libxl__event_occurred(egc, ev);
+        }
+        ao->notified = 1;
+    }
+    if (!ao->in_initiator && ao->notified)
+        libxl__ao__destroy(libxl__gc_owner(&egc->gc), ao);

You added a helper for this libxl__gc_owner(&egc..) construct.

Quoted 4 lines

You mean EGC_GC and CTX. I don't think that's a good idea here because it obscures exactly what's going on. In particular, there are two gcs here - the ao's and the egc's - and one of them may be about to evaporate.

OK.

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
tools/libxl/libxl_event.c +10 -0
+            rc = eventloop_iteration(&egc,ao->poller);
+            if (rc) {
+                /* Oh dear, this is quite unfortunate. */
+                LIBXL__LOG(CTX, LIBXL__LOG_ERROR, "Error waiting for"
+                           " event during long-running operation (rc=%d)", rc);
+                sleep(1);
+                /* It's either this or return ERROR_I_DONT_KNOW_WHETHER
+                 * _THE_THING_YOU_ASKED_FOR_WILL_BE_DONE_LATER_WHEN
+                 * _YOU_DIDNT_EXPECT_IT, since we don't have any kind of
+                 * cancellation ability. */
Quoted 8 lines
Quoted 1 line

Does this constitute a "disaster" (in the special hook sense)?

No, disaster just lets us say that some events may be lost and an ao completion might not be an event. disaster doesn't let us randomly store up ongoing activity and have it happen when not expected. For example, a caller asking a synchronous operation does not expect to get an error code and then have the operation continue in the background anyway.

OK.

Quoted 6 lines
Quoted 3 lines
Quoted 1 line

+ * Usually callback function should use GET_CONTAINING_STRUCT

Now called CONTAINER_OF

Fixed. Sometimes I wish the compiler could look into comments and spot when I've done this kind of thing.

Or read the comments and DWIM so we just need to write the comments ;-)

Quoted 27 lines
Quoted 5 lines
Quoted 5 lines

+ * to obtain its own structure, containing a pointer to the ao,
+ * and then use the gc from that ao.
+ */

tools/libxl/libxl_internal.h +2 -0
+
+#define AO_CREATE(ctx, domid, ao_how)                           \
Quoted 8 lines

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1203

Quoted 4 lines
tools/libxl/libxl_internal.h +4 -0
+    libxl__ao *ao = libxl__ao_create(ctx, domid, ao_how);       \
+    if (!ao) return ERROR_NOMEM;                                \
+    AO_GC;                                                      \
+    CTX_LOCK;

Where does the unlock which balances this come from? The only unlock I see in this patch is the temporary drop in libxl__ao_inprogress which is matched by another lock.

The AO_INPROGRESS macro is supposed to unlock it, but locks it again by mistake. Well spotted.

Quoted 7 lines

tools/libxl/libxl_internal.h _hidden void libxl__egc_cleanup(libxl__egc *egc); · line 1208

Quoted 4 lines
tools/libxl/libxl_internal.h +4 -0
+#define AO_INPROGRESS do{                                       \
+        libxl_ctx *ao__ctx = libxl__gc_owner(&ao->gc);          \
+        int ao__rc = libxl__ao_inprogress(ao);                  \
+        libxl__ctx_lock(ao__ctx); /* gc is now invalid */       \

Is this supposed to be unlock answering my question above? Likewise in ABORT?

Yes. Indeed the comment above agrees:

Quoted 7 lines

* - If initiation is successful, the initiating function needs
* to run libxl__ao_inprogress right before unlocking and
* returning, and return whatever it returns (AO_INPROGRESS macro).
*
* - If the initiation is unsuccessful, the initiating function must
* call libxl__ao_abort before unlocking and returning whatever
* error code is appropriate (AO_ABORT macro).

Right.

I think this highlights my concern about some code paths not being run by the in-xl users...

Quoted 7 lines
Quoted 6 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+        return ao__rc;                                          \
+   }while(0)

Can we arrange for AO_INPROGRESS and AO_ABORT to return the rc? So it would become

        return AO_INPROGRESS;
Quoted 6 lines

That would be possible. I wasn't sure whether to do it like that. Note that AO_CREATE already might return; doing it the way I have it now seems more symmetrical.

But perhaps it would make things clearer to have the return outside the macro.

I thought there was a general preference for that sort of thing, but I suppose it depends on the required macro contortions to make it happen.

Ian.

#19 lore raw

Re: [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure

Ian Campbell writes ("Re: [Xen-devel] [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure"):

Quoted 10 lines · Ian Jackson
Quoted 5 lines

If ao_how is non-NULL then these functions cannot return 0. If it is NULL they cannot return ASYNC_INPROGRESS.

I chose to use a new exit status because it seemed safer but that's a matter of taste and if you prefer I could return 0 for that case.

I'm undecided (plus it seems a bit like bikeshedding). I certainly prefer either 0 or {LIBXL_}ASYNC_IN_PROGRESS to ERROR_ASYNC_IN_PROGRESS though.

OK, I'll rename it.

Quoted 5 lines
Quoted 2 lines

I guess we could but isn't this going to become a proper IDL enum at some point ?

At which point it would become LIBXL_ERROR_{FOOS} and LIBXL_ASYNC_IN_PROGRESS?

I guess so. Or we could rename it LIBXL_RC_...

Quoted 4 lines

+ * * initiator calls ao_complete: |
+ * - observes event not net done, |

You want s/net/yet/.

Yes.

Quoted 8 lines
Quoted 8 lines
Quoted 3 lines

Can we arrange for AO_INPROGRESS and AO_ABORT to return the rc? So it would become

        return AO_INPROGRESS;

That would be possible. I wasn't sure whether to do it like that. Note that AO_CREATE already might return; doing it the way I have it now seems more symmetrical.

Quoted 5 lines
Quoted 2 lines

But perhaps it would make things clearer to have the return outside the macro.

I thought there was a general preference for that sort of thing, but I suppose it depends on the required macro contortions to make it happen.

I think this should be easily doable. I'll sort it out.

Ian.

#20 lore raw

Re: [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure

Ian Jackson writes ("Re: [Xen-devel] [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure"):

Quoted 5 lines

Ian Campbell writes ("Re: [Xen-devel] [PATCH 6/9] libxl: Asynchronous/long-running operation infrastructure"):

Quoted 4 lines · Ian Jackson
Quoted 3 lines

If ao_how is non-NULL then these functions cannot return 0. If it is NULL they cannot return ASYNC_INPROGRESS.

Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

I chose to use a new exit status because it seemed safer but that's a matter of taste and if you prefer I could return 0 for that case.

I'm undecided (plus it seems a bit like bikeshedding). I certainly prefer either 0 or {LIBXL_}ASYNC_IN_PROGRESS to ERROR_ASYNC_IN_PROGRESS though.

OK, I'll rename it.

Having thought about this some more, and particularly about what callers would be likely to want, I decided it would be better to abolish it and return 0 instead.

So I will do that.

Ian.

#21 lore raw

PATCH v7 7/9 libxl: New convenience macro CONTAINER_OF

In reply to Ian Jackson

Provide a convenient and type-safe wrapper which does the correct dance to subtract offsetof. This is very similar to the "container_of" macro in the Linux kernel, but it has an additional feature that instead of the type argument you may also pass an expression of that type; this makes initialising a variable with CONTAINER_OF easier.

---
 tools/libxl/libxl_internal.h |   29 +++++++++++++++++++++++++++++
 1 files changed, 29 insertions(+), 0 deletions(-)
tools/libxl/libxl_internal.h +29 -0
index 594b9fb..213b5f9 100644
@@ -1238,6 +1238,35 @@ _hidden void libxl__ao__destroy(libxl_ctx*, libxl__ao *ao);
  * Convenience macros.
  */
 
+/*
+ * CONTAINER_OF work like this.  Given:
+ *    typedef struct {
+ *      ...
+ *      member_type member_name;
+ *      ...
+ *    } outer_type;
+ *    outer_type outer, *outer_var;
+ *    member_type *inner_ptr = &outer->member_name;
+ *
+ * Then, effectively:
+ *    outer_type *CONTAINER_OF(member_type *inner_ptr,
+ *                             *outer_var, // or type name for outer_type
+ *                             member_name);
+ *
+ * So that:
+ *    CONTAINER_OF(inner_ptr, *outer_var, member_name) == &outer
+ *    CONTAINER_OF(inner_ptr, outer_type, member_name) == &outer
+ */
+#define CONTAINER_OF(inner_ptr, outer, member_name)                     \
+    ({                                                                  \
+        typeof(outer) *container_of_;                                   \
+        container_of_ = (void*)((char*)(inner_ptr) -                    \
+                                offsetof(typeof(outer), member_name));  \
+        (void)(&container_of_->member_name ==                           \
+               (typeof(inner_ptr))0) /* type check */;                  \
+        container_of_;                                                  \
+    })
+
 
 /*
  * All of these assume (or define)
Signature · 1 line
1.7.2.5
Acked-by on v7 7/9
#22 lore raw

Re: [PATCH 7/9] libxl: New convenience macro CONTAINER_OF

Quoted 8 lines · Ian Jackson

Provide a convenient and type-safe wrapper which does the correct dance to subtract offsetof. This is very similar to the "container_of" macro in the Linux kernel, but it has an additional feature that instead of the type argument you may also pass an expression of that type; this makes initialising a variable with CONTAINER_OF easier.

Quoted 44 lines
---
 tools/libxl/libxl_internal.h |   29 +++++++++++++++++++++++++++++
 1 files changed, 29 insertions(+), 0 deletions(-)
tools/libxl/libxl_internal.h +29 -0
index 594b9fb..213b5f9 100644
@@ -1238,6 +1238,35 @@ _hidden void libxl__ao__destroy(libxl_ctx*, libxl__ao *ao);
  * Convenience macros.
  */
 
+/*
+ * CONTAINER_OF work like this.  Given:
+ *    typedef struct {
+ *      ...
+ *      member_type member_name;
+ *      ...
+ *    } outer_type;
+ *    outer_type outer, *outer_var;
+ *    member_type *inner_ptr = &outer->member_name;
+ *
+ * Then, effectively:
+ *    outer_type *CONTAINER_OF(member_type *inner_ptr,
+ *                             *outer_var, // or type name for outer_type
+ *                             member_name);
+ *
+ * So that:
+ *    CONTAINER_OF(inner_ptr, *outer_var, member_name) == &outer
+ *    CONTAINER_OF(inner_ptr, outer_type, member_name) == &outer
+ */
+#define CONTAINER_OF(inner_ptr, outer, member_name)                     \
+    ({                                                                  \
+        typeof(outer) *container_of_;                                   \
+        container_of_ = (void*)((char*)(inner_ptr) -                    \
+                                offsetof(typeof(outer), member_name));  \
+        (void)(&container_of_->member_name ==                           \
+               (typeof(inner_ptr))0) /* type check */;                  \
+        container_of_;                                                  \
+    })
+
 
 /*
  * All of these assume (or define)
#23 lore raw

PATCH v7 8/9 libxl: Introduce libxl__ev_devstate

In reply to Ian Jackson

Provide a new-style asynchronous facility for waiting for device states on xenbus. This will replace libxl__wait_for_device_state, after the callers have been updated in later patches.

---
 tools/libxl/libxl_event.c    |   75 ++++++++++++++++++++++++++++++++++++++++++
 tools/libxl/libxl_internal.h |   41 +++++++++++++++++++++++
 2 files changed, 116 insertions(+), 0 deletions(-)
tools/libxl/libxl_event.c +75 -0
index b99049a..1d271b8 100644
@@ -507,6 +507,81 @@ void libxl__ev_xswatch_deregister(libxl__gc *gc, libxl__ev_xswatch *w)
 }
 
 /*
+ * waiting for device state
+ */
+
+static void devstate_watch_callback(libxl__egc *egc, libxl__ev_xswatch *watch,
+                                const char *watch_path, const char *event_path)
+{
+    EGC_GC;
+    libxl__ev_devstate *ds = CONTAINER_OF(watch, *ds, watch);
+    int rc;
+
+    char *sstate = libxl__xs_read(gc, XBT_NULL, watch_path);
+    if (!sstate) {
+        if (errno == ENOENT) {
+            LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d"
+                       " but it was removed", watch_path, ds->wanted);
+            rc = ERROR_INVAL;
+        } else {
+            LIBXL__LOG_ERRNO(CTX, LIBXL__LOG_ERROR, "backend %s wanted state"
+                             " %d but read failed", watch_path, ds->wanted);
+            rc = ERROR_FAIL;
+        }
+    } else {
+        int got = atoi(sstate);
+        if (got == ds->wanted) {
+            LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d ok",
+                       watch_path, ds->wanted);
+            rc = 0;
+        } else {
+            LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d"
+                       " still waiting state %d", watch_path, ds->wanted, got);
+            return;
+        }
+    }
+    libxl__ev_devstate_cancel(gc, ds);
+    ds->callback(egc, ds, rc);
+}
+
+static void devstate_timeout(libxl__egc *egc, libxl__ev_time *ev,
+                             const struct timeval *requested_abs)
+{
+    EGC_GC;
+    libxl__ev_devstate *ds = CONTAINER_OF(ev, *ds, timeout);
+    LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d "
+               " timed out", ds->watch.path, ds->wanted);
+    libxl__ev_devstate_cancel(gc, ds);
+    ds->callback(egc, ds, ERROR_TIMEDOUT);
+}
+
+int libxl__ev_devstate_wait(libxl__gc *gc, libxl__ev_devstate *ds,
+                            libxl__ev_devstate_callback cb,
+                            const char *state_path, int state, int milliseconds)
+{
+    int rc;
+
+    libxl__ev_time_init(&ds->timeout);
+    libxl__ev_xswatch_init(&ds->watch);
+    ds->wanted = state;
+    ds->callback = cb;
+
+    rc = libxl__ev_time_register_rel(gc, &ds->timeout, devstate_timeout,
+                                     milliseconds);
+    if (rc) goto out;
+
+    rc = libxl__ev_xswatch_register(gc, &ds->watch, devstate_watch_callback,
+                                    state_path);
+    if (rc) goto out;
+
+    return 0;
+
+ out:
+    libxl__ev_devstate_cancel(gc, ds);
+    return rc;
+}
+
+/*
  * osevent poll
  */
 
tools/libxl/libxl_internal.h +41 -0

47 lines not on this page · raw message

Signature · 1 line
1.7.2.5
#24 lore raw

Re: [PATCH 8/9] libxl: Introduce libxl__ev_devstate

Quoted 3 lines · Ian Jackson

Provide a new-style asynchronous facility for waiting for device states on xenbus. This will replace libxl__wait_for_device_state, after the callers have been updated in later patches.

Is event-with-timeout likely to be a useful/common enough pattern to be worth baking into the infrastructure/helpers rather than implementing just for this one event type? (if yes then, "I will refactor for the second user is a valid response").

Quoted 11 lines
---
 tools/libxl/libxl_event.c    |   75 ++++++++++++++++++++++++++++++++++++++++++
 tools/libxl/libxl_internal.h |   41 +++++++++++++++++++++++
 2 files changed, 116 insertions(+), 0 deletions(-)
tools/libxl/libxl_event.c +0 -0
index b99049a..1d271b8 100644
@@ -507,6 +507,81 @@ void libxl__ev_xswatch_deregister(libxl__gc *gc, libxl__ev_xswatch *w)

[...]

tools/libxl/libxl_event.c void libxl__ev_xswatch_deregister(libxl__gc *gc, libxl__ev_xswatch *w) · line 554

Quoted 12 lines
tools/libxl/libxl_event.c +12 -0
+    libxl__ev_devstate_cancel(gc, ds);
+    ds->callback(egc, ds, rc);
+}
+
+static void devstate_timeout(libxl__egc *egc, libxl__ev_time *ev,
+                             const struct timeval *requested_abs)
+{
+    EGC_GC;
+    libxl__ev_devstate *ds = CONTAINER_OF(ev, *ds, timeout);
+    LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d "
+               " timed out", ds->watch.path, ds->wanted);
+    libxl__ev_devstate_cancel(gc, ds);

What prevents racing here with the watch happening? Might the caller see two callbacks?

Quoted 3 lines
tools/libxl/libxl_event.c +3 -0
+    ds->callback(egc, ds, ERROR_TIMEDOUT);
+}
+
#25 lore raw

Re: [PATCH 8/9] libxl: Introduce libxl__ev_devstate

Ian Campbell writes ("Re: [Xen-devel] [PATCH 8/9] libxl: Introduce libxl__ev_devstate"):

Quoted 9 lines · Ian Jackson
Quoted 3 lines

Provide a new-style asynchronous facility for waiting for device states on xenbus. This will replace libxl__wait_for_device_state, after the callers have been updated in later patches.

Is event-with-timeout likely to be a useful/common enough pattern to be worth baking into the infrastructure/helpers rather than implementing just for this one event type? (if yes then, "I will refactor for the second user is a valid response").

I'm not convinced. I thought of this but I think it would result in flabby code - all the libxl__ev_register functions would gain a new timeout parameter (and note that the timeout machinery has both absolute and relative timeouts...)

I think when we have a second user it might be worth seeing if some commonality could be extracted but TBH I doubt it would make the code smaller or simpler.

Quoted 11 lines

tools/libxl/libxl_event.c void libxl__ev_xswatch_deregister(libxl__gc *gc, libxl__ev_xswatch *w) · line 554

Quoted 8 lines
tools/libxl/libxl_event.c +8 -0
+static void devstate_timeout(libxl__egc *egc, libxl__ev_time *ev,
+                             const struct timeval *requested_abs)
+{
+    EGC_GC;
+    libxl__ev_devstate *ds = CONTAINER_OF(ev, *ds, timeout);
+    LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d "
+               " timed out", ds->watch.path, ds->wanted);
+    libxl__ev_devstate_cancel(gc, ds);

What prevents racing here with the watch happening? Might the caller see two callbacks?

  static inline void libxl__ev_devstate_cancel(libxl__gc *gc,
                                               libxl__ev_devstate *ds)
  {
      libxl__ev_time_deregister(gc,&ds->timeout);
      libxl__ev_xswatch_deregister(gc,&ds->watch);
  }

So, no. When the timeout happens, the ev xswatch is deregistered and can thereafter no longer generate callbacks. If there are any xenstore watch events in the pipeline for deregistered ev_xswatch's, they're discarded by watchfd_callback.

Ian.

#26 lore raw

Re: [PATCH 8/9] libxl: Introduce libxl__ev_devstate

Quoted 11 lines · Ian Jackson

Ian Campbell writes ("Re: [Xen-devel] [PATCH 8/9] libxl: Introduce libxl__ev_devstate"):

Quoted 9 lines · Ian Jackson
Quoted 3 lines

Provide a new-style asynchronous facility for waiting for device states on xenbus. This will replace libxl__wait_for_device_state, after the callers have been updated in later patches.

Is event-with-timeout likely to be a useful/common enough pattern to be worth baking into the infrastructure/helpers rather than implementing just for this one event type? (if yes then, "I will refactor for the second user is a valid response").

Quoted 8 lines

I'm not convinced. I thought of this but I think it would result in flabby code - all the libxl__ev_register functions would gain a new timeout parameter (and note that the timeout machinery has both absolute and relative timeouts...)

I think when we have a second user it might be worth seeing if some commonality could be extracted but TBH I doubt it would make the code smaller or simpler.

Right, lets leave it then.

Quoted 19 lines
Quoted 11 lines

tools/libxl/libxl_event.c void libxl__ev_xswatch_deregister(libxl__gc *gc, libxl__ev_xswatch *w) · line 554

Quoted 8 lines
tools/libxl/libxl_event.c +8 -0
+static void devstate_timeout(libxl__egc *egc, libxl__ev_time *ev,
+                             const struct timeval *requested_abs)
+{
+    EGC_GC;
+    libxl__ev_devstate *ds = CONTAINER_OF(ev, *ds, timeout);
+    LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d "
+               " timed out", ds->watch.path, ds->wanted);
+    libxl__ev_devstate_cancel(gc, ds);

What prevents racing here with the watch happening? Might the caller see two callbacks?

  static inline void libxl__ev_devstate_cancel(libxl__gc *gc,
                                               libxl__ev_devstate *ds)
  {
      libxl__ev_time_deregister(gc,&ds->timeout);
      libxl__ev_xswatch_deregister(gc,&ds->watch);
  }
Quoted 4 lines

So, no. When the timeout happens, the ev xswatch is deregistered and can thereafter no longer generate callbacks. If there are any xenstore watch events in the pipeline for deregistered ev_xswatch's, they're discarded by watchfd_callback.

What happens if the watch occurs and is delivered (in a different thread) e.g. just before devstate_timeout calls libxl__ev_devstate_cancel? The watch callback will be delivered but we will unconditionally go on to deliver the cancel callback as well.

#27 lore raw

Re: [PATCH 8/9] libxl: Introduce libxl__ev_devstate

Ian Campbell writes ("Re: [Xen-devel] [PATCH 8/9] libxl: Introduce libxl__ev_devstate"):

Quoted 10 lines · Ian Jackson
Quoted 4 lines

So, no. When the timeout happens, the ev xswatch is deregistered and can thereafter no longer generate callbacks. If there are any xenstore watch events in the pipeline for deregistered ev_xswatch's, they're discarded by watchfd_callback.

What happens if the watch occurs and is delivered (in a different thread) e.g. just before devstate_timeout calls libxl__ev_devstate_cancel? The watch callback will be delivered but we will unconditionally go on to deliver the cancel callback as well.

All of these callback functions are called with the lock held, so there aren't any of these kind of races.

Ian.

#28 lore raw

PATCH v7 9/9 libxl: Convert to asynchronous: device removal

In reply to Ian Jackson

Convert libxl_FOO_device_remove, and the function which does the bulk of the work, libxl__device_remove, to the new async ops scheme.

Adjust all callers.

Also remove libxl__wait_for_device_state which is now obsolete.

---
 tools/libxl/libxl.c          |   60 +++++++++++++--------
 tools/libxl/libxl.h          |   16 ++++--
 tools/libxl/libxl_device.c   |  118 +++++++++++++-----------------------------
 tools/libxl/libxl_internal.h |   30 ++---------
 tools/libxl/xl_cmdimpl.c     |    4 +-
 5 files changed, 93 insertions(+), 135 deletions(-)
tools/libxl/libxl.c +38 -22
index 9890d79..d63da97 100644
@@ -1310,19 +1310,23 @@ out:
 }
 
 int libxl_device_disk_remove(libxl_ctx *ctx, uint32_t domid,
-                             libxl_device_disk *disk)
+                             libxl_device_disk *disk,
+                             const libxl_asyncop_how *ao_how)
 {
-    GC_INIT(ctx);
+    AO_CREATE(ctx, domid, ao_how);
     libxl__device device;
     int rc;
 
     rc = libxl__device_from_disk(gc, domid, disk, &device);
     if (rc != 0) goto out;
 
-    rc = libxl__device_remove(gc, &device, 1);
+    rc = libxl__initiate_device_remove(ao, &device);
+    if (rc) goto out;
+
+    AO_INPROGRESS;
+
 out:
-    GC_FREE;
-    return rc;
+    AO_ABORT(rc);
 }
 
 int libxl_device_disk_destroy(libxl_ctx *ctx, uint32_t domid,
@@ -1536,11 +1540,11 @@ int libxl_cdrom_insert(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk)
 
     ret = 0;
 
-    libxl_device_disk_remove(ctx, domid, disks + i);
+    libxl_device_disk_remove(ctx, domid, disks + i, 0);
     libxl_device_disk_add(ctx, domid, disk);
     stubdomid = libxl_get_stubdom_id(ctx, domid);
     if (stubdomid) {
-        libxl_device_disk_remove(ctx, stubdomid, disks + i);
+        libxl_device_disk_remove(ctx, stubdomid, disks + i, 0);
         libxl_device_disk_add(ctx, stubdomid, disk);
     }
 out:
@@ -1759,19 +1763,23 @@ out:
 }
 
 int libxl_device_nic_remove(libxl_ctx *ctx, uint32_t domid,
-                            libxl_device_nic *nic)
+                            libxl_device_nic *nic,
+                            const libxl_asyncop_how *ao_how)
 {
-    GC_INIT(ctx);
+    AO_CREATE(ctx, domid, ao_how);
     libxl__device device;
     int rc;
 
     rc = libxl__device_from_nic(gc, domid, nic, &device);
     if (rc != 0) goto out;
 
-    rc = libxl__device_remove(gc, &device, 1);
+    rc = libxl__initiate_device_remove(ao, &device);
+    if (rc) goto out;
+
+    AO_INPROGRESS;
+
 out:
-    GC_FREE;
-    return rc;
+    AO_ABORT(rc);
 }
 
 int libxl_device_nic_destroy(libxl_ctx *ctx, uint32_t domid,
@@ -2099,19 +2107,23 @@ out:
 }
 
 int libxl_device_vkb_remove(libxl_ctx *ctx, uint32_t domid,
-                            libxl_device_vkb *vkb)
+                            libxl_device_vkb *vkb,
+                            const libxl_asyncop_how *ao_how)
 {
-    GC_INIT(ctx);
+    AO_CREATE(ctx, domid, ao_how);
     libxl__device device;
     int rc;
 
     rc = libxl__device_from_vkb(gc, domid, vkb, &device);
     if (rc != 0) goto out;
 
-    rc = libxl__device_remove(gc, &device, 1);
+    rc = libxl__initiate_device_remove(ao, &device);
+    if (rc) goto out;
+
+    AO_INPROGRESS;
+
 out:
-    GC_FREE;
-    return rc;
+    AO_ABORT(rc);
 }
 
 int libxl_device_vkb_destroy(libxl_ctx *ctx, uint32_t domid,
@@ -2216,19 +2228,23 @@ out:
 }
 
 int libxl_device_vfb_remove(libxl_ctx *ctx, uint32_t domid,
-                            libxl_device_vfb *vfb)
+                            libxl_device_vfb *vfb,
+                            const libxl_asyncop_how *ao_how)
 {
-    GC_INIT(ctx);
+    AO_CREATE(ctx, domid, ao_how);
     libxl__device device;
     int rc;
 
     rc = libxl__device_from_vfb(gc, domid, vfb, &device);
     if (rc != 0) goto out;
 
-    rc = libxl__device_remove(gc, &device, 1);
+    rc = libxl__initiate_device_remove(ao, &device);
+    if (rc) goto out;
+
+    AO_INPROGRESS;
+
 out:
-    GC_FREE;
-    return rc;
+    AO_ABORT(rc);
 }
 
 int libxl_device_vfb_destroy(libxl_ctx *ctx, uint32_t domid,
tools/libxl/libxl.h +12 -4
index 416d6e8..602bd01 100644
@@ -464,7 +464,9 @@ libxl_vminfo * libxl_list_vm(libxl_ctx *ctx, int *nb_vm);
 /* Disks */
 int libxl_device_disk_init(libxl_ctx *ctx, libxl_device_disk *disk);
 int libxl_device_disk_add(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk);
-int libxl_device_disk_remove(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk);
+int libxl_device_disk_remove(libxl_ctx *ctx, uint32_t domid,
+                             libxl_device_disk *disk,
+                             const libxl_asyncop_how *ao_how);
 int libxl_device_disk_destroy(libxl_ctx *ctx, uint32_t domid,
                               libxl_device_disk *disk);
 
@@ -488,7 +490,9 @@ int libxl_device_disk_local_detach(libxl_ctx *ctx, libxl_device_disk *disk);
 /* Network Interfaces */
 int libxl_device_nic_init(libxl_ctx *ctx, libxl_device_nic *nic);
 int libxl_device_nic_add(libxl_ctx *ctx, uint32_t domid, libxl_device_nic *nic);
-int libxl_device_nic_remove(libxl_ctx *ctx, uint32_t domid, libxl_device_nic *nic);
+int libxl_device_nic_remove(libxl_ctx *ctx, uint32_t domid,
+                            libxl_device_nic *nic,
+                            const libxl_asyncop_how *ao_how);
 int libxl_device_nic_destroy(libxl_ctx *ctx, uint32_t domid, libxl_device_nic *nic);
 
 libxl_device_nic *libxl_device_nic_list(libxl_ctx *ctx, uint32_t domid, int *num);
@@ -498,13 +502,17 @@ int libxl_device_nic_getinfo(libxl_ctx *ctx, uint32_t domid,
 /* Keyboard */
 int libxl_device_vkb_init(libxl_ctx *ctx, libxl_device_vkb *vkb);
 int libxl_device_vkb_add(libxl_ctx *ctx, uint32_t domid, libxl_device_vkb *vkb);
-int libxl_device_vkb_remove(libxl_ctx *ctx, uint32_t domid, libxl_device_vkb *vkb);
+int libxl_device_vkb_remove(libxl_ctx *ctx, uint32_t domid,
+                            libxl_device_vkb *vkb,
+                            const libxl_asyncop_how *ao_how);
 int libxl_device_vkb_destroy(libxl_ctx *ctx, uint32_t domid, libxl_device_vkb *vkb);
 
 /* Framebuffer */
 int libxl_device_vfb_init(libxl_ctx *ctx, libxl_device_vfb *vfb);
 int libxl_device_vfb_add(libxl_ctx *ctx, uint32_t domid, libxl_device_vfb *vfb);
-int libxl_device_vfb_remove(libxl_ctx *ctx, uint32_t domid, libxl_device_vfb *vfb);
+int libxl_device_vfb_remove(libxl_ctx *ctx, uint32_t domid,
+                            libxl_device_vfb *vfb,
+                            const libxl_asyncop_how *ao_how);
 int libxl_device_vfb_destroy(libxl_ctx *ctx, uint32_t domid, libxl_device_vfb *vfb);
 
 /* PCI Passthrough */
tools/libxl/libxl_device.c +36 -82

144 lines not on this page · raw message

tools/libxl/libxl_internal.h +5 -25
index b7f0f54..9920fb9 100644
@@ -653,35 +653,15 @@ _hidden char *libxl__device_backend_path(libxl__gc *gc, libxl__device *device);
 _hidden char *libxl__device_frontend_path(libxl__gc *gc, libxl__device *device);
 _hidden int libxl__parse_backend_path(libxl__gc *gc, const char *path,
                                       libxl__device *dev);
-_hidden int libxl__device_remove(libxl__gc *gc, libxl__device *dev, int wait);
 _hidden int libxl__device_destroy(libxl__gc *gc, libxl__device *dev);
 _hidden int libxl__devices_destroy(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__wait_for_backend(libxl__gc *gc, char *be_path, char *state);
 
-/* Handler for the libxl__wait_for_device_state callback */
-/*
- * libxl__device_state_handler - Handler for the libxl__wait_for_device_state
- * gc: allocation pool
- * l1: array containing the path and token
- * state: string that contains the state of the device
- *
- * Returns 0 on success, and < 0 on error.
- */
-typedef int libxl__device_state_handler(libxl__gc *gc, char **l1, char *state);
-
-/*
- * libxl__wait_for_device_state - waits a given time for a device to
- * reach a given state
- * gc: allocation pool
- * tv: timeval struct containing the maximum time to wait
- * state: state to wait for (check xen/io/xenbus.h)
- * handler: callback function to execute when state is reached
- *
- * Returns 0 on success, and < 0 on error.
- */
-_hidden int libxl__wait_for_device_state(libxl__gc *gc, struct timeval *tv,
-                                         XenbusState state,
-                                         libxl__device_state_handler handler);
+/* Arranges that dev will be removed from its guest.  When
+ * this is done, the ao will be completed.  An error
+ * return from libxl__device_remove means that the ao
+ * will _not_ be completed and the caller must do so. */
+_hidden int libxl__initiate_device_remove(libxl__ao*, libxl__device *dev);
 
 /*
  * libxl__ev_devstate - waits a given time for a device to
tools/libxl/xl_cmdimpl.c +2 -2
index c2b7a1e..659a9e6 100644
@@ -4624,7 +4624,7 @@ int main_networkdetach(int argc, char **argv)
             return 1;
         }
     }
-    if (libxl_device_nic_remove(ctx, domid, &nic)) {
+    if (libxl_device_nic_remove(ctx, domid, &nic, 0)) {
         fprintf(stderr, "libxl_device_nic_del failed.\n");
         return 1;
     }
@@ -4719,7 +4719,7 @@ int main_blockdetach(int argc, char **argv)
         fprintf(stderr, "Error: Device %s not connected.\n", argv[optind+1]);
         return 1;
     }
-    if (libxl_device_disk_remove(ctx, domid, &disk)) {
+    if (libxl_device_disk_remove(ctx, domid, &disk, 0)) {
         fprintf(stderr, "libxl_device_disk_remove failed.\n");
     }
     return 0;
Signature · 1 line
1.7.2.5
#29 lore raw

Re: [PATCH 9/9] libxl: Convert to asynchronous: device removal

Quoted 37 lines · Ian Jackson

Convert libxl_FOO_device_remove, and the function which does the bulk of the work, libxl__device_remove, to the new async ops scheme.

Adjust all callers.

Also remove libxl__wait_for_device_state which is now obsolete.

---
 tools/libxl/libxl.c          |   60 +++++++++++++--------
 tools/libxl/libxl.h          |   16 ++++--
 tools/libxl/libxl_device.c   |  118 +++++++++++++-----------------------------
 tools/libxl/libxl_internal.h |   30 ++---------
 tools/libxl/xl_cmdimpl.c     |    4 +-
 5 files changed, 93 insertions(+), 135 deletions(-)
tools/libxl/libxl.c +3 -3
index 9890d79..d63da97 100644
@@ -1310,19 +1310,23 @@ out:
 }
 
 int libxl_device_disk_remove(libxl_ctx *ctx, uint32_t domid,
-                             libxl_device_disk *disk)
+                             libxl_device_disk *disk,
+                             const libxl_asyncop_how *ao_how)
 {
-    GC_INIT(ctx);
+    AO_CREATE(ctx, domid, ao_how);
     libxl__device device;
     int rc;
 
     rc = libxl__device_from_disk(gc, domid, disk, &device);
     if (rc != 0) goto out;
 
-    rc = libxl__device_remove(gc, &device, 1);

tools/libxl/libxl.c out: · line 1330

Quoted 10 lines
tools/libxl/libxl.c +6 -2
+    rc = libxl__initiate_device_remove(ao, &device);
+    if (rc) goto out;
+
+    AO_INPROGRESS;
+
 out:
-    GC_FREE;
-    return rc;
+    AO_ABORT(rc);
 }

After all the internal complexity the actual usage is refreshingly simple. Phew!

Quoted 6 lines
tools/libxl/libxl.c +0 -0
 int libxl_device_disk_destroy(libxl_ctx *ctx, uint32_t domid,
@@ -1536,11 +1540,11 @@ int libxl_cdrom_insert(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk)
 
     ret = 0;
 

tools/libxl/libxl.c int libxl_cdrom_insert(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk) · line 1550

Quoted 10 lines
tools/libxl/libxl.c +2 -2
-    libxl_device_disk_remove(ctx, domid, disks + i);
+    libxl_device_disk_remove(ctx, domid, disks + i, 0);
     libxl_device_disk_add(ctx, domid, disk);
     stubdomid = libxl_get_stubdom_id(ctx, domid);
     if (stubdomid) {
-        libxl_device_disk_remove(ctx, stubdomid, disks + i);
+        libxl_device_disk_remove(ctx, stubdomid, disks + i, 0);
         libxl_device_disk_add(ctx, stubdomid, disk);
     }
 out:

The async capability here ought to be propagated to the libxl_cdrom_insert interface too. I guess that would mean handling compound asynchronous operations.

...in the fullness of time, of course.

Quoted 13 lines
tools/libxl/libxl.h +0 -0
index 416d6e8..602bd01 100644
tools/libxl/libxl_device.c +0 -0
index 5d05e90..e905133 100644
@@ -357,85 +357,41 @@ int libxl__device_disk_dev_number(const char *virtpath, int *pdisk,
     return -1;
 }
 

[...]

Quoted 11 lines
tools/libxl/libxl_device.c +10 -0
+typedef struct {
+    libxl__ao *ao;
+    libxl__ev_devstate ds;
+} libxl__ao_device_remove;
+
+static void device_remove_cleanup(libxl__gc *gc,
+                                  libxl__ao_device_remove *aorm) {
+    if (!aorm) return;
+    libxl__ev_devstate_cancel(gc, &aorm->ds);
+}

[...]

Quoted 8 lines
tools/libxl/libxl_device.c +6 -0
+static void device_remove_callback(libxl__egc *egc, libxl__ev_devstate *ds,
+                                   int rc) {
+    libxl__ao_device_remove *aorm = CONTAINER_OF(ds, *aorm, ds);
+    libxl__gc *gc = &aorm->ao->gc;
+    libxl__ao_complete(egc, aorm->ao, rc);
+    device_remove_cleanup(gc, aorm);
 }

[...]

tools/libxl/libxl_device.c int libxl__device_disk_dev_number(const char *virtpath, int *pdisk, · line 385

Quoted 6 lines
tools/libxl/libxl_device.c +5 -0
+int libxl__initiate_device_remove(libxl__ao *ao, libxl__device *dev)
 {
+    /* Arranges that dev will be removed from its guest.  When
+     * this is done, the ao will be completed.  An error
+     * return from libxl__device_remove means that the ao
+     * will _not_ be completed and the caller must do so.

Do you mean aborted or cancelled rather than completed here?

Quoted 16 lines
tools/libxl/libxl_device.c +3 -0
+     */
+    AO_GC;
     libxl_ctx *ctx = libxl__gc_owner(gc);
     xs_transaction_t t;
     char *be_path = libxl__device_backend_path(gc, dev);
     char *state_path = libxl__sprintf(gc, "%s/state", be_path);
     char *state = libxl__xs_read(gc, XBT_NULL, state_path);
     int rc = 0;
+    libxl__ao_device_remove *aorm = 0;
 
     if (!state)
         goto out;
@@ -458,23 +414,21 @@ retry_transaction:
         }
     }
 

[...]

Quoted 2 lines
     libxl__device_destroy_tapdisk(gc, be_path);

[...]

Quoted 4 lines
tools/libxl/libxl_device.c +3 -0
+    aorm = libxl__zalloc(gc, sizeof(*aorm));
+    aorm->ao = ao;
+    libxl__ev_devstate_init(&aorm->ds);

[...]

Quoted 17 lines
tools/libxl/libxl_device.c +9 -0
+    rc = libxl__ev_devstate_wait(gc, &aorm->ds, device_remove_callback,
+                                 state_path, XenbusStateClosed,
+                                 LIBXL_DESTROY_TIMEOUT * 1000);
+    if (rc) goto out;
+
+    return 0;
+
+ out:
+    device_remove_cleanup(gc, aorm);
     return rc;
 }
tools/libxl/libxl_internal.h +0 -0
index b7f0f54..9920fb9 100644
@@ -653,35 +653,15 @@ _hidden char *libxl__device_backend_path(libxl__gc *gc, libxl__device *device);

[...]

Quoted 4 lines

+/* Arranges that dev will be removed from its guest. When
+ * this is done, the ao will be completed. An error
+ * return from libxl__device_remove means that the ao
+ * will _not_ be completed and the caller must do so. */

This is the same comment as at the head of the implementation so the same comment re aborting applies. Do we need both comments?

Quoted 9 lines
tools/libxl/libxl_internal.h +1 -0
+_hidden int libxl__initiate_device_remove(libxl__ao*, libxl__device *dev);
 
 /*
  * libxl__ev_devstate - waits a given time for a device to
tools/libxl/xl_cmdimpl.c +0 -0
index c2b7a1e..659a9e6 100644

tools/libxl/xl_cmdimpl.c int main_networkdetach(int argc, char **argv) · line 4630

Quoted 8 lines
tools/libxl/xl_cmdimpl.c +1 -1
@@ -4624,7 +4624,7 @@ int main_networkdetach(int argc, char **argv)
             return 1;
         }
     }
-    if (libxl_device_nic_remove(ctx, domid, &nic)) {
+    if (libxl_device_nic_remove(ctx, domid, &nic, 0)) {
         fprintf(stderr, "libxl_device_nic_del failed.\n");
         return 1;
     }

There aren't actually any examples of a caller using the ao-ness in xl are there?

I know that sync is for the most part ao+wait but I'm a bit concerned that e.g. several of the paths in libxl__ao_complete probably haven't been run and one of the flow-charts added to tools/libxl/libxl_event.c in patch 6/8 has probably never happened either.

IMHO this isn't a blocker for this patch but since xl is, in addition to being a toolstack, a testbed for libxl perhaps one or more "gratuitously asynchronous" calls could be made? Perhaps the libxl_cdrom_insert case would be an interesting one? In particular the case in the create_domain() event loop (e.g. so that the response to a cdrom eject does not block shutdown processing).

Ian.

#30 lore raw

Re: [PATCH 9/9] libxl: Convert to asynchronous: device removal

Ian Campbell writes ("Re: [Xen-devel] [PATCH 9/9] libxl: Convert to asynchronous: device removal"):

Quoted 3 lines · Ian Jackson
Quoted 2 lines

Convert libxl_FOO_device_remove, and the function which does the bulk of the work, libxl__device_remove, to the new async ops scheme.

...

Quoted 3 lines

After all the internal complexity the actual usage is refreshingly simple. Phew!

Yes, that was my main aim ...

Quoted 7 lines

Review int libxl_cdrom_insert(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk) · line 1540

Quoted 3 lines

int libxl_device_disk_destroy(libxl_ctx *ctx, uint32_t domid,

(quoted diff) +0 -0
@@ -1536,11 +1540,11 @@ int libxl_cdrom_insert(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk)
 out:

The async capability here ought to be propagated to the libxl_cdrom_insert interface too. I guess that would mean handling compound asynchronous operations.

Yes. Compound asynchronous operations are already supported by the current scheme: the code which implements them just sets up an appropriate series of callbacks.

Quoted 8 lines

tools/libxl/libxl_device.c int libxl__device_disk_dev_number(const char *virtpath, int *pdisk, · line 385

Quoted 6 lines
tools/libxl/libxl_device.c +5 -0
+int libxl__initiate_device_remove(libxl__ao *ao, libxl__device *dev)
 {
+    /* Arranges that dev will be removed from its guest.  When
+     * this is done, the ao will be completed.  An error
+     * return from libxl__device_remove means that the ao
+     * will _not_ be completed and the caller must do so.

Do you mean aborted or cancelled rather than completed here?

No. An ao cannot be aborted or cancelled, only completed (perhaps with an error code).

I see that the comment is missing "initiate_" from the function name, which I will fix.

Quoted 6 lines
Quoted 5 lines
tools/libxl/libxl_internal.h +0 -0
index b7f0f54..9920fb9 100644
@@ -653,35 +653,15 @@ _hidden char *libxl__device_backend_path(libxl__gc *gc, libxl__device *device);

[...]

Quoted 7 lines
Quoted 4 lines

+/* Arranges that dev will be removed from its guest. When
+ * this is done, the ao will be completed. An error
+ * return from libxl__device_remove means that the ao
+ * will _not_ be completed and the caller must do so. */

This is the same comment as at the head of the implementation so the same comment re aborting applies. Do we need both comments?

No. The comment should be in the header file only. I'll fix this.

Quoted 2 lines
Quoted 2 lines
tools/libxl/libxl_internal.h +1 -1
-    if (libxl_device_nic_remove(ctx, domid, &nic)) {
+    if (libxl_device_nic_remove(ctx, domid, &nic, 0)) {

...

Quoted 3 lines

There aren't actually any examples of a caller using the ao-ness in xl are there?

No.

Quoted 4 lines

I know that sync is for the most part ao+wait but I'm a bit concerned that e.g. several of the paths in libxl__ao_complete probably haven't been run and one of the flow-charts added to tools/libxl/libxl_event.c in patch 6/8 has probably never happened either.

Yes.

Quoted 6 lines

IMHO this isn't a blocker for this patch but since xl is, in addition to being a toolstack, a testbed for libxl perhaps one or more "gratuitously asynchronous" calls could be made? Perhaps the libxl_cdrom_insert case would be an interesting one? In particular the case in the create_domain() event loop (e.g. so that the response to a cdrom eject does not block shutdown processing).

That would be definitely worthwhile. I'll put it (mentally) on my todo list.

Ian.