Skip to contentSkip to conversation

libxl: domain save/restore: run in a separate process

PATCH Superseded Ian Jackson 2 participants 57 messages Jun 8, 2012 – Jun 19, 2012

v3 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v3 cover libxl: domain save/restore: run in a separate process

This is v3 of my series to asyncify save/restore, rebased to current tip, retested, and with all comments addressed.

In the list below "A" indicates a patch which has been acked sufficiently to go in (assuming its dependencies were to go in too). "*" indicates a new patch in v3.

Preparatory work:

01/19 libxc: xc_domain_restore, make toolstack_restore const-correct 02/19 libxl: domain save: rename variables etc.
03/19 libxl: domain restore: reshuffle, preparing for ao 04/19 libxl: domain save: API changes for asynchrony

The meat:

05/19 libxl: domain save/restore: run in a separate process

Some fixups:

A 06/19 libxl: rename libxl_dom:save_helper to physmap_path
07/19 libxl: provide libxl__xs_*_checked and libxl__xs_transaction_* 08/19 libxl: wait for qemu to acknowledge logdirty command

Asyncify writing of qemu save file, too:

09/19 libxl: datacopier: provide "prefix data" facility 10/19 libxl: prepare for asynchronous writing of qemu save file 11/19 libxl: Make libxl__domain_save_device_model asynchronous

Fix gc_opt handling:

* 12/19 libxl: Add a gc to libxl_get_cpu_topology
* 13/19 libxl: Do not pass NULL as gc_opt; introduce NOGC
* 14/19 libxl: Get compiler to warn about gc_opt==NULL

Work on essentially-unrelated bugs:

A 15/19 xl: Handle return value from libxl_domain_suspend correctly A 16/19 libxl: do not leak dms->saved_state
17/19 libxl: do not leak spawned middle children
A 18/19 libxl: do not leak an event struct on ignored ao progress
* 19/19 libxl: DO NOT APPLY enforce prohibition on internal

Thanks,
Ian.

#1 lore raw

PATCH 1/19 libxc: xc_domain_restore, make toolstack_restore const-correct

Update the one provider of this callback, in libxl.

Changes in v3:
* No longer introduce function pointer typedefs into the libxc API.

---
 tools/libxc/xenguest.h  |    2 +-
 tools/libxl/libxl_dom.c |    4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
tools/libxc/xenguest.h +1 -1
index 91d53f7..707e31c 100644
@@ -92,7 +92,7 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iter
 /* callbacks provided by xc_domain_restore */
 struct restore_callbacks {
     /* callback to restore toolstack specific data */
-    int (*toolstack_restore)(uint32_t domid, uint8_t *buf,
+    int (*toolstack_restore)(uint32_t domid, const uint8_t *buf,
             uint32_t size, void* data);
 
     /* to be provided as the last argument to each callback function */
tools/libxl/libxl_dom.c +2 -2
index 10f8c1f..677db1d 100644
@@ -467,13 +467,13 @@ static inline char *restore_helper(libxl__gc *gc, uint32_t domid,
             domid, phys_offset, node);
 }
 
-static int libxl__toolstack_restore(uint32_t domid, uint8_t *buf,
+static int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
         uint32_t size, void *data)
 {
     libxl__gc *gc = (libxl__gc *) data;
     libxl_ctx *ctx = gc->owner;
     int i, ret;
-    uint8_t *ptr = buf;
+    const uint8_t *ptr = buf;
     uint32_t count = 0, version = 0;
     struct libxl__physmap_info* pi;
     char *xs_path;
Signature · 1 line
1.7.2.5
Acked-by on v1 1/19
#2 lore raw

Re: [PATCH 01/19] libxc: xc_domain_restore, make toolstack_restore const-correct

Quoted 3 lines · Ian Jackson

Update the one provider of this callback, in libxl.

Quoted 2 lines

Changes in v3:
* No longer introduce function pointer typedefs into the libxc API.

Thanks!

Quoted 38 lines
---
 tools/libxc/xenguest.h  |    2 +-
 tools/libxl/libxl_dom.c |    4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
tools/libxc/xenguest.h +1 -1
index 91d53f7..707e31c 100644
@@ -92,7 +92,7 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iter
 /* callbacks provided by xc_domain_restore */
 struct restore_callbacks {
     /* callback to restore toolstack specific data */
-    int (*toolstack_restore)(uint32_t domid, uint8_t *buf,
+    int (*toolstack_restore)(uint32_t domid, const uint8_t *buf,
             uint32_t size, void* data);
 
     /* to be provided as the last argument to each callback function */
tools/libxl/libxl_dom.c +2 -2
index 10f8c1f..677db1d 100644
@@ -467,13 +467,13 @@ static inline char *restore_helper(libxl__gc *gc, uint32_t domid,
             domid, phys_offset, node);
 }
 
-static int libxl__toolstack_restore(uint32_t domid, uint8_t *buf,
+static int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
         uint32_t size, void *data)
 {
     libxl__gc *gc = (libxl__gc *) data;
     libxl_ctx *ctx = gc->owner;
     int i, ret;
-    uint8_t *ptr = buf;
+    const uint8_t *ptr = buf;
     uint32_t count = 0, version = 0;
     struct libxl__physmap_info* pi;
     char *xs_path;
#3 lore raw

PATCH 2/19 libxl: domain save: rename variables etc.

In reply to Ian Jackson

Preparatory work for making domain suspend asynchronous:

* Rename struct suspendinfo' to libxl__domain_suspend_state' and move it to libxl_internal.h.

* Rename variables si' to dss'.

* Change the stack-allocated state and callbacks from

    struct suspendinfo si;
    struct save_callbacks callbacks;
    struct restore_callbacks callbacks;
  to
    libxl__domain_suspend_state dss[1];
    struct save_callbacks callbacks[1];
    struct restore_callbacks callbacks[1];

so that it may be referred to as a pointer variable everywhere.

* Rename the variable flags' (in libxl__domain_suspend_state) to xcflags', to help distinguish it from the other `flags' which is passed in from the calling application in libxl_domain_suspend_info. Abolish the local variable in libxl__domain_suspend_common, as it can use the one in the dss.

* Move the prototypes of suspend-related functions in libxl_internal.h to after the definition of the state struct.

* Replace several ctx variables with gc variables and consequently references to ctx with CTX. Change references to dss->gc' in the functional code to simply gc'.

* Use LOG* rather than LIBXL__LOG* in a number of places.

* In libxl__domain_save_device_model use rc' instead of ret'.

* Introduce and use gc' and domid' in
libxl__domain_suspend_common_callback.

* Wrap some long lines.

* Add an extra pair of parens for clarity in a flag test.

* Remove two pointless casts from void* to a struct*.

No functional change whatsoever.

Changes in v3:
* Abolish local variables xcflags' and hvm' in libxl__domain_suspend_common; just use dss->xcflags and dss->hvm instead and hence do not lose some of the changes to xcflags.

Changes in v2:
* Make callbacks into arrays (for pointerisation) too.
* Updated to cope with new remus code.
* Fixed typo in commit message.

---
 tools/libxl/libxl_dom.c      |  261 ++++++++++++++++++++----------------------
 tools/libxl/libxl_internal.h |   30 ++++-
 2 files changed, 151 insertions(+), 140 deletions(-)
tools/libxl/libxl_dom.c +125 -136
index 677db1d..e90030d 100644
@@ -470,7 +470,7 @@ static inline char *restore_helper(libxl__gc *gc, uint32_t domid,
 static int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
         uint32_t size, void *data)
 {
-    libxl__gc *gc = (libxl__gc *) data;
+    libxl__gc *gc = data;
     libxl_ctx *ctx = gc->owner;
     int i, ret;
     const uint8_t *ptr = buf;
@@ -531,7 +531,7 @@ int libxl__domain_restore_common(libxl__gc *gc, uint32_t domid,
     /* read signature */
     int rc;
     int hvm, pae, superpages;
-    struct restore_callbacks callbacks;
+    struct restore_callbacks callbacks[1];
     int no_incr_generationid;
     switch (info->type) {
     case LIBXL_DOMAIN_TYPE_HVM:
@@ -539,8 +539,8 @@ int libxl__domain_restore_common(libxl__gc *gc, uint32_t domid,
         superpages = 1;
         pae = libxl_defbool_val(info->u.hvm.pae);
         no_incr_generationid = !libxl_defbool_val(info->u.hvm.incr_generationid);
-        callbacks.toolstack_restore = libxl__toolstack_restore;
-        callbacks.data = gc;
+        callbacks->toolstack_restore = libxl__toolstack_restore;
+        callbacks->data = gc;
         break;
     case LIBXL_DOMAIN_TYPE_PV:
         hvm = 0;
@@ -556,7 +556,7 @@ int libxl__domain_restore_common(libxl__gc *gc, uint32_t domid,
                            state->store_domid, state->console_port,
                            &state->console_mfn, state->console_domid,
                            hvm, pae, superpages, no_incr_generationid,
-                           &state->vm_generationid_addr, &callbacks);
+                           &state->vm_generationid_addr, callbacks);
     if ( rc ) {
         LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "restoring domain");
         return ERROR_FAIL;
@@ -564,33 +564,23 @@ int libxl__domain_restore_common(libxl__gc *gc, uint32_t domid,
     return 0;
 }
 
-struct suspendinfo {
-    libxl__gc *gc;
-    xc_evtchn *xce; /* event channel handle */
-    int suspend_eventchn;
-    int domid;
-    int hvm;
-    unsigned int flags;
-    int guest_responded;
-    int save_fd; /* Migration stream fd (for Remus) */
-    int interval; /* checkpoint interval (for Remus) */
-};
-
-static int libxl__domain_suspend_common_switch_qemu_logdirty(int domid, unsigned int enable, void *data)
+static int libxl__domain_suspend_common_switch_qemu_logdirty
+                               (int domid, unsigned int enable, void *data)
 {
-    struct suspendinfo *si = data;
-    libxl_ctx *ctx = libxl__gc_owner(si->gc);
+    libxl__domain_suspend_state *dss = data;
+    libxl__gc *gc = dss->gc;
     char *path;
     bool rc;
 
-    path = libxl__sprintf(si->gc, "/local/domain/0/device-model/%u/logdirty/cmd", domid);
+    path = libxl__sprintf(gc,
+                   "/local/domain/0/device-model/%u/logdirty/cmd", domid);
     if (!path)
         return 1;
 
     if (enable)
-        rc = xs_write(ctx->xsh, XBT_NULL, path, "enable", strlen("enable"));
+        rc = xs_write(CTX->xsh, XBT_NULL, path, "enable", strlen("enable"));
     else
-        rc = xs_write(ctx->xsh, XBT_NULL, path, "disable", strlen("disable"));
+        rc = xs_write(CTX->xsh, XBT_NULL, path, "disable", strlen("disable"));
 
     return rc ? 0 : 1;
 }
@@ -645,53 +635,56 @@ int libxl__domain_resume_device_model(libxl__gc *gc, uint32_t domid)
 
 static int libxl__domain_suspend_common_callback(void *data)
 {
-    struct suspendinfo *si = data;
+    libxl__domain_suspend_state *dss = data;
+    libxl__gc *gc = dss->gc;
     unsigned long hvm_s_state = 0, hvm_pvdrv = 0;
     int ret;
     char *state = "suspend";
     int watchdog;
-    libxl_ctx *ctx = libxl__gc_owner(si->gc);
     xs_transaction_t t;
 
-    if (si->hvm) {
-        xc_get_hvm_param(ctx->xch, si->domid, HVM_PARAM_CALLBACK_IRQ, &hvm_pvdrv);
-        xc_get_hvm_param(ctx->xch, si->domid, HVM_PARAM_ACPI_S_STATE, &hvm_s_state);
+    /* Convenience aliases */
+    const uint32_t domid = dss->domid;
+
+    if (dss->hvm) {
+        xc_get_hvm_param(CTX->xch, domid, HVM_PARAM_CALLBACK_IRQ, &hvm_pvdrv);
+        xc_get_hvm_param(CTX->xch, domid, HVM_PARAM_ACPI_S_STATE, &hvm_s_state);
     }
 
-    if ((hvm_s_state == 0) && (si->suspend_eventchn >= 0)) {
-        LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "issuing %s suspend request via event channel",
-                   si->hvm ? "PVHVM" : "PV");
-        ret = xc_evtchn_notify(si->xce, si->suspend_eventchn);
+    if ((hvm_s_state == 0) && (dss->suspend_eventchn >= 0)) {
+        LOG(DEBUG, "issuing %s suspend request via event channel",
+            dss->hvm ? "PVHVM" : "PV");
+        ret = xc_evtchn_notify(dss->xce, dss->suspend_eventchn);
         if (ret < 0) {
-            LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "xc_evtchn_notify failed ret=%d", ret);
+            LOG(ERROR, "xc_evtchn_notify failed ret=%d", ret);
             return 0;
         }
-        ret = xc_await_suspend(ctx->xch, si->xce, si->suspend_eventchn);
+        ret = xc_await_suspend(CTX->xch, dss->xce, dss->suspend_eventchn);
         if (ret < 0) {
-            LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "xc_await_suspend failed ret=%d", ret);
+            LOG(ERROR, "xc_await_suspend failed ret=%d", ret);
             return 0;
         }
-        si->guest_responded = 1;
+        dss->guest_responded = 1;
         goto guest_suspended;
     }
 
-    if (si->hvm && (!hvm_pvdrv || hvm_s_state)) {
-        LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "Calling xc_domain_shutdown on HVM domain");
-        xc_domain_shutdown(ctx->xch, si->domid, SHUTDOWN_suspend);
+    if (dss->hvm && (!hvm_pvdrv || hvm_s_state)) {
+        LOG(DEBUG, "Calling xc_domain_shutdown on HVM domain");
+        xc_domain_shutdown(CTX->xch, domid, SHUTDOWN_suspend);
         /* The guest does not (need to) respond to this sort of request. */
-        si->guest_responded = 1;
+        dss->guest_responded = 1;
     } else {
-        LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "issuing %s suspend request via XenBus control node",
-                   si->hvm ? "PVHVM" : "PV");
+        LOG(DEBUG, "issuing %s suspend request via XenBus control node",
+            dss->hvm ? "PVHVM" : "PV");
 
-        libxl__domain_pvcontrol_write(si->gc, XBT_NULL, si->domid, "suspend");
+        libxl__domain_pvcontrol_write(gc, XBT_NULL, domid, "suspend");
 
-        LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "wait for the guest to acknowledge suspend request");
+        LOG(DEBUG, "wait for the guest to acknowledge suspend request");
         watchdog = 60;
         while (!strcmp(state, "suspend") && watchdog > 0) {
             usleep(100000);
 
-            state = libxl__domain_pvcontrol_read(si->gc, XBT_NULL, si->domid);
+            state = libxl__domain_pvcontrol_read(gc, XBT_NULL, domid);
             if (!state) state = "";
 
             watchdog--;
@@ -707,17 +700,17 @@ static int libxl__domain_suspend_common_callback(void *data)
          * at the last minute.
          */
         if (!strcmp(state, "suspend")) {
-            LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "guest didn't acknowledge suspend, cancelling request");
+            LOG(ERROR, "guest didn't acknowledge suspend, cancelling request");
         retry_transaction:
-            t = xs_transaction_start(ctx->xsh);
+            t = xs_transaction_start(CTX->xsh);
 
-            state = libxl__domain_pvcontrol_read(si->gc, t, si->domid);
+            state = libxl__domain_pvcontrol_read(gc, t, domid);
             if (!state) state = "";
 
             if (!strcmp(state, "suspend"))
-                libxl__domain_pvcontrol_write(si->gc, t, si->domid, "");
+                libxl__domain_pvcontrol_write(gc, t, domid, "");
 
-            if (!xs_transaction_end(ctx->xsh, t, 0))
+            if (!xs_transaction_end(CTX->xsh, t, 0))
                 if (errno == EAGAIN)
                     goto retry_transaction;
 
@@ -729,27 +722,29 @@ static int libxl__domain_suspend_common_callback(void *data)
          * case we lost the race while cancelling and should continue.
          */
         if (!strcmp(state, "suspend")) {
-            LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "guest didn't acknowledge suspend, request cancelled");
+            LOG(ERROR, "guest didn't acknowledge suspend, request cancelled");
             return 0;
         }
 
-        LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "guest acknowledged suspend request");
-        si->guest_responded = 1;
+        LOG(DEBUG, "guest acknowledged suspend request");
+        dss->guest_responded = 1;
     }
 
-    LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "wait for the guest to suspend");
+    LOG(DEBUG, "wait for the guest to suspend");
     watchdog = 60;
     while (watchdog > 0) {
         xc_domaininfo_t info;
 
         usleep(100000);
-        ret = xc_domain_getinfolist(ctx->xch, si->domid, 1, &info);
-        if (ret == 1 && info.domain == si->domid && info.flags & XEN_DOMINF_shutdown) {
+        ret = xc_domain_getinfolist(CTX->xch, domid, 1, &info);
+        if (ret == 1 && info.domain == domid &&
+            (info.flags & XEN_DOMINF_shutdown)) {
             int shutdown_reason;
 
-            shutdown_reason = (info.flags >> XEN_DOMINF_shutdownshift) & XEN_DOMINF_shutdownmask;
+            shutdown_reason = (info.flags >> XEN_DOMINF_shutdownshift)
+                & XEN_DOMINF_shutdownmask;
             if (shutdown_reason == SHUTDOWN_suspend) {
-                LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "guest has suspended");
+                LOG(DEBUG, "guest has suspended");
                 goto guest_suspended;
             }
         }
@@ -757,15 +752,14 @@ static int libxl__domain_suspend_common_callback(void *data)
         watchdog--;
     }
 
-    LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "guest did not suspend");
+    LOG(ERROR, "guest did not suspend");
     return 0;
 
  guest_suspended:
-    if (si->hvm) {
-        ret = libxl__domain_suspend_device_model(si->gc, si->domid);
+    if (dss->hvm) {
+        ret = libxl__domain_suspend_device_model(dss->gc, dss->domid);
         if (ret) {
-            LIBXL__LOG(ctx, LIBXL__LOG_ERROR,
-                       "libxl__domain_suspend_device_model failed ret=%d", ret);
+            LOG(ERROR, "libxl__domain_suspend_device_model failed ret=%d", ret);
             return 0;
         }
     }
@@ -783,9 +777,8 @@ static inline char *save_helper(libxl__gc *gc, uint32_t domid,
 static int libxl__toolstack_save(uint32_t domid, uint8_t **buf,
         uint32_t *len, void *data)
 {
-    struct suspendinfo *si = (struct suspendinfo *) data;
-    libxl__gc *gc = (libxl__gc *) si->gc;
-    libxl_ctx *ctx = gc->owner;
+    libxl__domain_suspend_state *dss = data;
+    libxl__gc *gc = dss->gc;
     int i = 0;
     char *start_addr = NULL, *size = NULL, *phys_offset = NULL, *name = NULL;
     unsigned int num = 0;
@@ -814,21 +807,21 @@ static int libxl__toolstack_save(uint32_t domid, uint8_t **buf,
         char *xs_path;
         phys_offset = entries[i];
         if (phys_offset == NULL) {
-            LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "phys_offset %d is NULL", i);
+            LOG(ERROR, "phys_offset %d is NULL", i);
             return -1;
         }
 
         xs_path = save_helper(gc, domid, phys_offset, "start_addr");
         start_addr = libxl__xs_read(gc, 0, xs_path);
         if (start_addr == NULL) {
-            LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "%s is NULL", xs_path);
+            LOG(ERROR, "%s is NULL", xs_path);
             return -1;
         }
 
         xs_path = save_helper(gc, domid, phys_offset, "size");
         size = libxl__xs_read(gc, 0, xs_path);
         if (size == NULL) {
-            LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "%s is NULL", xs_path);
+            LOG(ERROR, "%s is NULL", xs_path);
             return -1;
         }
 
@@ -864,11 +857,11 @@ static int libxl__remus_domain_suspend_callback(void *data)
 
 static int libxl__remus_domain_resume_callback(void *data)
 {
-    struct suspendinfo *si = data;
-    libxl_ctx *ctx = libxl__gc_owner(si->gc);
+    libxl__domain_suspend_state *dss = data;
+    libxl__gc *gc = dss->gc;
 
     /* Resumes the domain and the device model */
-    if (libxl_domain_resume(ctx, si->domid, /* Fast Suspend */1))
+    if (libxl_domain_resume(CTX, dss->domid, /* Fast Suspend */1))
         return 0;
 
     /* TODO: Deal with disk. Start a new network output buffer */
@@ -877,15 +870,15 @@ static int libxl__remus_domain_resume_callback(void *data)
 
 static int libxl__remus_domain_checkpoint_callback(void *data)
 {
-    struct suspendinfo *si = data;
+    libxl__domain_suspend_state *dss = data;
 
     /* This would go into tailbuf. */
-    if (si->hvm &&
-        libxl__domain_save_device_model(si->gc, si->domid, si->save_fd))
+    if (dss->hvm &&
+        libxl__domain_save_device_model(dss->gc, dss->domid, dss->save_fd))
         return 0;
 
     /* TODO: Wait for disk and memory ack, release network buffer */
-    usleep(si->interval * 1000);
+    usleep(dss->interval * 1000);
     return 1;
 }
 
@@ -894,12 +887,10 @@ int libxl__domain_suspend_common(libxl__gc *gc, uint32_t domid, int fd,
                                  int live, int debug,
                                  const libxl_domain_remus_info *r_info)
 {
-    libxl_ctx *ctx = libxl__gc_owner(gc);
-    int flags;
     int port;
-    struct save_callbacks callbacks;
-    struct suspendinfo si;
-    int hvm, rc = ERROR_FAIL;
+    struct save_callbacks callbacks[1];
+    libxl__domain_suspend_state dss[1];
+    int rc = ERROR_FAIL;
     unsigned long vm_generationid_addr;
 
     switch (type) {
@@ -912,82 +903,81 @@ int libxl__domain_suspend_common(libxl__gc *gc, uint32_t domid, int fd,
         addr = libxl__xs_read(gc, XBT_NULL, path);
 
         vm_generationid_addr = (addr) ? strtoul(addr, NULL, 0) : 0;
-        hvm = 1;
+        dss->hvm = 1;
         break;
     }
     case LIBXL_DOMAIN_TYPE_PV:
         vm_generationid_addr = 0;
-        hvm = 0;
+        dss->hvm = 0;
         break;
     default:
         return ERROR_INVAL;
     }
 
-    memset(&si, 0, sizeof(si));
-    flags = (live) ? XCFLAGS_LIVE : 0
+    dss->xcflags = (live) ? XCFLAGS_LIVE : 0
           | (debug) ? XCFLAGS_DEBUG : 0
-          | (hvm) ? XCFLAGS_HVM : 0;
+          | (dss->hvm) ? XCFLAGS_HVM : 0;
+
+    dss->domid = domid;
+    dss->gc = gc;
+    dss->suspend_eventchn = -1;
+    dss->guest_responded = 0;
 
     if (r_info != NULL) {
-        si.interval = r_info->interval;
+        dss->interval = r_info->interval;
         if (r_info->compression)
-            flags |= XCFLAGS_CHECKPOINT_COMPRESS;
-        si.save_fd = fd;
+            dss->xcflags |= XCFLAGS_CHECKPOINT_COMPRESS;
+        dss->save_fd = fd;
     }
     else
-        si.save_fd = -1;
+        dss->save_fd = -1;
 
-    si.domid = domid;
-    si.flags = flags;
-    si.hvm = hvm;
-    si.gc = gc;
-    si.suspend_eventchn = -1;
-    si.guest_responded = 0;
-
-    si.xce = xc_evtchn_open(NULL, 0);
-    if (si.xce == NULL)
+    dss->xce = xc_evtchn_open(NULL, 0);
+    if (dss->xce == NULL)
         goto out;
     else
     {
-        port = xs_suspend_evtchn_port(si.domid);
+        port = xs_suspend_evtchn_port(dss->domid);
 
         if (port >= 0) {
-            si.suspend_eventchn = xc_suspend_evtchn_init(ctx->xch, si.xce, si.domid, port);
+            dss->suspend_eventchn =
+                xc_suspend_evtchn_init(CTX->xch, dss->xce, dss->domid, port);
 
-            if (si.suspend_eventchn < 0)
-                LIBXL__LOG(ctx, LIBXL__LOG_WARNING, "Suspend event channel initialization failed");
+            if (dss->suspend_eventchn < 0)
+                LOG(WARN, "Suspend event channel initialization failed");
         }
     }
 
-    memset(&callbacks, 0, sizeof(callbacks));
+    memset(callbacks, 0, sizeof(*callbacks));
     if (r_info != NULL) {
-        callbacks.suspend = libxl__remus_domain_suspend_callback;
-        callbacks.postcopy = libxl__remus_domain_resume_callback;
-        callbacks.checkpoint = libxl__remus_domain_checkpoint_callback;
+        callbacks->suspend = libxl__remus_domain_suspend_callback;
+        callbacks->postcopy = libxl__remus_domain_resume_callback;
+        callbacks->checkpoint = libxl__remus_domain_checkpoint_callback;
     } else
-        callbacks.suspend = libxl__domain_suspend_common_callback;
+        callbacks->suspend = libxl__domain_suspend_common_callback;
 
-    callbacks.switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
-    callbacks.toolstack_save = libxl__toolstack_save;
-    callbacks.data = &si;
+    callbacks->switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
+    callbacks->toolstack_save = libxl__toolstack_save;
+    callbacks->data = dss;
 
-    rc = xc_domain_save(ctx->xch, fd, domid, 0, 0, flags, &callbacks,
-                        hvm, vm_generationid_addr);
+    rc = xc_domain_save(CTX->xch, fd, domid, 0, 0, dss->xcflags, callbacks,
+                        dss->hvm, vm_generationid_addr);
     if ( rc ) {
-        LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "saving domain: %s",
-                         si.guest_responded ?
+        LOGE(ERROR, "saving domain: %s",
+                         dss->guest_responded ?
                          "domain responded to suspend request" :
                          "domain did not respond to suspend request");
-        if ( !si.guest_responded )
+        if ( !dss->guest_responded )
             rc = ERROR_GUEST_TIMEDOUT;
         else
             rc = ERROR_FAIL;
     }
 
-    if (si.suspend_eventchn > 0)
-        xc_suspend_evtchn_release(ctx->xch, si.xce, domid, si.suspend_eventchn);
-    if (si.xce != NULL)
-        xc_evtchn_close(si.xce);
+    if (dss->suspend_eventchn > 0)
+        xc_suspend_evtchn_release(CTX->xch, dss->xce, domid,
+                                  dss->suspend_eventchn);
+    if (dss->xce != NULL)
+        xc_evtchn_close(dss->xce);
 
 out:
     return rc;
@@ -995,8 +985,7 @@ out:
 
 int libxl__domain_save_device_model(libxl__gc *gc, uint32_t domid, int fd)
 {
-    libxl_ctx *ctx = libxl__gc_owner(gc);
-    int ret, fd2 = -1, c;
+    int rc, fd2 = -1, c;
     char buf[1024];
     const char *filename = libxl__device_model_savefile(gc, domid);
     struct stat st;
@@ -1004,46 +993,46 @@ int libxl__domain_save_device_model(libxl__gc *gc, uint32_t domid, int fd)
 
     if (stat(filename, &st) < 0)
     {
-        LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "Unable to stat qemu save file\n");
-        ret = ERROR_FAIL;
+        LOG(ERROR, "Unable to stat qemu save file\n");
+        rc = ERROR_FAIL;
         goto out;
     }
 
     qemu_state_len = st.st_size;
-    LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "Qemu state is %d bytes\n", qemu_state_len);
+    LOG(DEBUG, "Qemu state is %d bytes\n", qemu_state_len);
 
-    ret = libxl_write_exactly(ctx, fd, QEMU_SIGNATURE, strlen(QEMU_SIGNATURE),
+    rc = libxl_write_exactly(CTX, fd, QEMU_SIGNATURE, strlen(QEMU_SIGNATURE),
                               "saved-state file", "qemu signature");
-    if (ret)
+    if (rc)
         goto out;
 
-    ret = libxl_write_exactly(ctx, fd, &qemu_state_len, sizeof(qemu_state_len),
+    rc = libxl_write_exactly(CTX, fd, &qemu_state_len, sizeof(qemu_state_len),
                             "saved-state file", "saved-state length");
-    if (ret)
+    if (rc)
         goto out;
 
     fd2 = open(filename, O_RDONLY);
     if (fd2 < 0) {
-        LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "Unable to open qemu save file\n");
+        LOGE(ERROR, "Unable to open qemu save file\n");
         goto out;
     }
     while ((c = read(fd2, buf, sizeof(buf))) != 0) {
         if (c < 0) {
             if (errno == EINTR)
                 continue;
-            ret = errno;
+            rc = errno;
             goto out;
         }
-        ret = libxl_write_exactly(
-            ctx, fd, buf, c, "saved-state file", "qemu state");
-        if (ret)
+        rc = libxl_write_exactly(
+            CTX, fd, buf, c, "saved-state file", "qemu state");
+        if (rc)
             goto out;
     }
-    ret = 0;
+    rc = 0;
 out:
     if (fd2 >= 0) close(fd2);
     unlink(filename);
-    return ret;
+    return rc;
 }
 
 char *libxl__uuid2string(libxl__gc *gc, const libxl_uuid uuid)
tools/libxl/libxl_internal.h +26 -4
index fa4c08f..f22bf94 100644
@@ -786,10 +786,6 @@ _hidden int libxl__domain_restore_common(libxl__gc *gc, uint32_t domid,
                                          libxl_domain_build_info *info,
                                          libxl__domain_build_state *state,
                                          int fd);
-_hidden int libxl__domain_suspend_common(libxl__gc *gc, uint32_t domid, int fd,
-                                         libxl_domain_type type,
-                                         int live, int debug,
-                                         const libxl_domain_remus_info *r_info);
 _hidden const char *libxl__device_model_savefile(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__domain_suspend_device_model(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__domain_resume_device_model(libxl__gc *gc, uint32_t domid);
@@ -1778,6 +1774,23 @@ _hidden void libxl__datacopier_kill(libxl__datacopier_state *dc);
 _hidden int libxl__datacopier_start(libxl__datacopier_state *dc);
 
 
+/*----- Domain suspend (save) state structure -----*/
+
+typedef struct libxl__domain_suspend_state libxl__domain_suspend_state;
+
+struct libxl__domain_suspend_state {
+    libxl__gc *gc;
+    xc_evtchn *xce; /* event channel handle */
+    int suspend_eventchn;
+    int domid;
+    int hvm;
+    unsigned int xcflags;
+    int guest_responded;
+    int save_fd; /* Migration stream fd (for Remus) */
+    int interval; /* checkpoint interval (for Remus) */
+};
+
+
 /*----- openpty -----*/
 
 /*
@@ -1888,6 +1901,15 @@ struct libxl__domain_create_state {
          * for the non-stubdom device model. */
 };
 
+/*----- Domain suspend (save) functions -----*/
+
+_hidden int libxl__domain_suspend_common(libxl__gc *gc, uint32_t domid, int fd,
+                                         libxl_domain_type type,
+                                         int live, int debug,
+                                         const libxl_domain_remus_info *r_info);
+
+
+
 /*
  * Convenience macros.
  */
Signature · 1 line
1.7.2.5
Acked-by on v1 2/19
#4 lore raw

Re: [PATCH 02/19] libxl: domain save: rename variables etc.

Quoted 1 line · Ian Jackson

Preparatory work for making domain suspend asynchronous:

[...]

Quoted 1 line

No functional change whatsoever.

Given that and a quick skim of the changes:

Although in general I find it easier to review patches which contain only one particular class of "mostly automatic" cleanup (e.g. renames separate from "pointerization" separate from local variable removal etc).

Ian.

#5 lore raw

Re: [PATCH 02/19] libxl: domain save: rename variables etc.

Ian Campbell writes ("Re: [Xen-devel] [PATCH 02/19] libxl: domain save: rename variables etc."):

Quoted 8 lines · Ian Jackson
Quoted 1 line

Preparatory work for making domain suspend asynchronous:

[...]

Quoted 1 line

No functional change whatsoever.

Given that and a quick skim of the changes:

Thanks.

Quoted 4 lines

Although in general I find it easier to review patches which contain only one particular class of "mostly automatic" cleanup (e.g. renames separate from "pointerization" separate from local variable removal etc).

OK, I will split it up more next time I do something like this. I thought I already had rather too many pre- and post-patches, but I'm happy to make more of them in future.

Thanks,
Ian.

#6 lore raw

PATCH 3/19 libxl: domain restore: reshuffle, preparing for ao

In reply to Ian Jackson

We are going to arrange that libxl, instead of calling xc_domain_restore, calls a stub function which forks and execs a helper program, so that restore can be asynchronous rather than blocking the whole toolstack.

This stub function will be called libxl__xc_domain_restore.

However, its prospective call site is unsuitable for a function which needs to make a callback, and is buried in two nested single-call-site functions which are logically part of the domain creation procedure.

So we first abolish those single-call-site functions, integrate their contents into domain creation in their proper temporal order, and break out libxl__xc_domain_restore ready for its reimplementation.

No functional change - just the following reorganisation:

* Abolish libxl__domain_restore_common, as it had only one caller. Move its contents into (what was) domain_restore.

* There is a new stage function domcreate_rebuild_done containing what used to be the bulk of domcreate_bootloader_done, since domcreate_bootloader_done now simply starts the restore (or does the rebuild) and arranges to call the next stage.

* Move the contents of domain_restore into its correct place in the domain creation sequence. We put it inside domcreate_bootloader_done, which now either calls libxl__xc_domain_restore which will call the new function domcreate_rebuild_done.

* Various general-purpose local variables (`i' etc.) and convenience alias variables need to be shuffled about accordingly.

* Consequently libxl__toolstack_restore needs to gain external linkage as it is now in a different file to its user.

* Move the xc_domain_save callbacks struct from the stack into libxl__domain_create_state.

In general the moved code remains almost identical. Two returns in what used to be libxl__domain_restore_common have been changed to set the return value and "goto out", and the call sites for the abolished and new functions have been adjusted.

Changes in v2:
* Also move the save callbacks

---
 tools/libxl/Makefile             |    1 +
 tools/libxl/libxl_create.c       |  244 +++++++++++++++++++++++--------------
 tools/libxl/libxl_dom.c          |   45 +-------
 tools/libxl/libxl_internal.h     |   19 +++-
 tools/libxl/libxl_save_callout.c |   37 ++++++
 5 files changed, 206 insertions(+), 140 deletions(-)
 create mode 100644 tools/libxl/libxl_save_callout.c
tools/libxl/Makefile +1 -0
index e7d5cc2..1d8b80a 100644
@@ -67,6 +67,7 @@ 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_aoutils.o \
+			libxl_save_callout.o \
 			libxl_qmp.o libxl_event.o libxl_fork.o $(LIBXL_OBJS-y)
 LIBXL_OBJS += _libxl_types.o libxl_flask.o _libxl_types_internal.o
 
tools/libxl/libxl_create.c +152 -92

290 lines not on this page · raw message

tools/libxl/libxl_dom.c +1 -44

63 lines not on this page · raw message

tools/libxl/libxl_internal.h +15 -4
index f22bf94..28478ea 100644
@@ -46,6 +46,7 @@
 
 #include <xenstore.h>
 #include <xenctrl.h>
+#include <xenguest.h>
 
 #include "xentoollog.h"
 
@@ -782,10 +783,8 @@ _hidden int libxl__domain_rename(libxl__gc *gc, uint32_t domid,
                                  const char *old_name, const char *new_name,
                                  xs_transaction_t trans);
 
-_hidden int libxl__domain_restore_common(libxl__gc *gc, uint32_t domid,
-                                         libxl_domain_build_info *info,
-                                         libxl__domain_build_state *state,
-                                         int fd);
+_hidden int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
+                                     uint32_t size, void *data);
 _hidden const char *libxl__device_model_savefile(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__domain_suspend_device_model(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__domain_resume_device_model(libxl__gc *gc, uint32_t domid);
@@ -1899,6 +1898,7 @@ struct libxl__domain_create_state {
     libxl__stub_dm_spawn_state dmss;
         /* If we're not doing stubdom, we use only dmss.dm,
          * for the non-stubdom device model. */
+    struct restore_callbacks callbacks;
 };
 
 /*----- Domain suspend (save) functions -----*/
@@ -1908,6 +1908,17 @@ _hidden int libxl__domain_suspend_common(libxl__gc *gc, uint32_t domid, int fd,
                                          int live, int debug,
                                          const libxl_domain_remus_info *r_info);
 
+/* calls libxl__xc_domain_restore_done when done */
+_hidden void libxl__xc_domain_restore(libxl__egc *egc,
+                                      libxl__domain_create_state *dcs,
+                                      int hvm, int pae, int superpages,
+                                      int no_incr_generationid);
+/* If rc==0 then retval is the return value from xc_domain_save
+ * and errnoval is the errno value it provided.
+ * If rc!=0, retval and errnoval are undefined. */
+_hidden void libxl__xc_domain_restore_done(libxl__egc *egc,
+                                           libxl__domain_create_state *dcs,
+                                           int rc, int retval, int errnoval);
 
 
 /*
tools/libxl/libxl_save_callout.c new file +37 -0
new file mode 100644
index 0000000..2f8db9f
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2012      Citrix Ltd.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; version 2.1 only. with the special
+ * exception on linking described in file LICENSE.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ */
+
+#include "libxl_osdeps.h"
+
+#include "libxl_internal.h"
+
+void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs,
+                              int hvm, int pae, int superpages,
+                              int no_incr_generationid)
+{
+    STATE_AO_GC(dcs->ao);
+
+    /* Convenience aliases */
+    const uint32_t domid = dcs->guest_domid;
+    const int restore_fd = dcs->restore_fd;
+    libxl__domain_build_state *const state = &dcs->build_state;
+
+    int r = xc_domain_restore(CTX->xch, restore_fd, domid,
+                              state->store_port, &state->store_mfn,
+                              state->store_domid, state->console_port,
+                              &state->console_mfn, state->console_domid,
+                              hvm, pae, superpages, no_incr_generationid,
+                              &state->vm_generationid_addr, &dcs->callbacks);
+    libxl__xc_domain_restore_done(egc, dcs, 0, r, errno);
+}
Signature · 1 line
1.7.2.5
Acked-by on v1 3/19
#7 lore raw

Re: [PATCH 03/19] libxl: domain restore: reshuffle, preparing for ao

Quoted 20 lines · Ian Jackson

We are going to arrange that libxl, instead of calling xc_domain_restore, calls a stub function which forks and execs a helper program, so that restore can be asynchronous rather than blocking the whole toolstack.

This stub function will be called libxl__xc_domain_restore.

However, its prospective call site is unsuitable for a function which needs to make a callback, and is buried in two nested single-call-site functions which are logically part of the domain creation procedure.

So we first abolish those single-call-site functions, integrate their contents into domain creation in their proper temporal order, and break out libxl__xc_domain_restore ready for its reimplementation.

No functional change - just the following reorganisation:

* Abolish libxl__domain_restore_common, as it had only one caller. Move its contents into (what was) domain_restore.

Quoted 8 lines

* There is a new stage function domcreate_rebuild_done containing what used to be the bulk of domcreate_bootloader_done, since domcreate_bootloader_done now simply starts the restore (or does the rebuild) and arranges to call the next stage.

* Move the contents of domain_restore into its correct place in the domain creation sequence. We put it inside domcreate_bootloader_done, which now either calls

"either" but no "or"? I suppose the or case is call domcreate_rebuild_done directly?

Quoted 12 lines

libxl__xc_domain_restore which will call the new function domcreate_rebuild_done.

* Various general-purpose local variables (`i' etc.) and convenience alias variables need to be shuffled about accordingly.

* Consequently libxl__toolstack_restore needs to gain external linkage as it is now in a different file to its user.

* Move the xc_domain_save callbacks struct from the stack into libxl__domain_create_state.

Quoted 6 lines

In general the moved code remains almost identical. Two returns in what used to be libxl__domain_restore_common have been changed to set the return value and "goto out", and the call sites for the abolished and new functions have been adjusted.

I confirmed at a high level that the same blocks of code exist and are called in the same overall order, but I didn't do a line by line comparison of the blocks in question, assuming they really are mostly motion and adjustments for the new context.

Quoted 495 lines

Changes in v2:
* Also move the save callbacks

---
 tools/libxl/Makefile             |    1 +
 tools/libxl/libxl_create.c       |  244 +++++++++++++++++++++++--------------
 tools/libxl/libxl_dom.c          |   45 +-------
 tools/libxl/libxl_internal.h     |   19 +++-
 tools/libxl/libxl_save_callout.c |   37 ++++++
 5 files changed, 206 insertions(+), 140 deletions(-)
 create mode 100644 tools/libxl/libxl_save_callout.c
tools/libxl/Makefile +1 -0
index e7d5cc2..1d8b80a 100644
@@ -67,6 +67,7 @@ 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_aoutils.o \
+                       libxl_save_callout.o \
                        libxl_qmp.o libxl_event.o libxl_fork.o $(LIBXL_OBJS-y)
 LIBXL_OBJS += _libxl_types.o libxl_flask.o _libxl_types_internal.o
 
tools/libxl/libxl_create.c +152 -92
index 4456ae8..4439367 100644
@@ -21,7 +21,6 @@
 #include "libxl_arch.h"
 
 #include <xc_dom.h>
-#include <xenguest.h>
 
 void libxl_domain_config_init(libxl_domain_config *d_config)
 {
@@ -317,89 +316,6 @@ out:
     return ret;
 }
 
-static int domain_restore(libxl__gc *gc, libxl_domain_build_info *info,
-                          uint32_t domid, int fd,
-                          libxl__domain_build_state *state)
-{
-    libxl_ctx *ctx = libxl__gc_owner(gc);
-    char **vments = NULL, **localents = NULL;
-    struct timeval start_time;
-    int i, ret, esave, flags;
-
-    ret = libxl__build_pre(gc, domid, info, state);
-    if (ret)
-        goto out;
-
-    ret = libxl__domain_restore_common(gc, domid, info, state, fd);
-    if (ret)
-        goto out;
-
-    gettimeofday(&start_time, NULL);
-
-    switch (info->type) {
-    case LIBXL_DOMAIN_TYPE_HVM:
-        vments = libxl__calloc(gc, 7, sizeof(char *));
-        vments[0] = "rtc/timeoffset";
-        vments[1] = (info->u.hvm.timeoffset) ? info->u.hvm.timeoffset : "";
-        vments[2] = "image/ostype";
-        vments[3] = "hvm";
-        vments[4] = "start_time";
-        vments[5] = libxl__sprintf(gc, "%lu.%02d", start_time.tv_sec,(int)start_time.tv_usec/10000);
-        break;
-    case LIBXL_DOMAIN_TYPE_PV:
-        vments = libxl__calloc(gc, 11, sizeof(char *));
-        i = 0;
-        vments[i++] = "image/ostype";
-        vments[i++] = "linux";
-        vments[i++] = "image/kernel";
-        vments[i++] = (char *) state->pv_kernel.path;
-        vments[i++] = "start_time";
-        vments[i++] = libxl__sprintf(gc, "%lu.%02d", start_time.tv_sec,(int)start_time.tv_usec/10000);
-        if (state->pv_ramdisk.path) {
-            vments[i++] = "image/ramdisk";
-            vments[i++] = (char *) state->pv_ramdisk.path;
-        }
-        if (state->pv_cmdline) {
-            vments[i++] = "image/cmdline";
-            vments[i++] = (char *) state->pv_cmdline;
-        }
-        break;
-    default:
-        ret = ERROR_INVAL;
-        goto out;
-    }
-    ret = libxl__build_post(gc, domid, info, state, vments, localents);
-    if (ret)
-        goto out;
-
-    if (info->type == LIBXL_DOMAIN_TYPE_HVM) {
-        ret = asprintf(&state->saved_state,
-                       XC_DEVICE_MODEL_RESTORE_FILE".%d", domid);
-        ret = (ret < 0) ? ERROR_FAIL : 0;
-    }
-
-out:
-    if (info->type == LIBXL_DOMAIN_TYPE_PV) {
-        libxl__file_reference_unmap(&state->pv_kernel);
-        libxl__file_reference_unmap(&state->pv_ramdisk);
-    }
-
-    esave = errno;
-
-    flags = fcntl(fd, F_GETFL);
-    if (flags == -1) {
-        LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "unable to get flags on restore fd");
-    } else {
-        flags &= ~O_NONBLOCK;
-        if (fcntl(fd, F_SETFL, flags) == -1)
-            LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "unable to put restore fd"
-                         " back to blocking mode");
-    }
-
-    errno = esave;
-    return ret;
-}
-
 int libxl__domain_make(libxl__gc *gc, libxl_domain_create_info *info,
                        uint32_t *domid)
 {
@@ -580,10 +496,13 @@ static void domcreate_bootloader_console_available(libxl__egc *egc,
 static void domcreate_bootloader_done(libxl__egc *egc,
                                       libxl__bootloader_state *bl,
                                       int rc);
-
 static void domcreate_console_available(libxl__egc *egc,
                                         libxl__domain_create_state *dcs);
 
+static void domcreate_rebuild_done(libxl__egc *egc,
+                                   libxl__domain_create_state *dcs,
+                                   int ret);
+
 /* Our own function to clean up and call the user's callback.
  * The final call in the sequence. */
 static void domcreate_complete(libxl__egc *egc,
@@ -671,20 +590,20 @@ static void domcreate_console_available(libxl__egc *egc,
 
 static void domcreate_bootloader_done(libxl__egc *egc,
                                       libxl__bootloader_state *bl,
-                                      int ret)
+                                      int rc)
 {
     libxl__domain_create_state *dcs = CONTAINER_OF(bl, *dcs, bl);
     STATE_AO_GC(bl->ao);
-    int i;
 
     /* convenience aliases */
     const uint32_t domid = dcs->guest_domid;
     libxl_domain_config *const d_config = dcs->guest_config;
+    libxl_domain_build_info *const info = &d_config->b_info;
     const int restore_fd = dcs->restore_fd;
     libxl__domain_build_state *const state = &dcs->build_state;
-    libxl_ctx *const ctx = CTX;
+    struct restore_callbacks *const callbacks = &dcs->callbacks;
 
-    if (ret) goto error_out;
+    if (rc) domcreate_rebuild_done(egc, dcs, rc);
 
     /* consume bootloader outputs. state->pv_{kernel,ramdisk} have
      * been initialised by the bootloader already.
@@ -700,12 +619,153 @@ static void domcreate_bootloader_done(libxl__egc *egc,
     dcs->dmss.dm.callback = domcreate_devmodel_started;
     dcs->dmss.callback = domcreate_devmodel_started;
 
-    if ( restore_fd >= 0 ) {
-        ret = domain_restore(gc, &d_config->b_info, domid, restore_fd, state);
+    if ( restore_fd < 0 ) {
+        rc = libxl__domain_build(gc, &d_config->b_info, domid, state);
+        domcreate_rebuild_done(egc, dcs, rc);
+        return;
+    }
+
+    /* Restore */
+
+    rc = libxl__build_pre(gc, domid, info, state);
+    if (rc)
+        goto out;
+
+    /* read signature */
+    int hvm, pae, superpages;
+    int no_incr_generationid;
+    switch (info->type) {
+    case LIBXL_DOMAIN_TYPE_HVM:
+        hvm = 1;
+        superpages = 1;
+        pae = libxl_defbool_val(info->u.hvm.pae);
+        no_incr_generationid = !libxl_defbool_val(info->u.hvm.incr_generationid);
+        callbacks->toolstack_restore = libxl__toolstack_restore;
+        callbacks->data = gc;
+        break;
+    case LIBXL_DOMAIN_TYPE_PV:
+        hvm = 0;
+        superpages = 0;
+        pae = 1;
+        no_incr_generationid = 0;
+        break;
+    default:
+        rc = ERROR_INVAL;
+        goto out;
+    }
+    libxl__xc_domain_restore(egc, dcs,
+                             hvm, pae, superpages, no_incr_generationid);
+    return;
+
+ out:
+    libxl__xc_domain_restore_done(egc, dcs, rc, 0, 0);
+}
+
+void libxl__xc_domain_restore_done(libxl__egc *egc,
+                                   libxl__domain_create_state *dcs,
+                                   int ret, int retval, int errnoval)
+{
+    STATE_AO_GC(dcs->ao);
+    libxl_ctx *ctx = libxl__gc_owner(gc);
+    char **vments = NULL, **localents = NULL;
+    struct timeval start_time;
+    int i, esave, flags;
+
+    /* convenience aliases */
+    const uint32_t domid = dcs->guest_domid;
+    libxl_domain_config *const d_config = dcs->guest_config;
+    libxl_domain_build_info *const info = &d_config->b_info;
+    libxl__domain_build_state *const state = &dcs->build_state;
+    const int fd = dcs->restore_fd;
+
+    if (ret)
+        goto out;
+
+    if (retval) {
+        LOGEV(ERROR, errnoval, "restoring domain");
+        ret = ERROR_FAIL;
+        goto out;
+    }
+
+    gettimeofday(&start_time, NULL);
+
+    switch (info->type) {
+    case LIBXL_DOMAIN_TYPE_HVM:
+        vments = libxl__calloc(gc, 7, sizeof(char *));
+        vments[0] = "rtc/timeoffset";
+        vments[1] = (info->u.hvm.timeoffset) ? info->u.hvm.timeoffset : "";
+        vments[2] = "image/ostype";
+        vments[3] = "hvm";
+        vments[4] = "start_time";
+        vments[5] = libxl__sprintf(gc, "%lu.%02d", start_time.tv_sec,(int)start_time.tv_usec/10000);
+        break;
+    case LIBXL_DOMAIN_TYPE_PV:
+        vments = libxl__calloc(gc, 11, sizeof(char *));
+        i = 0;
+        vments[i++] = "image/ostype";
+        vments[i++] = "linux";
+        vments[i++] = "image/kernel";
+        vments[i++] = (char *) state->pv_kernel.path;
+        vments[i++] = "start_time";
+        vments[i++] = libxl__sprintf(gc, "%lu.%02d", start_time.tv_sec,(int)start_time.tv_usec/10000);
+        if (state->pv_ramdisk.path) {
+            vments[i++] = "image/ramdisk";
+            vments[i++] = (char *) state->pv_ramdisk.path;
+        }
+        if (state->pv_cmdline) {
+            vments[i++] = "image/cmdline";
+            vments[i++] = (char *) state->pv_cmdline;
+        }
+        break;
+    default:
+        ret = ERROR_INVAL;
+        goto out;
+    }
+    ret = libxl__build_post(gc, domid, info, state, vments, localents);
+    if (ret)
+        goto out;
+
+    if (info->type == LIBXL_DOMAIN_TYPE_HVM) {
+        ret = asprintf(&state->saved_state,
+                       XC_DEVICE_MODEL_RESTORE_FILE".%d", domid);
+        ret = (ret < 0) ? ERROR_FAIL : 0;
+    }
+
+out:
+    if (info->type == LIBXL_DOMAIN_TYPE_PV) {
+        libxl__file_reference_unmap(&state->pv_kernel);
+        libxl__file_reference_unmap(&state->pv_ramdisk);
+    }
+
+    esave = errno;
+
+    flags = fcntl(fd, F_GETFL);
+    if (flags == -1) {
+        LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "unable to get flags on restore fd");
     } else {
-        ret = libxl__domain_build(gc, &d_config->b_info, domid, state);
+        flags &= ~O_NONBLOCK;
+        if (fcntl(fd, F_SETFL, flags) == -1)
+            LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "unable to put restore fd"
+                         " back to blocking mode");
     }
 
+    errno = esave;
+    domcreate_rebuild_done(egc, dcs, ret);
+}
+
+static void domcreate_rebuild_done(libxl__egc *egc,
+                                   libxl__domain_create_state *dcs,
+                                   int ret)
+{
+    STATE_AO_GC(dcs->ao);
+    int i;
+
+    /* convenience aliases */
+    const uint32_t domid = dcs->guest_domid;
+    libxl_domain_config *const d_config = dcs->guest_config;
+    libxl__domain_build_state *const state = &dcs->build_state;
+    libxl_ctx *const ctx = CTX;
+
     if (ret) {
         LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "cannot (re-)build domain: %d", ret);
         ret = ERROR_FAIL;
tools/libxl/libxl_dom.c +1 -44
index e90030d..1d4e809 100644
@@ -19,7 +19,6 @@
 
 #include <xenctrl.h>
 #include <xc_dom.h>
-#include <xenguest.h>
 
 #include <xen/hvm/hvm_info_table.h>
 
@@ -467,7 +466,7 @@ static inline char *restore_helper(libxl__gc *gc, uint32_t domid,
             domid, phys_offset, node);
 }
 
-static int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
+int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
         uint32_t size, void *data)
 {
     libxl__gc *gc = data;
@@ -522,48 +521,6 @@ static int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
     return 0;
 }
 
-int libxl__domain_restore_common(libxl__gc *gc, uint32_t domid,
-                                 libxl_domain_build_info *info,
-                                 libxl__domain_build_state *state,
-                                 int fd)
-{
-    libxl_ctx *ctx = libxl__gc_owner(gc);
-    /* read signature */
-    int rc;
-    int hvm, pae, superpages;
-    struct restore_callbacks callbacks[1];
-    int no_incr_generationid;
-    switch (info->type) {
-    case LIBXL_DOMAIN_TYPE_HVM:
-        hvm = 1;
-        superpages = 1;
-        pae = libxl_defbool_val(info->u.hvm.pae);
-        no_incr_generationid = !libxl_defbool_val(info->u.hvm.incr_generationid);
-        callbacks->toolstack_restore = libxl__toolstack_restore;
-        callbacks->data = gc;
-        break;
-    case LIBXL_DOMAIN_TYPE_PV:
-        hvm = 0;
-        superpages = 0;
-        pae = 1;
-        no_incr_generationid = 0;
-        break;
-    default:
-        return ERROR_INVAL;
-    }
-    rc = xc_domain_restore(ctx->xch, fd, domid,
-                           state->store_port, &state->store_mfn,
-                           state->store_domid, state->console_port,
-                           &state->console_mfn, state->console_domid,
-                           hvm, pae, superpages, no_incr_generationid,
-                           &state->vm_generationid_addr, callbacks);
-    if ( rc ) {
-        LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "restoring domain");
-        return ERROR_FAIL;
-    }
-    return 0;
-}
-
 static int libxl__domain_suspend_common_switch_qemu_logdirty
                                (int domid, unsigned int enable, void *data)
 {
tools/libxl/libxl_internal.h +15 -4
index f22bf94..28478ea 100644
@@ -46,6 +46,7 @@
 
 #include <xenstore.h>
 #include <xenctrl.h>
+#include <xenguest.h>
 
 #include "xentoollog.h"
 
@@ -782,10 +783,8 @@ _hidden int libxl__domain_rename(libxl__gc *gc, uint32_t domid,
                                  const char *old_name, const char *new_name,
                                  xs_transaction_t trans);
 
-_hidden int libxl__domain_restore_common(libxl__gc *gc, uint32_t domid,
-                                         libxl_domain_build_info *info,
-                                         libxl__domain_build_state *state,
-                                         int fd);
+_hidden int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
+                                     uint32_t size, void *data);
 _hidden const char *libxl__device_model_savefile(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__domain_suspend_device_model(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__domain_resume_device_model(libxl__gc *gc, uint32_t domid);
@@ -1899,6 +1898,7 @@ struct libxl__domain_create_state {
     libxl__stub_dm_spawn_state dmss;
         /* If we're not doing stubdom, we use only dmss.dm,
          * for the non-stubdom device model. */
+    struct restore_callbacks callbacks;
 };
 
 /*----- Domain suspend (save) functions -----*/
@@ -1908,6 +1908,17 @@ _hidden int libxl__domain_suspend_common(libxl__gc *gc, uint32_t domid, int fd,
                                          int live, int debug,
                                          const libxl_domain_remus_info *r_info);
 
+/* calls libxl__xc_domain_restore_done when done */
+_hidden void libxl__xc_domain_restore(libxl__egc *egc,
+                                      libxl__domain_create_state *dcs,
+                                      int hvm, int pae, int superpages,
+                                      int no_incr_generationid);
+/* If rc==0 then retval is the return value from xc_domain_save
+ * and errnoval is the errno value it provided.
+ * If rc!=0, retval and errnoval are undefined. */
+_hidden void libxl__xc_domain_restore_done(libxl__egc *egc,
+                                           libxl__domain_create_state *dcs,
+                                           int rc, int retval, int errnoval);
 
 
 /*
tools/libxl/libxl_save_callout.c new file +37 -1
new file mode 100644
index 0000000..2f8db9f
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2012      Citrix Ltd.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; version 2.1 only. with the special
+ * exception on linking described in file LICENSE.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ */
+
+#include "libxl_osdeps.h"
+
+#include "libxl_internal.h"
+
+void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs,
+                              int hvm, int pae, int superpages,
+                              int no_incr_generationid)
+{
+    STATE_AO_GC(dcs->ao);
+
+    /* Convenience aliases */
+    const uint32_t domid = dcs->guest_domid;
+    const int restore_fd = dcs->restore_fd;
+    libxl__domain_build_state *const state = &dcs->build_state;
+
+    int r = xc_domain_restore(CTX->xch, restore_fd, domid,
+                              state->store_port, &state->store_mfn,
+                              state->store_domid, state->console_port,
+                              &state->console_mfn, state->console_domid,
+                              hvm, pae, superpages, no_incr_generationid,
+                              &state->vm_generationid_addr, &dcs->callbacks);
+    libxl__xc_domain_restore_done(egc, dcs, 0, r, errno);
+}
--

1.7.2.5

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

#8 lore raw

Re: [PATCH 03/19] libxl: domain restore: reshuffle, preparing for ao

Ian Campbell writes ("Re: [Xen-devel] [PATCH 03/19] libxl: domain restore: reshuffle, preparing for ao"):

Quoted 5 lines · Ian Jackson
Quoted 4 lines

We are going to arrange that libxl, instead of calling xc_domain_restore, calls a stub function which forks and execs a helper program, so that restore can be asynchronous rather than blocking the whole toolstack.

...

Quoted 6 lines
Quoted 3 lines

* Move the contents of domain_restore into its correct place in the domain creation sequence. We put it inside domcreate_bootloader_done, which now either calls

"either" but no "or"? I suppose the or case is call domcreate_rebuild_done directly?

Yes. I have completed this sentence.

Quoted 1 line

Thanks.

Quoted 4 lines

I confirmed at a high level that the same blocks of code exist and are called in the same overall order, but I didn't do a line by line comparison of the blocks in question, assuming they really are mostly motion and adjustments for the new context.

Right. I did some semi-mechanical checks to confirm that assertion, after the last round of hideous merge conflict doom.

Ian.

#9 lore raw

PATCH 4/19 libxl: domain save: API changes for asynchrony

In reply to Ian Jackson

Change the internal and external APIs for domain save (suspend) to be capable of asynchronous operation. The implementation remains synchronous. The interfaces surrounding device model saving are still synchronous.

Public API changes:

* libxl_domain_save takes an ao_how.

* libxl_domain_remus_start takes an ao_how. If the libxl_domain_remus_info is NULL, we abort rather than returning an error.

* The `suspend_callback' function passed to libxl_domain_save is never called by the existing implementation in libxl. Abolish it.

* libxl_domain_save takes its flags parameter as an argument. Thus libxl_domain_suspend_info is abolished.

* XL_SUSPEND_* flags renamed to LIBXL_SAVE_*.

* Callers in xl updated.

Internal code restructuring:

* libxl__domain_suspend_state member types and names rationalised.

* libxl__domain_suspend renamed from libxl__domain_suspend_common. (_common here actually meant "internal function").

* libxl__domain_suspend takes a libxl__domain_suspend_state, which where the parameters to the operation are filled in by the caller.

* xc_domain_save is now called via libxl__xc_domain_save which can itself become asynchronous.

* Consequently, libxl__domain_suspend is split into two functions at the callback boundary; the second half is libxl__xc_domain_save_done.

* libxl__domain_save_device_model is now called by the actual implementation rather than by the public wrapper. It is already in its proper place in the domain save execution sequence. So officially make it part of that execution sequence, renaming it to domain_save_device_model.

* Effectively, rewrite the public wrapper functions libxl_domain_suspend and libxl_domain_remus_start.

* Remove a needless #include <xenctrl.h>

* libxl__domain_suspend aborts on unexpected domain types rather than mysteriously returning EINVAL.

* struct save_callbacks moved from the stack to the dss.

Changes in v3:
* Remove hvm' and xcflags' args to libxl__xc_domain_save. Instead, just use the values from the dss.

Changes in v2:
* Move save_callbacks too.
* Merge with Remus changes.
* Improvements to commit message.
* Do not rename libxl_domain_suspend any more.

---
 tools/libxl/libxl.c              |   95 +++++++++++++++++++++---------
 tools/libxl/libxl.h              |   22 ++++----
 tools/libxl/libxl_dom.c          |  121 +++++++++++++++++++++++++++-----------
 tools/libxl/libxl_internal.h     |   45 ++++++++++++---
 tools/libxl/libxl_save_callout.c |   11 ++++
 tools/libxl/xl_cmdimpl.c         |    9 +--
 6 files changed, 215 insertions(+), 88 deletions(-)
tools/libxl/libxl.c +67 -28
index 6215923..7de026b 100644
@@ -648,32 +648,51 @@ libxl_vminfo * libxl_list_vm(libxl_ctx *ctx, int *nb_vm)
     return ptr;
 }
 
+static void remus_crashed_cb(libxl__egc *egc,
+                             libxl__domain_suspend_state *dss, int rc);
+
 /* TODO: Explicit Checkpoint acknowledgements via recv_fd. */
 int libxl_domain_remus_start(libxl_ctx *ctx, libxl_domain_remus_info *info,
-                             uint32_t domid, int send_fd, int recv_fd)
+                             uint32_t domid, int send_fd, int recv_fd,
+                             const libxl_asyncop_how *ao_how)
 {
-    GC_INIT(ctx);
-    libxl_domain_type type = libxl__domain_type(gc, domid);
-    int rc = 0;
+    AO_CREATE(ctx, domid, ao_how);
+    libxl__domain_suspend_state *dss;
+    int rc;
 
+    libxl_domain_type type = libxl__domain_type(gc, domid);
     if (type == LIBXL_DOMAIN_TYPE_INVALID) {
         rc = ERROR_FAIL;
-        goto remus_fail;
+        goto out;
     }
 
-    if (info == NULL) {
-        LIBXL__LOG(ctx, LIBXL__LOG_ERROR,
-                   "No remus_info structure supplied for domain %d", domid);
-        rc = ERROR_INVAL;
-        goto remus_fail;
-    }
+    GCNEW(dss);
+    dss->ao = ao;
+    dss->callback = remus_crashed_cb;
+    dss->domid = domid;
+    dss->fd = send_fd;
+    /* TODO do something with recv_fd */
+    dss->type = type;
+    dss->live = 1;
+    dss->debug = 0;
+    dss->remus = info;
+
+    assert(info);
 
     /* TBD: Remus setup - i.e. attach qdisc, enable disk buffering, etc */
 
     /* Point of no return */
-    rc = libxl__domain_suspend_common(gc, domid, send_fd, type, /* live */ 1,
-                                      /* debug */ 0, info);
+    libxl__domain_suspend(egc, dss);
+    return AO_INPROGRESS;
+
+ out:
+    return AO_ABORT(rc);
+}
 
+static void remus_crashed_cb(libxl__egc *egc,
+                             libxl__domain_suspend_state *dss, int rc)
+{
+    STATE_AO_GC(dss->ao);
     /*
      * With Remus, if we reach this point, it means either
      * backup died or some network error occurred preventing us
@@ -683,27 +702,47 @@ int libxl_domain_remus_start(libxl_ctx *ctx, libxl_domain_remus_info *info,
     /* TBD: Remus cleanup - i.e. detach qdisc, release other
      * resources.
      */
- remus_fail:
-    GC_FREE;
-    return rc;
+    libxl__ao_complete(egc, ao, rc);
 }
 
-int libxl_domain_suspend(libxl_ctx *ctx, libxl_domain_suspend_info *info,
-                         uint32_t domid, int fd)
+static void domain_suspend_cb(libxl__egc *egc,
+                              libxl__domain_suspend_state *dss, int rc)
 {
-    GC_INIT(ctx);
+    STATE_AO_GC(dss->ao);
+    libxl__ao_complete(egc,ao,rc);
+
+}
+
+int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
+                         const libxl_asyncop_how *ao_how)
+{
+    AO_CREATE(ctx, domid, ao_how);
+    int rc;
+
     libxl_domain_type type = libxl__domain_type(gc, domid);
-    int live = info != NULL && info->flags & XL_SUSPEND_LIVE;
-    int debug = info != NULL && info->flags & XL_SUSPEND_DEBUG;
-    int rc = 0;
+    if (type < 0) {
+        LOG(ERROR,"domain %"PRIu32": unable to determine domain type", domid);
+        rc = ERROR_FAIL;
+        goto out_err;
+    }
 
-    rc = libxl__domain_suspend_common(gc, domid, fd, type, live, debug,
-                                      /* No Remus */ NULL);
+    libxl__domain_suspend_state *dss;
+    GCNEW(dss);
 
-    if (!rc && type == LIBXL_DOMAIN_TYPE_HVM)
-        rc = libxl__domain_save_device_model(gc, domid, fd);
-    GC_FREE;
-    return rc;
+    dss->ao = ao;
+    dss->callback = domain_suspend_cb;
+
+    dss->domid = domid;
+    dss->fd = fd;
+    dss->type = type;
+    dss->live = flags & LIBXL_SUSPEND_LIVE;
+    dss->debug = flags & LIBXL_SUSPEND_DEBUG;
+
+    libxl__domain_suspend(egc, dss);
+    return AO_INPROGRESS;
+
+ out_err:
+    return AO_ABORT(rc);
 }
 
 int libxl_domain_pause(libxl_ctx *ctx, uint32_t domid)
tools/libxl/libxl.h +11 -11
index 05f0e01..10d7115 100644
@@ -347,13 +347,6 @@ typedef struct libxl__ctx libxl_ctx;
 
 const libxl_version_info* libxl_get_version_info(libxl_ctx *ctx);
 
-typedef struct {
-#define XL_SUSPEND_DEBUG 1
-#define XL_SUSPEND_LIVE 2
-    int flags;
-    int (*suspend_callback)(void *, int);
-} libxl_domain_suspend_info;
-
 enum {
     ERROR_NONSPECIFIC = -1,
     ERROR_VERSION = -2,
@@ -514,16 +507,23 @@ int libxl_domain_create_restore(libxl_ctx *ctx, libxl_domain_config *d_config,
 
 void libxl_domain_config_init(libxl_domain_config *d_config);
 void libxl_domain_config_dispose(libxl_domain_config *d_config);
-int libxl_domain_remus_start(libxl_ctx *ctx, libxl_domain_remus_info *info,
-                             uint32_t domid, int send_fd, int recv_fd);
-int libxl_domain_suspend(libxl_ctx *ctx, libxl_domain_suspend_info *info,
-                          uint32_t domid, int fd);
+
+int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd,
+                         int flags, /* LIBXL_SUSPEND_* */
+                         const libxl_asyncop_how *ao_how);
+#define LIBXL_SUSPEND_DEBUG 1
+#define LIBXL_SUSPEND_LIVE 2
 
 /* @param suspend_cancel [from xenctrl.h:xc_domain_resume( @param fast )]
  *   If this parameter is true, use co-operative resume. The guest
  *   must support this.
  */
 int libxl_domain_resume(libxl_ctx *ctx, uint32_t domid, int suspend_cancel);
+
+int libxl_domain_remus_start(libxl_ctx *ctx, libxl_domain_remus_info *info,
+                             uint32_t domid, int send_fd, int recv_fd,
+                             const libxl_asyncop_how *ao_how);
+
 int libxl_domain_shutdown(libxl_ctx *ctx, uint32_t domid);
 int libxl_domain_reboot(libxl_ctx *ctx, uint32_t domid);
 int libxl_domain_destroy(libxl_ctx *ctx, uint32_t domid);
tools/libxl/libxl_dom.c +86 -35

235 lines not on this page · raw message

tools/libxl/libxl_internal.h +37 -8

63 lines not on this page · raw message

tools/libxl/libxl_save_callout.c +11 -0
index 2f8db9f..1b481ab 100644
@@ -35,3 +35,14 @@ void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs,
                               &state->vm_generationid_addr, &dcs->callbacks);
     libxl__xc_domain_restore_done(egc, dcs, 0, r, errno);
 }
+
+void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_suspend_state *dss,
+                           unsigned long vm_generationid_addr)
+{
+    STATE_AO_GC(dss->ao);
+    int r;
+
+    r = xc_domain_save(CTX->xch, dss->fd, dss->domid, 0, 0, dss->xcflags,
+                       &dss->callbacks, dss->hvm, vm_generationid_addr);
+    libxl__xc_domain_save_done(egc, dss, 0, r, errno);
+}
tools/libxl/xl_cmdimpl.c +3 -6
index 3ea95ef..19daa1c 100644
@@ -2846,7 +2846,7 @@ static int save_domain(const char *p, const char *filename, int checkpoint,
 
     save_domain_core_writeconfig(fd, filename, config_data, config_len);
 
-    CHK_ERRNO(libxl_domain_suspend(ctx, NULL, domid, fd));
+    CHK_ERRNO(libxl_domain_suspend(ctx, domid, fd, 0, NULL));
     close(fd);
 
     if (checkpoint)
@@ -3008,7 +3008,6 @@ static void migrate_domain(const char *domain_spec, const char *rune,
     pid_t child = -1;
     int rc;
     int send_fd = -1, recv_fd = -1;
-    libxl_domain_suspend_info suspinfo;
     char *away_domname;
     char rc_buf;
     uint8_t *config_data;
@@ -3030,9 +3029,7 @@ static void migrate_domain(const char *domain_spec, const char *rune,
 
     xtl_stdiostream_adjust_flags(logger, XTL_STDIOSTREAM_HIDE_PROGRESS, 0);
 
-    memset(&suspinfo, 0, sizeof(suspinfo));
-    suspinfo.flags |= XL_SUSPEND_LIVE;
-    rc = libxl_domain_suspend(ctx, &suspinfo, domid, send_fd);
+    rc = libxl_domain_suspend(ctx, domid, send_fd, LIBXL_SUSPEND_LIVE, NULL);
     if (rc) {
         fprintf(stderr, "migration sender: libxl_domain_suspend failed"
                 " (rc=%d)\n", rc);
@@ -6604,7 +6601,7 @@ int main_remus(int argc, char **argv)
     }
 
     /* Point of no return */
-    rc = libxl_domain_remus_start(ctx, &r_info, domid, send_fd, recv_fd);
+    rc = libxl_domain_remus_start(ctx, &r_info, domid, send_fd, recv_fd, 0);
 
     /* If we are here, it means backup has failed/domain suspend failed.
      * Try to resume the domain and exit gracefully.
Signature · 1 line
1.7.2.5
#10 lore raw

Re: [PATCH 04/19] libxl: domain save: API changes for asynchrony

Quoted 7 lines · Ian Jackson

Change the internal and external APIs for domain save (suspend) to be capable of asynchronous operation. The implementation remains synchronous. The interfaces surrounding device model saving are still synchronous.

Public API changes:

Quoted 8 lines

* libxl_domain_save takes an ao_how.

* libxl_domain_remus_start takes an ao_how. If the libxl_domain_remus_info is NULL, we abort rather than returning an error.

* The `suspend_callback' function passed to libxl_domain_save is never called by the existing implementation in libxl. Abolish it.

Furthermore xl never passes one in either.
[...]

Quoted 1 line

A few minor comments below, but otherwise looks good to me.

[...]

Review

Quoted 3 lines
(quoted diff) +2 -0
+static void remus_crashed_cb(libxl__egc *egc,
+                             libxl__domain_suspend_state *dss, int rc)

I'm not sure "crashed" is quite right here, it's finished for whatever reason which may not necessarily be a crash (going forward it should rarely be a crash, I think). It's "stopped" or "done" or something.

Quoted 4 lines

[...]

tools/libxl/libxl.c +2 -0
+int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
+                         const libxl_asyncop_how *ao_how)

tools/libxl/libxl.c int libxl_domain_remus_start(libxl_ctx *ctx, libxl_domain_remus_info *info, · line 724

Quoted 10 lines
tools/libxl/libxl.c +6 -3
+{
+    AO_CREATE(ctx, domid, ao_how);
+    int rc;
+
     libxl_domain_type type = libxl__domain_type(gc, domid);
-    int live = info != NULL && info->flags & XL_SUSPEND_LIVE;
-    int debug = info != NULL && info->flags & XL_SUSPEND_DEBUG;
-    int rc = 0;
+    if (type < 0) {
+        LOG(ERROR,"domain %"PRIu32": unable to determine domain type", domid);

libxl__domain_type now logs for you.

Quoted 30 lines
tools/libxl/libxl.c +19 -6
+        rc = ERROR_FAIL;
+        goto out_err;
+    }
 
-    rc = libxl__domain_suspend_common(gc, domid, fd, type, live, debug,
-                                      /* No Remus */ NULL);
+    libxl__domain_suspend_state *dss;
+    GCNEW(dss);
 
-    if (!rc && type == LIBXL_DOMAIN_TYPE_HVM)
-        rc = libxl__domain_save_device_model(gc, domid, fd);
-    GC_FREE;
-    return rc;
+    dss->ao = ao;
+    dss->callback = domain_suspend_cb;
+
+    dss->domid = domid;
+    dss->fd = fd;
+    dss->type = type;
+    dss->live = flags & LIBXL_SUSPEND_LIVE;
+    dss->debug = flags & LIBXL_SUSPEND_DEBUG;
+
+    libxl__domain_suspend(egc, dss);
+    return AO_INPROGRESS;
+
+ out_err:
+    return AO_ABORT(rc);
 }
 
 int libxl_domain_pause(libxl_ctx *ctx, uint32_t domid)

[...]

tools/libxl/libxl_internal.h struct libxl__domain_create_state { · line 1918

Quoted 9 lines
tools/libxl/libxl_internal.h +1 -4
@@ -1903,10 +1915,27 @@ struct libxl__domain_create_state {
 
 /*----- Domain suspend (save) functions -----*/
 
-_hidden int libxl__domain_suspend_common(libxl__gc *gc, uint32_t domid, int fd,
-                                         libxl_domain_type type,
-                                         int live, int debug,
-                                         const libxl_domain_remus_info *r_info);
+/* calls callback when done */

Which callback? dss->callback I guess.

Quoted 23 lines
tools/libxl/libxl_internal.h +20 -0
+_hidden void libxl__domain_suspend(libxl__egc *egc,
+                                   libxl__domain_suspend_state *dss);
+
+
+/* calls libxl__xc_domain_suspend_done when done */
+_hidden void libxl__xc_domain_save(libxl__egc*, libxl__domain_suspend_state*,
+                                   unsigned long vm_generationid_addr);
+/* If rc==0 then retval is the return value from xc_domain_save
+ * and errnoval is the errno value it provided.
+ * If rc!=0, retval and errnoval are undefined. */
+_hidden void libxl__xc_domain_save_done(libxl__egc*,
+                                        libxl__domain_suspend_state*,
+                                        int rc, int retval, int errnoval);
+
+_hidden int libxl__domain_suspend_common_callback(void *data);
+_hidden int libxl__domain_suspend_common_switch_qemu_logdirty
+                               (int domid, unsigned int enable, void *data);
+_hidden int libxl__toolstack_save(uint32_t domid, uint8_t **buf,
+        uint32_t *len, void *data);
+
 
 /* calls libxl__xc_domain_restore_done when done */
 _hidden void libxl__xc_domain_restore(libxl__egc *egc,
#11 lore raw

Re: [PATCH 04/19] libxl: domain save: API changes for asynchrony

Ian Campbell writes ("Re: [Xen-devel] [PATCH 04/19] libxl: domain save: API changes for asynchrony"):

Quoted 5 lines · Ian Jackson
Quoted 4 lines

Change the internal and external APIs for domain save (suspend) to be capable of asynchronous operation. The implementation remains synchronous. The interfaces surrounding device model saving are still synchronous.

...

Quoted 4 lines
Quoted 2 lines

* The `suspend_callback' function passed to libxl_domain_save is never called by the existing implementation in libxl. Abolish it.

Furthermore xl never passes one in either.

Right. I will update the commit message to note this too.

Quoted 3 lines
Quoted 1 line

A few minor comments below, but otherwise looks good to me.

Thanks...

Quoted 6 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+static void remus_crashed_cb(libxl__egc *egc,
+                             libxl__domain_suspend_state *dss, int rc)

I'm not sure "crashed" is quite right here, it's finished for whatever reason which may not necessarily be a crash (going forward it should rarely be a crash, I think). It's "stopped" or "done" or something.

How about "remus_target_gone_cb" ?

Quoted 7 lines

tools/libxl/libxl.c int libxl_domain_remus_start(libxl_ctx *ctx, libxl_domain_remus_info *info,

Quoted 5 lines
tools/libxl/libxl.c +4 -0
+int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
+                         const libxl_asyncop_how *ao_how)
 
+    if (type < 0) {
+        LOG(ERROR,"domain %"PRIu32": unable to determine domain type", domid);

libxl__domain_type now logs for you.

I will bring forward the relevant hunk from my domain type final fixups patch.

Quoted 6 lines
Quoted 1 line

int libxl_domain_pause(libxl_ctx *ctx, uint32_t domid)

[...]

Quoted 4 lines
tools/libxl/libxl_internal.h +0 -0
@@ -1903,10 +1915,27 @@ struct libxl__domain_create_state {
 
 /*----- Domain suspend (save) functions -----*/
 
Quoted 7 lines

tools/libxl/libxl_internal.h struct libxl__domain_create_state { · line 1918

Quoted 5 lines
tools/libxl/libxl_internal.h +1 -4
-_hidden int libxl__domain_suspend_common(libxl__gc *gc, uint32_t domid, int fd,
-                                         libxl_domain_type type,
-                                         int live, int debug,
-                                         const libxl_domain_remus_info *r_info);
+/* calls callback when done */

Which callback? dss->callback I guess.

What a confusing way to quote this. You're referring to this function of course:

Quoted 2 lines

tools/libxl/libxl_internal.h struct libxl__domain_create_state { · line 1920

Quoted 2 lines
tools/libxl/libxl_internal.h +2 -0
+_hidden void libxl__domain_suspend(libxl__egc *egc,
+                                   libxl__domain_suspend_state *dss);

Gripe gripe these comments before functions are inducing you to top-post !

Anyway, yes. I will clarify this comment.

Ian.

#12 lore raw

Re: [PATCH 04/19] libxl: domain save: API changes for asynchrony

Quoted 20 lines · Ian Jackson

Ian Campbell writes ("Re: [Xen-devel] [PATCH 04/19] libxl: domain save: API changes for asynchrony"):

Quoted 5 lines · Ian Jackson
Quoted 4 lines

Change the internal and external APIs for domain save (suspend) to be capable of asynchronous operation. The implementation remains synchronous. The interfaces surrounding device model saving are still synchronous.

...

Quoted 4 lines
Quoted 2 lines

* The `suspend_callback' function passed to libxl_domain_save is never called by the existing implementation in libxl. Abolish it.

Furthermore xl never passes one in either.

Right. I will update the commit message to note this too.

Quoted 3 lines
Quoted 1 line

A few minor comments below, but otherwise looks good to me.

Thanks...

Quoted 8 lines
Quoted 6 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+static void remus_crashed_cb(libxl__egc *egc,
+                             libxl__domain_suspend_state *dss, int rc)

I'm not sure "crashed" is quite right here, it's finished for whatever reason which may not necessarily be a crash (going forward it should rarely be a crash, I think). It's "stopped" or "done" or something.

How about "remus_target_gone_cb" ?

Sounds fine to me, unless you want to work the word "failover" into it?

Quoted 14 lines
Quoted 6 lines
Quoted 1 line

int libxl_domain_pause(libxl_ctx *ctx, uint32_t domid)

[...]

Quoted 4 lines
tools/libxl/libxl_internal.h +0 -0
@@ -1903,10 +1915,27 @@ struct libxl__domain_create_state {
 
 /*----- Domain suspend (save) functions -----*/
 
Quoted 7 lines

tools/libxl/libxl_internal.h struct libxl__domain_create_state { · line 1918

Quoted 5 lines
tools/libxl/libxl_internal.h +1 -4
-_hidden int libxl__domain_suspend_common(libxl__gc *gc, uint32_t domid, int fd,
-                                         libxl_domain_type type,
-                                         int live, int debug,
-                                         const libxl_domain_remus_info *r_info);
+/* calls callback when done */

Which callback? dss->callback I guess.

Quoted 1 line

What a confusing way to quote this.

Yes, sorry.

Quoted 10 lines

You're referring to this function
of course:

Quoted 2 lines

tools/libxl/libxl_internal.h struct libxl__domain_create_state { · line 1920

Quoted 2 lines
tools/libxl/libxl_internal.h +2 -0
+_hidden void libxl__domain_suspend(libxl__egc *egc,
+                                   libxl__domain_suspend_state *dss);

Gripe gripe these comments before functions are inducing you to top-post !

Anyway, yes. I will clarify this comment.

Thanks.

Ian.

#13 lore raw

Re: [PATCH 04/19] libxl: domain save: API changes for asynchrony

Ian Campbell writes ("Re: [Xen-devel] [PATCH 04/19] libxl: domain save: API changes for asynchrony"):

Quoted 4 lines · Ian Jackson
Quoted 1 line

How about "remus_target_gone_cb" ?

Sounds fine to me, unless you want to work the word "failover" into it?

remus_failover_cb ?

Ian.

#14 lore raw

Re: [PATCH 04/19] libxl: domain save: API changes for asynchrony

Quoted 7 lines · Ian Jackson

Ian Campbell writes ("Re: [Xen-devel] [PATCH 04/19] libxl: domain save: API changes for asynchrony"):

Quoted 4 lines · Ian Jackson
Quoted 1 line

How about "remus_target_gone_cb" ?

Sounds fine to me, unless you want to work the word "failover" into it?

remus_failover_cb ?

Sounds good.

#15 lore raw

PATCH 5/19 libxl: domain save/restore: run in a separate process

In reply to Ian Jackson

libxenctrl expects to be able to simply run the save or restore operation synchronously. This won't work well in a process which is trying to handle multiple domains.

The options are:

- Block such a whole process (eg, the whole of libvirt) while migration completes (or until it fails).

- Create a thread to run xc_domain_save and xc_domain_restore on. This is quite unpalatable. Multithreaded programming is error prone enough without generating threads in libraries, particularly if the thread does some very complex operation.

- Fork and run the operation in the child without execing. This is no good because we would need to negotiate with the caller about fds we would inherit (and we might be a very large process).

- Fork and exec a helper.

Of these options the latter is the most palatable.

Consequently:

* A new helper program libxl-save-helper (which does both save and restore). It will be installed in /usr/lib/xen/bin. It does not link against libxl, only libxc, and its error handling does not need to be very advanced. It does contain a plumbing through of the logging interface into the callback stream.

* A small ad-hoc protocol between the helper and libxl which allows log messages and the libxc callbacks to be passed up and down. Protocol doc comment is in libxl_save_helper.c.

* To avoid a lot of tedium the marshalling boilerplate (stubs for the helper and the callback decoder for libxl) is generated with a small perl script.

* Implement new functionality to spawn the helper, monitor its output, provide responses, and check on its exit status.

* The functions libxl__xc_domain_restore_done and libxl__xc_domain_save_done now turn out to want be called in the same place. So make their state argument a void* so that the two functions are type compatible.

The domain save path still writes the qemu savefile synchronously. This will need to be fixed in a subsequent patch.

Changes in v3:
* Suppress errno value in debug message when helper reports successful completion.
* Significant consequential changes to cope with changes to earlier patches in the series.

Changes in v2:
* Helper path can be overridden by an environment variable for testing.
* Add a couple of debug logging messages re toolstack data.
* Fixes from testing.
* Helper protocol message lengths (and numbers) are 16-bit which more clearly avoids piling lots of junk on the stack.
* Merged with remus changes.
* Callback implementations in libxl now called via pointers so remus can have its own callbacks.
* Better namespace prefixes on autogenerated names etc.
* Autogenerator can generate debugging printfs too.

---
 .gitignore                         |    1 +
 .hgignore                          |    2 +
 tools/libxl/Makefile               |   21 ++-
 tools/libxl/libxl_create.c         |   22 ++-
 tools/libxl/libxl_dom.c            |   36 ++--
 tools/libxl/libxl_internal.h       |   56 +++++-
 tools/libxl/libxl_save_callout.c   |  332 +++++++++++++++++++++++++++++-
 tools/libxl/libxl_save_helper.c    |  279 +++++++++++++++++++++++++
 tools/libxl/libxl_save_msgs_gen.pl |  393 ++++++++++++++++++++++++++++++++++++
 9 files changed, 1104 insertions(+), 38 deletions(-)
 create mode 100644 tools/libxl/libxl_save_helper.c
 create mode 100755 tools/libxl/libxl_save_msgs_gen.pl
.gitignore +1 -0
index 7770e54..3451e52 100644
@@ -353,6 +353,7 @@ tools/libxl/_*.[ch]
 tools/libxl/testidl
 tools/libxl/testidl.c
 tools/libxl/*.pyc
+tools/libxl/libxl-save-helper
 tools/blktap2/control/tap-ctl
 tools/firmware/etherboot/eb-roms.h
 tools/firmware/etherboot/gpxe-git-snapshot.tar.gz
.hgignore +2 -0
index 27d8f79..05304ea 100644
@@ -180,9 +180,11 @@
 ^tools/libxl/_.*\.c$
 ^tools/libxl/libxlu_cfg_y\.output$
 ^tools/libxl/xl$
+^tools/libxl/libxl-save-helper$
 ^tools/libxl/testidl$
 ^tools/libxl/testidl\.c$
 ^tools/libxl/tmp\..*$
+^tools/libxl/.*\.new$
 ^tools/libvchan/vchan-node[12]$
 ^tools/libaio/src/.*\.ol$
 ^tools/libaio/src/.*\.os$
tools/libxl/Makefile +18 -3
index 1d8b80a..1b81963 100644
@@ -67,25 +67,30 @@ 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_aoutils.o \
-			libxl_save_callout.o \
+			libxl_save_callout.o _libxl_save_msgs_callout.o \
 			libxl_qmp.o libxl_event.o libxl_fork.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) -include $(XEN_ROOT)/tools/config.h
 
-AUTOINCS= libxlu_cfg_y.h libxlu_cfg_l.h _libxl_list.h _paths.h
+AUTOINCS= libxlu_cfg_y.h libxlu_cfg_l.h _libxl_list.h _paths.h \
+	_libxl_save_msgs_callout.h _libxl_save_msgs_helper.h
 AUTOSRCS= libxlu_cfg_y.c libxlu_cfg_l.c
+AUTOSRCS += _libxl_save_msgs_callout.c _libxl_save_msgs_helper.c
 LIBXLU_OBJS = libxlu_cfg_y.o libxlu_cfg_l.o libxlu_cfg.o \
 	libxlu_disk_l.o libxlu_disk.o libxlu_vif.o libxlu_pci.o
 $(LIBXLU_OBJS): CFLAGS += $(CFLAGS_libxenctrl) # For xentoollog.h
 
-CLIENTS = xl testidl
+CLIENTS = xl testidl libxl-save-helper
 
 XL_OBJS = xl.o xl_cmdimpl.o xl_cmdtable.o xl_sxp.o
 $(XL_OBJS): CFLAGS += $(CFLAGS_libxenctrl) # For xentoollog.h
 $(XL_OBJS): CFLAGS += $(CFLAGS_libxenlight)
 $(XL_OBJS): CFLAGS += -include $(XEN_ROOT)/tools/config.h # libxl_json.h needs it.
 
+SAVE_HELPER_OBJS = libxl_save_helper.o _libxl_save_msgs_helper.o
+$(SAVE_HELPER_OBJS): CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenlight)
+
 testidl.o: CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenlight)
 testidl.c: libxl_types.idl gentest.py libxl.h $(AUTOINCS)
 	$(PYTHON) gentest.py libxl_types.idl testidl.c.new
@@ -117,6 +122,12 @@ _libxl_list.h: $(XEN_INCLUDE)/xen-external/bsd-sys-queue-h-seddery $(XEN_INCLUDE
 	perl $^ --prefix=libxl >[email protected]
 	$(call move-if-changed,[email protected],$@)
 
+_libxl_save_msgs_helper.c _libxl_save_msgs_callout.c \
+_libxl_save_msgs_helper.h _libxl_save_msgs_callout.h: \
+		libxl_save_msgs_gen.pl
+	$(PERL) -w $< $@ >[email protected]
+	$(call move-if-changed,[email protected],$@)
+
 libxl.h: _libxl_types.h
 libxl_json.h: _libxl_types_json.h
 libxl_internal.h: _libxl_types_internal.h _paths.h
@@ -159,6 +170,9 @@ libxlutil.a: $(LIBXLU_OBJS)
 xl: $(XL_OBJS) libxlutil.so libxenlight.so
 	$(CC) $(LDFLAGS) -o $@ $(XL_OBJS) libxlutil.so $(LDLIBS_libxenlight) $(LDLIBS_libxenctrl) -lyajl $(APPEND_LDFLAGS)
 
+libxl-save-helper: $(SAVE_HELPER_OBJS) libxenlight.so
+	$(CC) $(LDFLAGS) -o $@ $(SAVE_HELPER_OBJS) $(LDLIBS_libxenctrl) $(LDLIBS_libxenguest) $(APPEND_LDFLAGS)
+
 testidl: testidl.o libxlutil.so libxenlight.so
 	$(CC) $(LDFLAGS) -o $@ testidl.o libxlutil.so $(LDLIBS_libxenlight) $(LDLIBS_libxenctrl) $(APPEND_LDFLAGS)
 
@@ -170,6 +184,7 @@ install: all
 	$(INSTALL_DIR) $(DESTDIR)$(BASH_COMPLETION_DIR)
 	$(INSTALL_DIR) $(DESTDIR)$(XEN_RUN_DIR)
 	$(INSTALL_PROG) xl $(DESTDIR)$(SBINDIR)
+	$(INSTALL_PROG) libxl-save-helper $(DESTDIR)$(PRIVATE_BINDIR)
 	$(INSTALL_PROG) libxenlight.so.$(MAJOR).$(MINOR) $(DESTDIR)$(LIBDIR)
 	ln -sf libxenlight.so.$(MAJOR).$(MINOR) $(DESTDIR)$(LIBDIR)/libxenlight.so.$(MAJOR)
 	ln -sf libxenlight.so.$(MAJOR) $(DESTDIR)$(LIBDIR)/libxenlight.so
tools/libxl/libxl_create.c +18 -4
index 4439367..00705d8 100644
@@ -601,7 +601,8 @@ static void domcreate_bootloader_done(libxl__egc *egc,
     libxl_domain_build_info *const info = &d_config->b_info;
     const int restore_fd = dcs->restore_fd;
     libxl__domain_build_state *const state = &dcs->build_state;
-    struct restore_callbacks *const callbacks = &dcs->callbacks;
+    libxl__srm_restore_autogen_callbacks *const callbacks =
+        &dcs->shs.callbacks.restore.a;
 
     if (rc) domcreate_rebuild_done(egc, dcs, rc);
 
@@ -641,7 +642,6 @@ static void domcreate_bootloader_done(libxl__egc *egc,
         pae = libxl_defbool_val(info->u.hvm.pae);
         no_incr_generationid = !libxl_defbool_val(info->u.hvm.incr_generationid);
         callbacks->toolstack_restore = libxl__toolstack_restore;
-        callbacks->data = gc;
         break;
     case LIBXL_DOMAIN_TYPE_PV:
         hvm = 0;
@@ -661,10 +661,24 @@ static void domcreate_bootloader_done(libxl__egc *egc,
     libxl__xc_domain_restore_done(egc, dcs, rc, 0, 0);
 }
 
-void libxl__xc_domain_restore_done(libxl__egc *egc,
-                                   libxl__domain_create_state *dcs,
+void libxl__srm_callout_callback_restore_results(unsigned long store_mfn,
+          unsigned long console_mfn, unsigned long genidad, void *user)
+{
+    libxl__save_helper_state *shs = user;
+    libxl__domain_create_state *dcs = CONTAINER_OF(shs, *dcs, shs);
+    STATE_AO_GC(dcs->ao);
+    libxl__domain_build_state *const state = &dcs->build_state;
+
+    state->store_mfn =            store_mfn;
+    state->console_mfn =          console_mfn;
+    state->vm_generationid_addr = genidad;
+    shs->need_results =           0;
+}
+
+void libxl__xc_domain_restore_done(libxl__egc *egc, void *dcs_void,
                                    int ret, int retval, int errnoval)
 {
+    libxl__domain_create_state *dcs = dcs_void;
     STATE_AO_GC(dcs->ao);
     libxl_ctx *ctx = libxl__gc_owner(gc);
     char **vments = NULL, **localents = NULL;
tools/libxl/libxl_dom.c +22 -14
index b48452c..fea0c94 100644
@@ -465,16 +465,20 @@ static inline char *restore_helper(libxl__gc *gc, uint32_t domid,
 }
 
 int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
-        uint32_t size, void *data)
+                             uint32_t size, void *user)
 {
-    libxl__gc *gc = data;
-    libxl_ctx *ctx = gc->owner;
+    libxl__save_helper_state *shs = user;
+    libxl__domain_create_state *dcs = CONTAINER_OF(shs, *dcs, shs);
+    STATE_AO_GC(dcs->ao);
+    libxl_ctx *ctx = CTX;
     int i, ret;
     const uint8_t *ptr = buf;
     uint32_t count = 0, version = 0;
     struct libxl__physmap_info* pi;
     char *xs_path;
 
+    LOG(DEBUG,"domain=%"PRIu32" toolstack data size=%"PRIu32, domid, size);
+
     if (size < sizeof(version) + sizeof(count)) {
         LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "wrong size");
         return -1;
@@ -527,9 +531,10 @@ static void domain_suspend_done(libxl__egc *egc,
 /*----- callbacks, called by xc_domain_save -----*/
 
 int libxl__domain_suspend_common_switch_qemu_logdirty
-                               (int domid, unsigned int enable, void *data)
+                               (int domid, unsigned enable, void *user)
 {
-    libxl__domain_suspend_state *dss = data;
+    libxl__save_helper_state *shs = user;
+    libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
     STATE_AO_GC(dss->ao);
     char *path;
     bool rc;
@@ -595,9 +600,10 @@ int libxl__domain_resume_device_model(libxl__gc *gc, uint32_t domid)
     return 0;
 }
 
-int libxl__domain_suspend_common_callback(void *data)
+int libxl__domain_suspend_common_callback(void *user)
 {
-    libxl__domain_suspend_state *dss = data;
+    libxl__save_helper_state *shs = user;
+    libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
     STATE_AO_GC(dss->ao);
     unsigned long hvm_s_state = 0, hvm_pvdrv = 0;
     int ret;
@@ -737,9 +743,9 @@ static inline char *save_helper(libxl__gc *gc, uint32_t domid,
 }
 
 int libxl__toolstack_save(uint32_t domid, uint8_t **buf,
-        uint32_t *len, void *data)
+        uint32_t *len, void *dss_void)
 {
-    libxl__domain_suspend_state *dss = data;
+    libxl__domain_suspend_state *dss = dss_void;
     STATE_AO_GC(dss->ao);
     int i = 0;
     char *start_addr = NULL, *size = NULL, *phys_offset = NULL, *name = NULL;
@@ -808,6 +814,8 @@ int libxl__toolstack_save(uint32_t domid, uint8_t **buf,
         ptr += sizeof(struct libxl__physmap_info) + namelen;
     }
 
+    LOG(DEBUG,"domain=%"PRIu32" toolstack data size=%"PRIu32, domid, *len);
+
     return 0;
 }
 
@@ -862,7 +870,8 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
     const int live = dss->live;
     const int debug = dss->debug;
     const libxl_domain_remus_info *const r_info = dss->remus;
-    struct save_callbacks *const callbacks = &dss->callbacks;
+    libxl__srm_save_autogen_callbacks *const callbacks =
+        &dss->shs.callbacks.save.a;
 
     switch (type) {
     case LIBXL_DOMAIN_TYPE_HVM: {
@@ -923,8 +932,7 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
         callbacks->suspend = libxl__domain_suspend_common_callback;
 
     callbacks->switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
-    callbacks->toolstack_save = libxl__toolstack_save;
-    callbacks->data = dss;
+    dss->shs.callbacks.save.toolstack_save = libxl__toolstack_save;
 
     libxl__xc_domain_save(egc, dss, vm_generationid_addr);
     return;
@@ -933,10 +941,10 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
     domain_suspend_done(egc, dss, rc);
 }
 
-void libxl__xc_domain_save_done(libxl__egc *egc,
-                                libxl__domain_suspend_state *dss,
+void libxl__xc_domain_save_done(libxl__egc *egc, void *dss_void,
                                 int rc, int retval, int errnoval)
 {
+    libxl__domain_suspend_state *dss = dss_void;
     STATE_AO_GC(dss->ao);
 
     /* Convenience aliases */
tools/libxl/libxl_internal.h +50 -6

92 lines not on this page · raw message

tools/libxl/libxl_save_callout.c +321 -11

349 lines not on this page · raw message

tools/libxl/libxl_save_helper.c new file +279 -0

279 lines not on this page · raw message

tools/libxl/libxl_save_msgs_gen.pl new file +393 -0

393 lines not on this page · raw message

Signature · 1 line
1.7.2.5
#16 lore raw
Quoted 69 lines · Ian Jackson

libxenctrl expects to be able to simply run the save or restore operation synchronously. This won't work well in a process which is trying to handle multiple domains.

The options are:

- Block such a whole process (eg, the whole of libvirt) while migration completes (or until it fails).

- Create a thread to run xc_domain_save and xc_domain_restore on. This is quite unpalatable. Multithreaded programming is error prone enough without generating threads in libraries, particularly if the thread does some very complex operation.

- Fork and run the operation in the child without execing. This is no good because we would need to negotiate with the caller about fds we would inherit (and we might be a very large process).

- Fork and exec a helper.

Of these options the latter is the most palatable.

Consequently:

* A new helper program libxl-save-helper (which does both save and restore). It will be installed in /usr/lib/xen/bin. It does not link against libxl, only libxc, and its error handling does not need to be very advanced. It does contain a plumbing through of the logging interface into the callback stream.

* A small ad-hoc protocol between the helper and libxl which allows log messages and the libxc callbacks to be passed up and down. Protocol doc comment is in libxl_save_helper.c.

* To avoid a lot of tedium the marshalling boilerplate (stubs for the helper and the callback decoder for libxl) is generated with a small perl script.

* Implement new functionality to spawn the helper, monitor its output, provide responses, and check on its exit status.

* The functions libxl__xc_domain_restore_done and libxl__xc_domain_save_done now turn out to want be called in the same place. So make their state argument a void* so that the two functions are type compatible.

The domain save path still writes the qemu savefile synchronously. This will need to be fixed in a subsequent patch.

Changes in v3:
* Suppress errno value in debug message when helper reports successful completion.
* Significant consequential changes to cope with changes to earlier patches in the series.

Changes in v2:
* Helper path can be overridden by an environment variable for testing.
* Add a couple of debug logging messages re toolstack data.
* Fixes from testing.
* Helper protocol message lengths (and numbers) are 16-bit which more clearly avoids piling lots of junk on the stack.
* Merged with remus changes.
* Callback implementations in libxl now called via pointers so remus can have its own callbacks.
* Better namespace prefixes on autogenerated names etc.
* Autogenerator can generate debugging printfs too.
---

[...]

.hgignore line 187

Quoted 13 lines
.hgignore +2 -0
index 27d8f79..05304ea 100644
@@ -180,9 +180,11 @@
 ^tools/libxl/_.*\.c$
 ^tools/libxl/libxlu_cfg_y\.output$
 ^tools/libxl/xl$
+^tools/libxl/libxl-save-helper$
 ^tools/libxl/testidl$
 ^tools/libxl/testidl\.c$
 ^tools/libxl/tmp\..*$
+^tools/libxl/.*\.new$

Our naming scheme for these sorts of temporary files is rather in consistent (including an existing use of .new), oh well...

[...]

Quoted 20 lines
.hgignore +9 -0
+SAVE_HELPER_OBJS = libxl_save_helper.o _libxl_save_msgs_helper.o
+$(SAVE_HELPER_OBJS): CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenlight)
+
 testidl.o: CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenlight)
 testidl.c: libxl_types.idl gentest.py libxl.h $(AUTOINCS)
        $(PYTHON) gentest.py libxl_types.idl testidl.c.new
@@ -117,6 +122,12 @@ _libxl_list.h: $(XEN_INCLUDE)/xen-external/bsd-sys-queue-h-seddery $(XEN_INCLUDE
        perl $^ --prefix=libxl >[email protected]
        $(call move-if-changed,[email protected],$@)
 
+_libxl_save_msgs_helper.c _libxl_save_msgs_callout.c \
+_libxl_save_msgs_helper.h _libxl_save_msgs_callout.h: \
+               libxl_save_msgs_gen.pl
+       $(PERL) -w $< $@ >[email protected]
+       $(call move-if-changed,[email protected],$@)
+
 libxl.h: _libxl_types.h
 libxl_json.h: _libxl_types_json.h
 libxl_internal.h: _libxl_types_internal.h _paths.h

.hgignore libxlutil.a: $(LIBXLU_OBJS) · line 174

Quoted 5 lines
.hgignore +2 -0
@@ -159,6 +170,9 @@ libxlutil.a: $(LIBXLU_OBJS)
 xl: $(XL_OBJS) libxlutil.so libxenlight.so
        $(CC) $(LDFLAGS) -o $@ $(XL_OBJS) libxlutil.so $(LDLIBS_libxenlight) $(LDLIBS_libxenctrl) -lyajl $(APPEND_LDFLAGS)
 
+libxl-save-helper: $(SAVE_HELPER_OBJS) libxenlight.so
+       $(CC) $(LDFLAGS) -o $@ $(SAVE_HELPER_OBJS) $(LDLIBS_libxenctrl) $(LDLIBS_libxenguest) $(APPEND_LDFLAGS)

The changelog says that libxl-save-helper doesn't link libxenlight but it is declared as a dependency here and CFLAGS_libxenlight is included in SAVE_HELPER_OBJS' CFLAGS above.

Quoted 3 lines
.hgignore +1 -0
+
 testidl: testidl.o libxlutil.so libxenlight.so
        $(CC) $(LDFLAGS) -o $@ testidl.o libxlutil.so $(LDLIBS_libxenlight) $(LDLIBS_libxenctrl) $(APPEND_LDFLAGS)

[...]

.hgignore install: all · line 187

Quoted 5 lines
.hgignore +1 -0
@@ -170,6 +184,7 @@ install: all
        $(INSTALL_DIR) $(DESTDIR)$(BASH_COMPLETION_DIR)
        $(INSTALL_DIR) $(DESTDIR)$(XEN_RUN_DIR)
        $(INSTALL_PROG) xl $(DESTDIR)$(SBINDIR)
+       $(INSTALL_PROG) libxl-save-helper $(DESTDIR)$(PRIVATE_BINDIR)

This needs an INSTALL_DIR for $(DESTDIR)$(PRIVATE_BINDIR) to support
"make -C tools/libxl DESTDIR=xxx install" else:
install: cannot create regular file `/tmp/tmplKa0Y7/usr/lib/xen/bin': No such file or directory

Quoted 11 lines
.hgignore +0 -0
        $(INSTALL_PROG) libxenlight.so.$(MAJOR).$(MINOR) $(DESTDIR)$(LIBDIR)
        ln -sf libxenlight.so.$(MAJOR).$(MINOR) $(DESTDIR)$(LIBDIR)/libxenlight.so.$(MAJOR)
        ln -sf libxenlight.so.$(MAJOR) $(DESTDIR)$(LIBDIR)/libxenlight.so
tools/libxl/libxl_dom.c +0 -0
index b48452c..fea0c94 100644
@@ -465,16 +465,20 @@ static inline char *restore_helper(libxl__gc *gc, uint32_t domid,
 }
 

tools/libxl/libxl_dom.c static inline char *restore_helper(libxl__gc *gc, uint32_t domid, · line 473

Quoted 10 lines
tools/libxl/libxl_dom.c +5 -3
 int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
-        uint32_t size, void *data)
+                             uint32_t size, void *user)
 {
-    libxl__gc *gc = data;
-    libxl_ctx *ctx = gc->owner;
+    libxl__save_helper_state *shs = user;
+    libxl__domain_create_state *dcs = CONTAINER_OF(shs, *dcs, shs);
+    STATE_AO_GC(dcs->ao);
+    libxl_ctx *ctx = CTX;

Any reason you didn't s/ctx/CTX/ in one of your preparatory patches?

Quoted 5 lines
tools/libxl/libxl_dom.c +0 -0
     int i, ret;
     const uint8_t *ptr = buf;
     uint32_t count = 0, version = 0;
     struct libxl__physmap_info* pi;
     char *xs_path;

[...]

Quoted 65 lines
tools/libxl/libxl_save_callout.c +36 -8
index 1b481ab..a39f434 100644
@@ -16,6 +16,19 @@
 
 #include "libxl_internal.h"
 
+static void run_helper(libxl__egc *egc, libxl__save_helper_state *shs,
+                       const char *mode_arg, int data_fd,
+                       const unsigned long *argnums, int num_argnums);
+
+static void helper_failed(libxl__egc*, libxl__save_helper_state *shs, int rc);
+static void helper_stdout_readable(libxl__egc *egc, libxl__ev_fd *ev,
+                                   int fd, short events, short revents);
+static void helper_exited(libxl__egc *egc, libxl__ev_child *ch,
+                          pid_t pid, int status);
+static void helper_done(libxl__egc *egc, libxl__save_helper_state *shs);
+
+/*----- entrypoints -----*/
+
 void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs,
                               int hvm, int pae, int superpages,
                               int no_incr_generationid)
@@ -27,22 +40,319 @@ void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs,
     const int restore_fd = dcs->restore_fd;
     libxl__domain_build_state *const state = &dcs->build_state;
 
-    int r = xc_domain_restore(CTX->xch, restore_fd, domid,
-                              state->store_port, &state->store_mfn,
-                              state->store_domid, state->console_port,
-                              &state->console_mfn, state->console_domid,
-                              hvm, pae, superpages, no_incr_generationid,
-                              &state->vm_generationid_addr, &dcs->callbacks);
-    libxl__xc_domain_restore_done(egc, dcs, 0, r, errno);
+    unsigned cbflags = libxl__srm_callout_enumcallbacks_restore
+        (&dcs->shs.callbacks.restore.a);
+
+    const unsigned long argnums[] = {
+        restore_fd, domid,
+        state->store_port,
+        state->store_domid, state->console_port,
+        state->console_domid,
+        hvm, pae, superpages, no_incr_generationid,
+        cbflags,
+    };
+
+    dcs->shs.ao = ao;
+    dcs->shs.domid = domid;
+    dcs->shs.recv_callback = libxl__srm_callout_received_restore;
+    dcs->shs.completion_callback = libxl__xc_domain_restore_done;
+    dcs->shs.caller_state = dcs;
+    dcs->shs.need_results = 1;
+    dcs->shs.toolstack_data_file = 0;
+
+    run_helper(egc, &dcs->shs, "--restore-domain", restore_fd,
+               argnums, ARRAY_SIZE(argnums));
 }
 
 void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_suspend_state *dss,
                            unsigned long vm_generationid_addr)
 {
     STATE_AO_GC(dss->ao);
-    int r;
+    int r, rc;

tools/libxl/libxl_save_callout.c void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs, · line 81

Quoted 10 lines
tools/libxl/libxl_save_callout.c +10 -0
+    uint32_t toolstack_data_len;
+
+    /* Resources we need to free */
+    uint8_t *toolstack_data_buf = 0;
+
+    unsigned cbflags = libxl__srm_callout_enumcallbacks_save
+        (&dss->shs.callbacks.save.a);
+
+    r = libxl__toolstack_save(dss->domid, &toolstack_data_buf,
+                              &toolstack_data_len, dss);

This seems to be called twice? I'm looking at the source after the full series is applied and I see

        dss->shs.callbacks.save.toolstack_save = libxl__toolstack_save;

in libxl__domain_suspend as well as this call here.

The callback one seems to be otherwise unused.

Quoted 29 lines
tools/libxl/libxl_save_callout.c +29 -0
+static void run_helper(libxl__egc *egc, libxl__save_helper_state *shs,
+                       const char *mode_arg, int data_fd,
+                       const unsigned long *argnums, int num_argnums)
+{
+    STATE_AO_GC(shs->ao);
+    const char *args[3 + num_argnums];
+    const char **arg = args;
+    int i, rc;
+
+    /* Resources we must free */
+    libxl__carefd *childs_pipes[2] = { 0,0 };
+
+    /* Convenience aliases */
+    const uint32_t domid = shs->domid;
+
+    shs->rc = 0;
+    shs->completed = 0;
+    shs->pipes[0] = shs->pipes[1] = 0;
+    libxl__ev_fd_init(&shs->readable);
+    libxl__ev_child_init(&shs->child);
+
+    shs->stdin_what = GCSPRINTF("domain %"PRIu32" save/restore helper"
+                                " stdin pipe", domid);
+    shs->stdout_what = GCSPRINTF("domain %"PRIu32" save/restore helper"
+                                 " stdout pipe", domid);
+
+    *arg++ = getenv("LIBXL_SAVE_HELPER") ?: LIBEXEC "/" "libxl-save-helper";
+    *arg++ = mode_arg;
+    for (i=0; i<num_argnums; i++)

tools/libxl/libxl_save_callout.c void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs, · line 171

Quoted 10 lines
tools/libxl/libxl_save_callout.c +10 -0
+        *arg++ = GCSPRINTF("%lu", argnums[i]);
+    *arg++ = 0;
+    assert(arg == args + ARRAY_SIZE(args));
+
+    libxl__carefd_begin();
+    for (i=0; i<2; i++) {
+        int fds[2];
+        if (libxl_pipe(CTX,fds)) { rc = ERROR_FAIL; goto out; }
+        childs_pipes[i] = libxl__carefd_record(CTX, fds[i]);
+        shs->pipes[i] = libxl__carefd_record(CTX, fds[!i]);

Using !i here is clever, but I had to deploy a pen to be sure the assignments were all correct.

Open coding this simple loop would also give you the opportunity the have comments like "/* This is the helper processes's stdout */" etc in the appropriate place to aid in comprehension when checking the correct end of each pipe goes in the right place.

Quoted 46 lines
tools/libxl/libxl_save_callout.c +46 -0
+    }
+    libxl__carefd_unlock();
+
+    pid_t pid = libxl__ev_child_fork(gc, &shs->child, helper_exited);
+    if (!pid) {
+        libxl_fd_set_cloexec(CTX, data_fd, 0);
+        libxl__exec(gc,
+                    libxl__carefd_fd(childs_pipes[0]),
+                    libxl__carefd_fd(childs_pipes[1]),
+                    -1,
+                    args[0], (char**)args, 0);
+    }
+
+    libxl__carefd_close(childs_pipes[0]);
+    libxl__carefd_close(childs_pipes[1]);
+
+    rc = libxl__ev_fd_register(gc, &shs->readable, helper_stdout_readable,
+                               libxl__carefd_fd(shs->pipes[1]), POLLIN|POLLPRI);
+    if (rc) goto out;
+    return;
+
+ out:
+    libxl__carefd_close(childs_pipes[0]);
+    libxl__carefd_close(childs_pipes[1]);
+    helper_failed(egc, shs, rc);;
+}
+
+static void helper_failed(libxl__egc *egc, libxl__save_helper_state *shs,
+                          int rc)
+{
+    STATE_AO_GC(shs->ao);
+
+    if (!shs->rc)
+        shs->rc = rc;
+
+    libxl__ev_fd_deregister(gc, &shs->readable);
+
+    if (!libxl__ev_child_inuse(&shs->child)) {
+        helper_done(egc, shs);
+        return;
+    }
+
+    int r = kill(shs->child.pid, SIGKILL);
+    if (r) LOGE(WARN, "failed to kill save/restore helper [%lu]",
+                (unsigned long)shs->child.pid);
+}

tools/libxl/libxl_save_callout.c void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs, · line 227

Quoted 10 lines
tools/libxl/libxl_save_callout.c +10 -0
+
+static void helper_stdout_readable(libxl__egc *egc, libxl__ev_fd *ev,
+                                   int fd, short events, short revents)
+{
+    libxl__save_helper_state *shs = CONTAINER_OF(ev, *shs, readable);
+    STATE_AO_GC(shs->ao);
+    int rc, errnoval;
+
+    if (revents & POLLPRI) {
+        LOG(ERROR, "%s signaled POLLERR", shs->stdout_what);

signalled ?

(it's not impossible that my spell checker is wrong, google seem to think both are ok)

The if says POLLPRI but the log says POLLERR?

tools/libxl/libxl_save_callout.c void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs, · line 230

Quoted 3 lines
tools/libxl/libxl_save_callout.c +3 -0
+        rc = ERROR_FAIL;
+ out:
+        /* this is here because otherwise we bypass the decl of msg[] */

I don't get this comment, why can't "out:" be in the normal place after the non-error return?

Quoted 36 lines
tools/libxl/libxl_save_callout.c +36 -0
+        helper_failed(egc, shs, rc);
+        return;
+    }
+
+    uint16_t msglen;
+    errnoval = libxl_read_exactly(CTX, fd, &msglen, sizeof(msglen),
+                                  shs->stdout_what, "ipc msg header");
+    if (errnoval) { rc = ERROR_FAIL; goto out; }
+
+    unsigned char msg[msglen];
+    errnoval = libxl_read_exactly(CTX, fd, msg, msglen,
+                                  shs->stdout_what, "ipc msg body");
+    if (errnoval) { rc = ERROR_FAIL; goto out; }
+
+    shs->egc = egc;
+    shs->recv_callback(msg, msglen, shs);
+    shs->egc = 0;
+    return;
+}
+
+static void helper_exited(libxl__egc *egc, libxl__ev_child *ch,
+                          pid_t pid, int status)
+{
+    libxl__save_helper_state *shs = CONTAINER_OF(ch, *shs, child);
+    STATE_AO_GC(shs->ao);
+
+    /* Convenience aliases */
+    const uint32_t domid = shs->domid;
+
+    const char *what =
+        GCSPRINTF("domain %"PRIu32" save/restore helper", domid);
+
+    if (status) {
+        libxl_report_child_exitstatus(CTX, XTL_ERROR, what, pid, status);
+        shs->rc = ERROR_FAIL;
+    }

tools/libxl/libxl_save_callout.c void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs, · line 276

Quoted 10 lines
tools/libxl/libxl_save_callout.c +10 -0
+
+    if (shs->need_results) {
+        if (!shs->rc)
+            LOG(ERROR,"%s exited without providing results",what);
+        shs->rc = ERROR_FAIL;
+    }
+
+    if (!shs->completed) {
+        if (!shs->rc)
+            LOG(ERROR,"%s exited without signaling completion",what);

signalling again, same caveat

Quoted 6 lines
tools/libxl/libxl_save_callout.c +6 -0
+        shs->rc = ERROR_FAIL;
+    }
+
+    helper_done(egc, shs);
+    return;
+}

[...]

Quoted 1 line

+/*----- generic helpers for the autogenerated code -----*/

[...]

tools/libxl/libxl_save_helper.c line 7

Quoted 13 lines
tools/libxl/libxl_save_helper.c new file +7 -0
new file mode 100644
index 0000000..d29f1f7
@@ -0,0 +1,279 @@
+/*
+ * Copyright (C) 2012      Citrix Ltd.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; version 2.1 only. with the special
+ * exception on linking described in file LICENSE.

LGPL, or perhaps GPL since this is a helper?

(I suppose the same argument could be made for xl itself)

[...]

Quoted 23 lines
tools/libxl/libxl_save_helper.c new file +23 -0
+/*----- helper functions called by autogenerated stubs -----*/
+
+unsigned char * helper_allocbuf(int len, void *user)
+{
+    return xmalloc(len);
+}
+
+static void transmit(const unsigned char *msg, int len, void *user)
+{
+    while (len) {
+        int r = write(1, msg, len);
+        if (r<0) { perror("write"); exit(-1); }
+        assert(r >= 0);
+        assert(r <= len);
+        len -= r;
+        msg += r;
+    }
+}
+
+void helper_transmitmsg(unsigned char *msg_freed, int len_in, void *user)
+{
+    assert(len_in < 64*1024);
+    uint16_t len = len_in;

tools/libxl/libxl_save_helper.c line 160

Quoted 10 lines
tools/libxl/libxl_save_helper.c new file +10 -0
+    transmit((const void*)&len, sizeof(len), user);
+    transmit(msg_freed, len, user);
+    free(msg_freed);
+}
+
+int helper_getreply(void *user)
+{
+    int v;
+    int r = read_exactly(0, &v, sizeof(v));
+    if (r<=0) exit(-2);

You use -1 a lot but here you use -2, are we supposed to be able to infer something from the specific error code?

Quoted 7 lines
tools/libxl/libxl_save_helper.c new file +7 -0
+    return v;
+}
+
+/*----- other callbacks -----*/
+
+static int toolstack_save_fd;
+static uint32_t toolstack_save_len;

[...]

tools/libxl/libxl_save_msgs_gen.pl line 7

Quoted 13 lines
tools/libxl/libxl_save_msgs_gen.pl new file +7 -0
new file mode 100755
index 0000000..cd0837e
@@ -0,0 +1,393 @@
+#!/usr/bin/perl -w
+
+use warnings;
+use strict;
+use POSIX;
+
+our $debug = 0; # produce copius debugging output at run-time?

copious

(which is probably the most useful feedback you are going to get from me on a Perl script ;-))

Quoted 54 lines
tools/libxl/libxl_save_msgs_gen.pl new file +54 -0
+
+our @msgs = (
+    # flags:
+    #   s  - applicable to save
+    #   r  - applicable to restore
+    #   c  - function pointer in callbacks struct rather than fixed function
+    #   x  - function pointer is in struct {save,restore}_callbacks
+    #         and its null-ness needs to be passed through to the helper's xc
+    #   W  - needs a return value; callback is synchronous
+    [  1, 'sr',     "log",                   [qw(uint32_t level
+                                                 uint32_t errnoval
+                                                 STRING context
+                                                 STRING formatted)] ],
+    [  2, 'sr',     "progress",              [qw(STRING context
+                                                 STRING doing_what),
+                                                'unsigned long', 'done',
+                                                'unsigned long', 'total'] ],
+    [  3, 'scxW',   "suspend", [] ],
+    [  4, 'scxW',   "postcopy", [] ],
+    [  5, 'scxW',   "checkpoint", [] ],
+    [  6, 'scxW',   "switch_qemu_logdirty",  [qw(int domid
+                                              unsigned enable)] ],
+    #                toolstack_save          done entirely `by hand'
+    [  7, 'rcxW',   "toolstack_restore",     [qw(uint32_t domid
+                                                BLOCK tsdata)] ],
+    [  8, 'r',      "restore_results",       ['unsigned long', 'store_mfn',
+                                              'unsigned long', 'console_mfn',
+                                              'unsigned long', 'genidad'] ],
+    [  9, 'srW',    "complete",              [qw(int retval
+                                                 int errnoval)] ],
+);
+
+#----------------------------------------
+
+our %cbs;
+our %func;
+our %func_ah;
+our @outfuncs;
+our %out_decls;
+our %out_body;
+our %msgnum_used;
+
+die unless @ARGV==1;
+die if $ARGV[0] =~ m/^-/;
+
+our ($intendedout) = @ARGV;
+
+$intendedout =~ m/([a-z]+)\.([ch])$/ or die;
+my ($want_ah, $ch) = ($1, $2);
+
+my $declprefix = '';
+
+foreach my $ah (qw(callout helper)) {
+    $out_body{$ah} .= <<END.($ah eq 'callout' ? <<END : <<END);

[...]

Quoted 1 line

+END

[...]

Quoted 1 line

+END

[...]

Quoted 1 line

+END

I think I can infer what this does, but wow ;-)

Quoted 1 line

+}

[...]

#17 lore raw

Ian Campbell writes ("Re: [Xen-devel] [PATCH 05/19] libxl: domain save/restore: run in a separate process"):

Quoted 4 lines · Ian Jackson
Quoted 3 lines

libxenctrl expects to be able to simply run the save or restore operation synchronously. This won't work well in a process which is trying to handle multiple domains.

...

Quoted 8 lines

.hgignore line 187

Quoted 5 lines
.hgignore +1 -0
index 27d8f79..05304ea 100644
 
 ^tools/libxl/tmp\..*$
+^tools/libxl/.*\.new$

Our naming scheme for these sorts of temporary files is rather in consistent (including an existing use of .new), oh well...

Hmm, yes. I took my cue from libxl_list.h, which is immediately before _libxl_save_msgs_helper.[ch] in the Makefile.

Quoted 6 lines

.hgignore

Quoted 2 lines
.hgignore +2 -0
+libxl-save-helper: $(SAVE_HELPER_OBJS) libxenlight.so
+       $(CC) $(LDFLAGS) -o $@ $(SAVE_HELPER_OBJS) $(LDLIBS_libxenctrl) $(LDLIBS_libxenguest) $(APPEND_LDFLAGS)

The changelog says that libxl-save-helper doesn't link libxenlight but it is declared as a dependency here and CFLAGS_libxenlight is included in SAVE_HELPER_OBJS' CFLAGS above.

This is a mistake in the Makefile, which I have fixed.

Quoted 12 lines
Quoted 2 lines

testidl: testidl.o libxlutil.so libxenlight.so

        $(CC) $(LDFLAGS) -o $@ testidl.o libxlutil.so $(LDLIBS_libxenlight) $(LDLIBS_libxenctrl) $(APPEND_LDFLAGS)

[...]

.hgignore install: all · line 187

Quoted 5 lines
.hgignore +1 -0
@@ -170,6 +184,7 @@ install: all
        $(INSTALL_DIR) $(DESTDIR)$(BASH_COMPLETION_DIR)
        $(INSTALL_DIR) $(DESTDIR)$(XEN_RUN_DIR)
        $(INSTALL_PROG) xl $(DESTDIR)$(SBINDIR)
+       $(INSTALL_PROG) libxl-save-helper $(DESTDIR)$(PRIVATE_BINDIR)

This needs an INSTALL_DIR for $(DESTDIR)$(PRIVATE_BINDIR) to support
"make -C tools/libxl DESTDIR=xxx install" else:
install: cannot create regular file `/tmp/tmplKa0Y7/usr/lib/xen/bin': No such file or directory

OK. I guess I never do that and it's a bit of a mystery why one would without having done a more general install before, but it's clearly a correct change.

Quoted 2 lines
Quoted 2 lines
tools/libxl/libxl_dom.c +0 -0
index b48452c..fea0c94 100644

...

Quoted 2 lines
Quoted 2 lines

int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
- uint32_t size, void *data)

...

Quoted 3 lines
Quoted 1 line

+ libxl_ctx *ctx = CTX;

Any reason you didn't s/ctx/CTX/ in one of your preparatory patches?

I didn't want to do that unless it was necessary. There was already enough else going on. I don't think having a ctx rather than using CTX is wrong, although it is slightly less in the modern idiom.

Quoted 19 lines
Quoted 6 lines

void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_suspend_state *dss,
unsigned long vm_generationid_addr)

 {
     STATE_AO_GC(dss->ao);
tools/libxl/libxl_dom.c +1 -1
-    int r;
+    int r, rc;

tools/libxl/libxl_dom.c

Quoted 10 lines
tools/libxl/libxl_dom.c +10 -0
+    uint32_t toolstack_data_len;
+
+    /* Resources we need to free */
+    uint8_t *toolstack_data_buf = 0;
+
+    unsigned cbflags = libxl__srm_callout_enumcallbacks_save
+        (&dss->shs.callbacks.save.a);
+
+    r = libxl__toolstack_save(dss->domid, &toolstack_data_buf,
+                              &toolstack_data_len, dss);

This seems to be called twice? I'm looking at the source after the full series is applied and I see

Quoted 2 lines
        dss->shs.callbacks.save.toolstack_save = libxl__toolstack_save;

in libxl__domain_suspend as well as this call here.

But in fact dss->shs.callbacks.save.toolstack_save is never used anywhere in that version. The bug is that libxl__xc_domain_save should call the callback function (if it is non-null), not call libxl__toolstack_save directly.

Quoted 1 line

The callback one seems to be otherwise unused.

Exactly.

I have fixed this:

* libxl__xc_domain_save uses supplied callback function pointer, rather than calling libxl__toolstack_save directly; toolstack data save callback is only supplied to libxc if in-libxl caller supplied a callback.

Quoted 4 lines
Quoted 4 lines
tools/libxl/libxl_dom.c +4 -0
+static void run_helper(libxl__egc *egc, libxl__save_helper_state *shs,
+                       const char *mode_arg, int data_fd,
+                       const unsigned long *argnums, int num_argnums)
+{

...

Quoted 7 lines

tools/libxl/libxl_dom.c

Quoted 6 lines
tools/libxl/libxl_dom.c +6 -0
+    libxl__carefd_begin();
+    for (i=0; i<2; i++) {
+        int fds[2];
+        if (libxl_pipe(CTX,fds)) { rc = ERROR_FAIL; goto out; }
+        childs_pipes[i] = libxl__carefd_record(CTX, fds[i]);
+        shs->pipes[i] = libxl__carefd_record(CTX, fds[!i]);
Quoted 7 lines

Using !i here is clever, but I had to deploy a pen to be sure the assignments were all correct.

Open coding this simple loop would also give you the opportunity the have comments like "/* This is the helper processes's stdout */" etc in the appropriate place to aid in comprehension when checking the correct end of each pipe goes in the right place.

Perhaps the right answer is to use a better variable name than `i'. I wrote it out longhand and it looked like this:

    libxl__carefd_begin();
    int fds[2];

    /* child's stdin */
    if (libxl_pipe(CTX,fds)) { rc = ERROR_FAIL; goto out; }
    childs_pipes[0] = libxl__carefd_record(CTX, fds[0]);
    shs->pipes[0] = libxl__carefd_record(CTX, fds[1]);

    /* child's stdout */
    if (libxl_pipe(CTX,fds)) { rc = ERROR_FAIL; goto out; }
    childs_pipes[1] = libxl__carefd_record(CTX, fds[1]);
    shs->pipes[1] = libxl__carefd_record(CTX, fds[0]);

    libxl__carefd_unlock();

which is a great way to obscure the subtle differences between the two stanzas. How about:

    libxl__carefd_begin();
    int childfd;
    for (childfd=0; childfd<2; childfd++) {
        /* Setting up the pipe for the child's fd childfd */
        int fds[2];
        if (libxl_pipe(CTX,fds)) { rc = ERROR_FAIL; goto out; }
        int childs_end = childfd==0 ? 0 /*read*/  : 1 /*write*/;
        int our_end    = childfd==0 ? 1 /*write*/ : 0 /*read*/;
        childs_pipes[childfd] = libxl__carefd_record(CTX, fds[childs_end]);
        shs->pipes[childfd] =   libxl__carefd_record(CTX, fds[our_end]);
    }
    libxl__carefd_unlock();

?

Quoted 12 lines

tools/libxl/libxl_dom.c

Quoted 9 lines
tools/libxl/libxl_dom.c +9 -0
+static void helper_stdout_readable(libxl__egc *egc, libxl__ev_fd *ev,
+                                   int fd, short events, short revents)
+{
+    libxl__save_helper_state *shs = CONTAINER_OF(ev, *shs, readable);
+    STATE_AO_GC(shs->ao);
+    int rc, errnoval;
+
+    if (revents & POLLPRI) {
+        LOG(ERROR, "%s signaled POLLERR", shs->stdout_what);

signalled ?

Quoted 2 lines

(it's not impossible that my spell checker is wrong, google seem to think both are ok)

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/kill.html

uses "signaled".

Quoted 1 line

The if says POLLPRI but the log says POLLERR?

This should check and log both.

Quoted 6 lines

tools/libxl/libxl_dom.c

Quoted 3 lines
tools/libxl/libxl_dom.c +3 -0
+        rc = ERROR_FAIL;
+ out:
+        /* this is here because otherwise we bypass the decl of msg[] */

I don't get this comment, why can't "out:" be in the normal place after the non-error return?

Because it is not legal to "goto" within the scope of a variable whose size is not a constant. The alternative would be to introduce a block scope starting before unsigned char msg[msglen]' and ending after return'.

Arguably msg[msglen] is asking too much (up to 64K) of the caller's stack. Should I change it ?

Quoted 5 lines

tools/libxl/libxl_dom.c

Quoted 3 lines
tools/libxl/libxl_dom.c +3 -0
+    if (!shs->completed) {
+        if (!shs->rc)
+            LOG(ERROR,"%s exited without signaling completion",what);

signalling again, same caveat

I'll go with what SuS says.

Quoted 13 lines

tools/libxl/libxl_save_helper.c line 7

Quoted 10 lines
tools/libxl/libxl_save_helper.c new file +7 -0
@@ -0,0 +1,279 @@
+/*
+ * Copyright (C) 2012      Citrix Ltd.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; version 2.1 only. with the special
+ * exception on linking described in file LICENSE.

LGPL, or perhaps GPL since this is a helper?

Quoted 1 line

(I suppose the same argument could be made for xl itself)

I can see no reason to deviate from the licence of the rest of libxl. If nothing else, code may move between the helper and libxl proper.

Quoted 8 lines

tools/libxl/libxl_save_helper.c line 160

Quoted 5 lines
tools/libxl/libxl_save_helper.c new file +5 -0
+int helper_getreply(void *user)
+{
+    int v;
+    int r = read_exactly(0, &v, sizeof(v));
+    if (r<=0) exit(-2);

You use -1 a lot but here you use -2, are we supposed to be able to infer something from the specific error code?

Not really. I used -1 for general system call failures. This particular situation might include a protocol error by the parent, though, so I thought I'd distinguish it. That way if you get a message saying the helper exited with a nonzero exit status foobar you get slightly more information.

I could make this more formal and be more consistent with these exit statuses, or alternatively I could abolish it. I don't think it's critical - nothing turns on this exit status.

Quoted 16 lines

tools/libxl/libxl_save_msgs_gen.pl line 7

Quoted 13 lines
tools/libxl/libxl_save_msgs_gen.pl new file +7 -0
new file mode 100755
index 0000000..cd0837e
@@ -0,0 +1,393 @@
+#!/usr/bin/perl -w
+
+use warnings;
+use strict;
+use POSIX;
+
+our $debug = 0; # produce copius debugging output at run-time?

copious

Quoted 2 lines

(which is probably the most useful feedback you are going to get from me on a Perl script ;-))

Fixed.

Quoted 10 lines
Quoted 2 lines
tools/libxl/libxl_save_msgs_gen.pl new file +2 -0
+foreach my $ah (qw(callout helper)) {
+    $out_body{$ah} .= <<END.($ah eq 'callout' ? <<END : <<END);

[...]

Quoted 1 line

+END

[...]

Quoted 1 line

+END

[...]

Quoted 1 line

+END

I think I can infer what this does, but wow ;-)

Following a suggestion from Mark Wooding I have changed this to:

          <<END_BOTH.($ah eq 'callout' ? <<END_CALLOUT : <<END_HELPER);

#include "libxl_osdeps.h"

  #include <assert.h>
  #include <string.h>
  #include <stdint.h>
  #include <limits.h>
  END_BOTH

  #include "libxl_internal.h"

END_CALLOUT

  #include "_libxl_save_msgs_${ah}.h"
  #include <xenctrl.h>
  #include <xenguest.h>

END_HELPER

which I think is much clearer.

Ian.

#18 lore raw
Quoted 13 lines
Quoted 12 lines
Quoted 2 lines

testidl: testidl.o libxlutil.so libxenlight.so

        $(CC) $(LDFLAGS) -o $@ testidl.o libxlutil.so $(LDLIBS_libxenlight) $(LDLIBS_libxenctrl) $(APPEND_LDFLAGS)

[...]

tools/libxl/Makefile install: all · line 187

Quoted 5 lines
tools/libxl/Makefile +1 -0
@@ -170,6 +184,7 @@ install: all
        $(INSTALL_DIR) $(DESTDIR)$(BASH_COMPLETION_DIR)
        $(INSTALL_DIR) $(DESTDIR)$(XEN_RUN_DIR)
        $(INSTALL_PROG) xl $(DESTDIR)$(SBINDIR)
+       $(INSTALL_PROG) libxl-save-helper $(DESTDIR)$(PRIVATE_BINDIR)

This needs an INSTALL_DIR for $(DESTDIR)$(PRIVATE_BINDIR) to support
"make -C tools/libxl DESTDIR=xxx install" else:
install: cannot create regular file `/tmp/tmplKa0Y7/usr/lib/xen/bin': No such file or directory

Quoted 3 lines

OK. I guess I never do that and it's a bit of a mystery why one would without having done a more general install before, but it's clearly a correct change.

I build and install on a different machine, which means I install into DESTDIR=mkdtemp ... and tar, copy etc. I do one full build to seed everything and then incrementally just the dir I'm working in, so this hits me because on the incremental ones the fresh DESTDIR doesn't have the directory yet.

Quoted 6 lines
Quoted 3 lines
Quoted 3 lines
tools/libxl/libxl_dom.c +0 -0
index b48452c..fea0c94 100644

...

Quoted 2 lines
Quoted 2 lines

int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
- uint32_t size, void *data)

Quoted 8 lines

...

Quoted 3 lines
Quoted 1 line

+ libxl_ctx *ctx = CTX;

Any reason you didn't s/ctx/CTX/ in one of your preparatory patches?

I didn't want to do that unless it was necessary. There was already enough else going on. I don't think having a ctx rather than using CTX is wrong, although it is slightly less in the modern idiom.

Fair enough.

Quoted 28 lines
Quoted 20 lines
Quoted 7 lines

void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_suspend_state *dss,
unsigned long vm_generationid_addr)

 {
     STATE_AO_GC(dss->ao);
tools/libxl/libxl_dom.c +1 -1
-    int r;
+    int r, rc;

tools/libxl/libxl_dom.c

Quoted 10 lines
tools/libxl/libxl_dom.c +10 -0
+    uint32_t toolstack_data_len;
+
+    /* Resources we need to free */
+    uint8_t *toolstack_data_buf = 0;
+
+    unsigned cbflags = libxl__srm_callout_enumcallbacks_save
+        (&dss->shs.callbacks.save.a);
+
+    r = libxl__toolstack_save(dss->domid, &toolstack_data_buf,
+                              &toolstack_data_len, dss);

This seems to be called twice? I'm looking at the source after the full series is applied and I see

Quoted 2 lines
        dss->shs.callbacks.save.toolstack_save = libxl__toolstack_save;

in libxl__domain_suspend as well as this call here.

But in fact dss->shs.callbacks.save.toolstack_save is never used anywhere in that version. The bug is that libxl__xc_domain_save should call the callback function (if it is non-null), not call libxl__toolstack_save directly.

Quoted 7 lines
Quoted 1 line

The callback one seems to be otherwise unused.

Exactly.

I have fixed this:

* libxl__xc_domain_save uses supplied callback function pointer,

                                ^ the ?
Quoted 3 lines

rather than calling libxl__toolstack_save directly; toolstack data save callback is only supplied to libxc if in-libxl caller supplied a callback.

     ^ "the" or "an"?

Otherwise looks good.

Quoted 22 lines
Quoted 4 lines
Quoted 4 lines
tools/libxl/libxl_dom.c +4 -0
+static void run_helper(libxl__egc *egc, libxl__save_helper_state *shs,
+                       const char *mode_arg, int data_fd,
+                       const unsigned long *argnums, int num_argnums)
+{

...

Quoted 7 lines

tools/libxl/libxl_dom.c

Quoted 6 lines
tools/libxl/libxl_dom.c +6 -0
+    libxl__carefd_begin();
+    for (i=0; i<2; i++) {
+        int fds[2];
+        if (libxl_pipe(CTX,fds)) { rc = ERROR_FAIL; goto out; }
+        childs_pipes[i] = libxl__carefd_record(CTX, fds[i]);
+        shs->pipes[i] = libxl__carefd_record(CTX, fds[!i]);
Quoted 7 lines

Using !i here is clever, but I had to deploy a pen to be sure the assignments were all correct.

Open coding this simple loop would also give you the opportunity the have comments like "/* This is the helper processes's stdout */" etc in the appropriate place to aid in comprehension when checking the correct end of each pipe goes in the right place.

Perhaps the right answer is to use a better variable name than `i'. I wrote it out longhand and it looked like this:

[...]

Quoted 16 lines

which is a great way to obscure the subtle differences between the two stanzas. How about:

    libxl__carefd_begin();
    int childfd;
    for (childfd=0; childfd<2; childfd++) {
        /* Setting up the pipe for the child's fd childfd */
        int fds[2];
        if (libxl_pipe(CTX,fds)) { rc = ERROR_FAIL; goto out; }
        int childs_end = childfd==0 ? 0 /*read*/  : 1 /*write*/;
        int our_end    = childfd==0 ? 1 /*write*/ : 0 /*read*/;
        childs_pipes[childfd] = libxl__carefd_record(CTX, fds[childs_end]);
        shs->pipes[childfd] =   libxl__carefd_record(CTX, fds[our_end]);
    }
    libxl__carefd_unlock();
Quoted 1 line

?

Yes renaming that variable, adding those inline /*read*/ etc comments and the local variable naming has really helped, thanks

Quoted 9 lines
Quoted 6 lines

tools/libxl/libxl_dom.c

Quoted 3 lines
tools/libxl/libxl_dom.c +3 -0
+        rc = ERROR_FAIL;
+ out:
+        /* this is here because otherwise we bypass the decl of msg[] */

I don't get this comment, why can't "out:" be in the normal place after the non-error return?

Because it is not legal to "goto" within the scope of a variable whose size is not a constant.

Ah OK, I didn't realise this, another interesting C quirk!

Quoted 6 lines

The alternative would be to introduce a block
scope starting before unsigned char msg[msglen]' and ending after return'.

Arguably msg[msglen] is asking too much (up to 64K) of the caller's stack. Should I change it ?

I think it's OK in a userspace process.

Although one thing to watch out for would be the stack guard page which modern Linux has -- this can cause issues with large stack allocations since you trigger the guard page instead of growing the stack like you'd expect -- I suppose this is really a bug in your compiler and/or libc but it does seem common enough to avoid for now...

Quoted 13 lines
Quoted 13 lines

tools/libxl/libxl_save_helper.c line 7

Quoted 10 lines
tools/libxl/libxl_save_helper.c new file +7 -0
@@ -0,0 +1,279 @@
+/*
+ * Copyright (C) 2012      Citrix Ltd.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; version 2.1 only. with the special
+ * exception on linking described in file LICENSE.

LGPL, or perhaps GPL since this is a helper?

Quoted 4 lines
Quoted 1 line

(I suppose the same argument could be made for xl itself)

I can see no reason to deviate from the licence of the rest of libxl. If nothing else, code may move between the helper and libxl proper.

That's a very good point.

Quoted 16 lines
Quoted 9 lines

tools/libxl/libxl_save_helper.c line 160

Quoted 6 lines
tools/libxl/libxl_save_helper.c new file +5 -0
+int helper_getreply(void *user)
+{
+    int v;
+    int r = read_exactly(0, &v, sizeof(v));
+    if (r<=0) exit(-2);

You use -1 a lot but here you use -2, are we supposed to be able to infer something from the specific error code?

Not really. I used -1 for general system call failures. This particular situation might include a protocol error by the parent, though, so I thought I'd distinguish it. That way if you get a message saying the helper exited with a nonzero exit status foobar you get slightly more information.

Quoted 3 lines

I could make this more formal and be more consistent with these exit statuses, or alternatively I could abolish it. I don't think it's critical - nothing turns on this exit status.

Lets just leave it then.

Quoted 26 lines
Quoted 10 lines
Quoted 2 lines
tools/libxl/libxl_save_helper.c new file +2 -0
+foreach my $ah (qw(callout helper)) {
+    $out_body{$ah} .= <<END.($ah eq 'callout' ? <<END : <<END);

[...]

Quoted 1 line

+END

[...]

Quoted 1 line

+END

[...]

Quoted 1 line

+END

I think I can infer what this does, but wow ;-)

Following a suggestion from Mark Wooding I have changed this to:

          <<END_BOTH.($ah eq 'callout' ? <<END_CALLOUT : <<END_HELPER);

#include "libxl_osdeps.h"

  #include <assert.h>
  #include <string.h>
  #include <stdint.h>
  #include <limits.h>
  END_BOTH

  #include "libxl_internal.h"

END_CALLOUT

Quoted 7 lines
  #include "_libxl_save_msgs_${ah}.h"
  #include <xenctrl.h>
  #include <xenguest.h>

END_HELPER

which I think is much clearer.

I agree with Mark, thanks!

Quoted 2 lines

Ian.

#19 lore raw

PATCH 6/19 libxl: rename libxl_dom:save_helper to physmap_path

In reply to Ian Jackson

"save_helper" isn't very descriptive. Also it is now confusing because it reads like it might refer to the libxl-save-helper executable which runs xc_domain_save and xc_domain_restore.

---
 tools/libxl/libxl_dom.c |    8 ++++----
 1 files changed, 4 insertions(+), 4 deletions(-)
tools/libxl/libxl_dom.c +4 -4
index fea0c94..a597627 100644
@@ -734,7 +734,7 @@ int libxl__domain_suspend_common_callback(void *user)
     return 1;
 }
 
-static inline char *save_helper(libxl__gc *gc, uint32_t domid,
+static inline char *physmap_path(libxl__gc *gc, uint32_t domid,
         char *phys_offset, char *node)
 {
     return libxl__sprintf(gc,
@@ -779,21 +779,21 @@ int libxl__toolstack_save(uint32_t domid, uint8_t **buf,
             return -1;
         }
 
-        xs_path = save_helper(gc, domid, phys_offset, "start_addr");
+        xs_path = physmap_path(gc, domid, phys_offset, "start_addr");
         start_addr = libxl__xs_read(gc, 0, xs_path);
         if (start_addr == NULL) {
             LOG(ERROR, "%s is NULL", xs_path);
             return -1;
         }
 
-        xs_path = save_helper(gc, domid, phys_offset, "size");
+        xs_path = physmap_path(gc, domid, phys_offset, "size");
         size = libxl__xs_read(gc, 0, xs_path);
         if (size == NULL) {
             LOG(ERROR, "%s is NULL", xs_path);
             return -1;
         }
 
-        xs_path = save_helper(gc, domid, phys_offset, "name");
+        xs_path = physmap_path(gc, domid, phys_offset, "name");
         name = libxl__xs_read(gc, 0, xs_path);
         if (name == NULL)
             namelen = 0;
Signature · 1 line
1.7.2.5
#20 lore raw

PATCH 7/19 libxl: provide libxl__xs_*_checked and libxl__xs_transaction_*

In reply to Ian Jackson

These useful utility functions make dealing with xenstore a little less painful.

Changes in v3:
* Fixed typo `transacton' in log messages.

---
 tools/libxl/libxl_internal.h |   38 +++++++++++++++++++++
 tools/libxl/libxl_xshelp.c   |   76 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 114 insertions(+), 0 deletions(-)
tools/libxl/libxl_internal.h +38 -0
index dbf7722..4634f5a 100644
@@ -498,6 +498,44 @@ _hidden bool libxl__xs_mkdir(libxl__gc *gc, xs_transaction_t t,
 
 _hidden char *libxl__xs_libxl_path(libxl__gc *gc, uint32_t domid);
 
+
+/*----- "checked" xenstore access functions -----*/
+/* Each of these functions will check that it succeeded; if it
+ * fails it logs and returns ERROR_FAIL.
+ */
+
+/* On success, *result_out came from the gc.
+ * On error, *result_out is undefined.
+ * ENOENT counts as success but sets *result_out=0
+ */
+int libxl__xs_read_checked(libxl__gc *gc, xs_transaction_t t,
+                           const char *path, const char **result_out);
+
+/* Does not include a trailing null.
+ * May usefully be combined with GCSPRINTF if the format string
+ * behaviour of libxl__xs_write is desirable. */
+int libxl__xs_write_checked(libxl__gc *gc, xs_transaction_t t,
+                            const char *path, const char *string);
+
+/* ENOENT is not an error (even if the parent directories don't exist) */
+int libxl__xs_rm_checked(libxl__gc *gc, xs_transaction_t t, const char *path);
+
+/* Transaction functions, best used together.
+ * The caller should initialise *t to 0 (XBT_NULL) before calling start.
+ * Each function leaves *t!=0 iff the transaction needs cleaning up.
+ *
+ * libxl__xs_transaction_commit returns:
+ *   <0  failure - a libxl error code
+ *   +1  commit conflict; transaction has been destroyed and caller
+ *        must go round again (call _start again and retry)
+ *    0  commited successfully
+ */
+int libxl__xs_transaction_start(libxl__gc *gc, xs_transaction_t *t);
+int libxl__xs_transaction_commit(libxl__gc *gc, xs_transaction_t *t);
+void libxl__xs_transaction_abort(libxl__gc *gc, xs_transaction_t *t);
+
+
+
 /*
  * This is a recursive delete, from top to bottom. What this function does
  * is remove empty folders that contained the deleted entry.
tools/libxl/libxl_xshelp.c +76 -0

82 lines not on this page · raw message

Signature · 1 line
1.7.2.5
Acked-by on v1 7/19
#21 lore raw

Re: [PATCH 07/19] libxl: provide libxl__xs_*_checked and libxl__xs_transaction_*

Quoted 4 lines · Ian Jackson

These useful utility functions make dealing with xenstore a little less painful.

(minor observation and a typo below)

[...]

tools/libxl/libxl_internal.h _hidden bool libxl__xs_mkdir(libxl__gc *gc, xs_transaction_t t, · line 518

Quoted 12 lines
tools/libxl/libxl_internal.h +12 -0
+/* On success, *result_out came from the gc.
+ * On error, *result_out is undefined.
+ * ENOENT counts as success but sets *result_out=0
+ */
+int libxl__xs_read_checked(libxl__gc *gc, xs_transaction_t t,
+                           const char *path, const char **result_out);
+
+/* Does not include a trailing null.
+ * May usefully be combined with GCSPRINTF if the format string
+ * behaviour of libxl__xs_write is desirable. */
+int libxl__xs_write_checked(libxl__gc *gc, xs_transaction_t t,
+                            const char *path, const char *string);

I suppose in the future we might consider merging this with libxl__xs_write -- there's no reason not to always log a failed write, is there?

tools/libxl/libxl_internal.h _hidden bool libxl__xs_mkdir(libxl__gc *gc, xs_transaction_t t, · line 531

Quoted 13 lines
tools/libxl/libxl_internal.h +13 -0
+
+/* ENOENT is not an error (even if the parent directories don't exist) */
+int libxl__xs_rm_checked(libxl__gc *gc, xs_transaction_t t, const char *path);
+
+/* Transaction functions, best used together.
+ * The caller should initialise *t to 0 (XBT_NULL) before calling start.
+ * Each function leaves *t!=0 iff the transaction needs cleaning up.
+ *
+ * libxl__xs_transaction_commit returns:
+ *   <0  failure - a libxl error code
+ *   +1  commit conflict; transaction has been destroyed and caller
+ *        must go round again (call _start again and retry)
+ *    0  commited successfully

committed

tools/libxl/libxl_internal.h _hidden bool libxl__xs_mkdir(libxl__gc *gc, xs_transaction_t t, · line 538

Quoted 7 lines

+ */

tools/libxl/libxl_internal.h +6 -0
+int libxl__xs_transaction_start(libxl__gc *gc, xs_transaction_t *t);
+int libxl__xs_transaction_commit(libxl__gc *gc, xs_transaction_t *t);
+void libxl__xs_transaction_abort(libxl__gc *gc, xs_transaction_t *t);
+
+
+

Ian.

#22 lore raw

Re: [PATCH 07/19] libxl: provide libxl__xs_*_checked and libxl__xs_transaction_*

Ian Campbell writes ("Re: [Xen-devel] [PATCH 07/19] libxl: provide libxl__xs_*_checked and libxl__xs_transaction_*"):

Quoted 7 lines · Ian Jackson
Quoted 4 lines

These useful utility functions make dealing with xenstore a little less painful.

Thanks.

Quoted 1 line

(minor observation and a typo below)

...

Quoted 6 lines

tools/libxl/libxl_internal.h _hidden bool libxl__xs_mkdir(libxl__gc *gc, xs_transaction_t t, · line 518

Quoted 2 lines
tools/libxl/libxl_internal.h +2 -0
+int libxl__xs_write_checked(libxl__gc *gc, xs_transaction_t t,
+                            const char *path, const char *string);

I suppose in the future we might consider merging this with libxl__xs_write -- there's no reason not to always log a failed write, is there?

Maybe. It might fail due to EPERM and there might be another strategy the caller might have available. Although this is rare enough that perhaps such callers should use raw xs calls.

Arguably the same applies to read.

Quoted 3 lines
Quoted 1 line

+ * 0 commited successfully

committed

Fixed.

Ian.

#23 lore raw

PATCH 8/19 libxl: wait for qemu to acknowledge logdirty command

In reply to Ian Jackson

The current migration code in libxl instructs qemu to start or stop logdirty, but it does not wait for an acknowledgement from qemu before continuing. This might lead to memory corruption (!)

Fix this by waiting for qemu to acknowledge the command.

Unfortunately the necessary ao arrangements for waiting for this command are unique because qemu has a special protocol for this particular operation.

Also, this change means that the switch_qemu_logdirty callback implementation in libxl can no longer synchronously produce its return value, as it now needs to wait for xenstore. So we tell the marshalling code generator that it is a message which does not need a reply. This turns the callback function called by the marshaller into one which returns void; the callback function arranges to later explicitly sends the reply to the helper, when the xs watch triggers and the appropriate value is read from xenstore.

---
 tools/libxl/libxl_dom.c            |  176 +++++++++++++++++++++++++++++++++---
 tools/libxl/libxl_internal.h       |   18 ++++-
 tools/libxl/libxl_save_callout.c   |    8 ++
 tools/libxl/libxl_save_msgs_gen.pl |    7 +-
 4 files changed, 193 insertions(+), 16 deletions(-)
tools/libxl/libxl_dom.c +164 -12
index a597627..d5ac79f 100644
@@ -528,30 +528,180 @@ int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
 static void domain_suspend_done(libxl__egc *egc,
                         libxl__domain_suspend_state *dss, int rc);
 
-/*----- callbacks, called by xc_domain_save -----*/
+/*----- complicated callback, called by xc_domain_save -----*/
+
+/*
+ * We implement the other end of protocol for controlling qemu-dm's
+ * logdirty.  There is no documentation for this protocol, but our
+ * counterparty's implementation is in
+ * qemu-xen-traditional.git:xenstore.c in the function
+ * xenstore_process_logdirty_event
+ */
+
+static void switch_logdirty_timeout(libxl__egc *egc, libxl__ev_time *ev,
+                                    const struct timeval *requested_abs);
+static void switch_logdirty_xswatch(libxl__egc *egc, libxl__ev_xswatch*,
+                            const char *watch_path, const char *event_path);
+static void switch_logdirty_done(libxl__egc *egc,
+                                 libxl__domain_suspend_state *dss, int ok);
 
-int libxl__domain_suspend_common_switch_qemu_logdirty
+static void logdirty_init(libxl__logdirty_switch *lds)
+{
+    lds->cmd_path = 0;
+    libxl__ev_xswatch_init(&lds->watch);
+    libxl__ev_time_init(&lds->timeout);
+}
+
+void libxl__domain_suspend_common_switch_qemu_logdirty
                                (int domid, unsigned enable, void *user)
 {
     libxl__save_helper_state *shs = user;
+    libxl__egc *egc = shs->egc;
     libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
+    libxl__logdirty_switch *lds = &dss->logdirty;
     STATE_AO_GC(dss->ao);
-    char *path;
-    bool rc;
+    int rc;
+    xs_transaction_t t = 0;
+    const char *got;
 
-    path = libxl__sprintf(gc,
+    if (!lds->cmd_path) {
+        lds->cmd_path = GCSPRINTF(
                    "/local/domain/0/device-model/%u/logdirty/cmd", domid);
-    if (!path)
-        return 1;
+        lds->ret_path = GCSPRINTF(
+                   "/local/domain/0/device-model/%u/logdirty/ret", domid);
+    }
+    lds->cmd = enable ? "enable" : "disable";
 
-    if (enable)
-        rc = xs_write(CTX->xsh, XBT_NULL, path, "enable", strlen("enable"));
-    else
-        rc = xs_write(CTX->xsh, XBT_NULL, path, "disable", strlen("disable"));
+    rc = libxl__ev_xswatch_register(gc, &lds->watch,
+                                switch_logdirty_xswatch, lds->ret_path);
+    if (rc) goto out;
+
+    rc = libxl__ev_time_register_rel(gc, &lds->timeout,
+                                switch_logdirty_timeout, 10*1000);
+    if (rc) goto out;
+
+    for (;;) {
+        rc = libxl__xs_transaction_start(gc, &t);
+        if (rc) goto out;
+
+        rc = libxl__xs_read_checked(gc, t, lds->cmd_path, &got);
+        if (rc) goto out;
+
+        if (got) {
+            const char *got_ret;
+            rc = libxl__xs_read_checked(gc, t, lds->ret_path, &got_ret);
+            if (rc) goto out;
 
-    return rc ? 0 : 1;
+            if (strcmp(got, got_ret)) {
+                LOG(ERROR,"controlling logdirty: qemu was already sent"
+                    " command `%s' (xenstore path `%s') but result is `%s'",
+                    got, lds->cmd_path, got_ret ? got_ret : "<none>");
+                rc = ERROR_FAIL;
+                goto out;
+            }
+            rc = libxl__xs_rm_checked(gc, t, lds->cmd_path);
+            if (rc) goto out;
+        }
+
+        rc = libxl__xs_rm_checked(gc, t, lds->ret_path);
+        if (rc) goto out;
+
+        rc = libxl__xs_write_checked(gc, t, lds->cmd_path, lds->cmd);
+        if (rc) goto out;
+
+        rc = libxl__xs_transaction_commit(gc, &t);
+        if (!rc) break;
+        if (rc<0) goto out;
+    }
+
+    /* OK, wait for some callback */
+    return;
+
+ out:
+    LOG(ERROR,"logdirty switch failed (rc=%d), aborting suspend",rc);
+    switch_logdirty_done(egc,dss,0);
+}
+
+static void switch_logdirty_timeout(libxl__egc *egc, libxl__ev_time *ev,
+                                    const struct timeval *requested_abs)
+{
+    libxl__domain_suspend_state *dss = CONTAINER_OF(ev, *dss, logdirty.timeout);
+    STATE_AO_GC(dss->ao);
+    LOG(ERROR,"logdirty switch: wait for device model timed out");
+    switch_logdirty_done(egc,dss,0);
 }
 
+static void switch_logdirty_xswatch(libxl__egc *egc, libxl__ev_xswatch *watch,
+                            const char *watch_path, const char *event_path)
+{
+    libxl__domain_suspend_state *dss =
+        CONTAINER_OF(watch, *dss, logdirty.watch);
+    libxl__logdirty_switch *lds = &dss->logdirty;
+    STATE_AO_GC(dss->ao);
+    const char *got;
+    xs_transaction_t t = 0;
+    int rc;
+
+    for (;;) {
+        rc = libxl__xs_transaction_start(gc, &t);
+        if (rc) goto out;
+
+        rc = libxl__xs_read_checked(gc, t, lds->ret_path, &got);
+        if (rc) goto out;
+
+        if (!got) {
+            rc = +1;
+            goto out;
+        }
+
+        if (strcmp(got, lds->cmd)) {
+            LOG(ERROR,"logdirty switch: sent command `%s' but got reply `%s'"
+                " (xenstore paths `%s' / `%s')", lds->cmd, got,
+                lds->cmd_path, lds->ret_path);
+            rc = ERROR_FAIL;
+            goto out;
+        }
+
+        rc = libxl__xs_rm_checked(gc, t, lds->cmd_path);
+        if (rc) goto out;
+
+        rc = libxl__xs_rm_checked(gc, t, lds->ret_path);
+        if (rc) goto out;
+
+        rc = libxl__xs_transaction_commit(gc, &t); 
+        if (!rc) break;
+        if (rc<0) goto out;
+    }
+
+ out:
+    /* rc < 0: error
+     * rc == 0: ok, we are done
+     * rc == +1: need to keep waiting
+     */
+    libxl__xs_transaction_abort(gc, &t);
+
+    if (!rc) {
+        switch_logdirty_done(egc,dss,1);
+    } else if (rc < 0) {
+        LOG(ERROR,"logdirty switch: response read failed (rc=%d)",rc);
+        switch_logdirty_done(egc,dss,0);
+    }
+}
+
+static void switch_logdirty_done(libxl__egc *egc,
+                                 libxl__domain_suspend_state *dss, int ok)
+{
+    STATE_AO_GC(dss->ao);
+    libxl__logdirty_switch *lds = &dss->logdirty;
+
+    libxl__ev_xswatch_deregister(gc, &lds->watch);
+    libxl__ev_time_deregister(gc, &lds->timeout);
+
+    libxl__xc_domain_saverestore_async_callback_done(egc, &dss->shs, ok);
+}
+
+/*----- callbacks, called by xc_domain_save -----*/
+
 int libxl__domain_suspend_device_model(libxl__gc *gc, uint32_t domid)
 {
     libxl_ctx *ctx = libxl__gc_owner(gc);
@@ -873,6 +1023,8 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
     libxl__srm_save_autogen_callbacks *const callbacks =
         &dss->shs.callbacks.save.a;
 
+    logdirty_init(&dss->logdirty);
+
     switch (type) {
     case LIBXL_DOMAIN_TYPE_HVM: {
         char *path;
tools/libxl/libxl_internal.h +17 -1
index 4634f5a..3b4d250 100644
@@ -1864,6 +1864,14 @@ typedef struct libxl__domain_suspend_state libxl__domain_suspend_state;
 typedef void libxl__domain_suspend_cb(libxl__egc*,
                                       libxl__domain_suspend_state*, int rc);
 
+typedef struct libxl__logdirty_switch {
+    const char *cmd;
+    const char *cmd_path;
+    const char *ret_path;
+    libxl__ev_xswatch watch;
+    libxl__ev_time timeout;
+} libxl__logdirty_switch;
+
 struct libxl__domain_suspend_state {
     /* set by caller of libxl__domain_suspend */
     libxl__ao *ao;
@@ -1883,6 +1891,7 @@ struct libxl__domain_suspend_state {
     int guest_responded;
     int interval; /* checkpoint interval (for Remus) */
     libxl__save_helper_state shs;
+    libxl__logdirty_switch logdirty;
 };
 
 
@@ -2013,8 +2022,15 @@ _hidden void libxl__xc_domain_save(libxl__egc*, libxl__domain_suspend_state*,
 _hidden void libxl__xc_domain_save_done(libxl__egc*, void *dss_void,
                                         int rc, int retval, int errnoval);
 
+/* Used by asynchronous callbacks: ie ones which xc regards as
+ * returning a value, but which we want to handle asynchronously.
+ * Such functions' actual callback function return void in libxl
+ * When they are ready to indicate completion, they call this. */
+void libxl__xc_domain_saverestore_async_callback_done(libxl__egc *egc,
+                           libxl__save_helper_state *shs, int return_value);
+
 _hidden int libxl__domain_suspend_common_callback(void *data);
-_hidden int libxl__domain_suspend_common_switch_qemu_logdirty
+_hidden void libxl__domain_suspend_common_switch_qemu_logdirty
                                (int domid, unsigned int enable, void *data);
 _hidden int libxl__toolstack_save(uint32_t domid, uint8_t **buf,
         uint32_t *len, void *data);
tools/libxl/libxl_save_callout.c +8 -0
index a39f434..ded311c 100644
@@ -128,6 +128,14 @@ void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_suspend_state *dss,
 }
 
 
+void libxl__xc_domain_saverestore_async_callback_done(libxl__egc *egc,
+                           libxl__save_helper_state *shs, int return_value)
+{
+    shs->egc = egc;
+    libxl__srm_callout_sendreply(return_value, shs);
+    shs->egc = 0;
+}
+
 /*----- helper execution -----*/
 
 static void run_helper(libxl__egc *egc, libxl__save_helper_state *shs,
tools/libxl/libxl_save_msgs_gen.pl +4 -3
index cd0837e..8832c46 100755
@@ -14,6 +14,7 @@ our @msgs = (
     #   x  - function pointer is in struct {save,restore}_callbacks
     #         and its null-ness needs to be passed through to the helper's xc
     #   W  - needs a return value; callback is synchronous
+    #   A  - needs a return value; callback is asynchronous
     [  1, 'sr',     "log",                   [qw(uint32_t level
                                                  uint32_t errnoval
                                                  STRING context
@@ -25,7 +26,7 @@ our @msgs = (
     [  3, 'scxW',   "suspend", [] ],         
     [  4, 'scxW',   "postcopy", [] ],        
     [  5, 'scxW',   "checkpoint", [] ],      
-    [  6, 'scxW',   "switch_qemu_logdirty",  [qw(int domid
+    [  6, 'scxA',   "switch_qemu_logdirty",  [qw(int domid
                                               unsigned enable)] ],
     #                toolstack_save          done entirely `by hand'
     [  7, 'rcxW',   "toolstack_restore",     [qw(uint32_t domid
@@ -260,7 +261,7 @@ foreach my $msginfo (@msgs) {
         $f_more_sr->("        int r;\n");
     }
 
-    my $c_rtype_helper = $flags =~ m/W/ ? 'int' : 'void';
+    my $c_rtype_helper = $flags =~ m/[WA]/ ? 'int' : 'void';
     my $c_rtype_callout = $flags =~ m/W/ ? 'int' : 'void';
     my $c_decl = '(';
     my $c_callback_args = '';
@@ -348,7 +349,7 @@ END
     assert(len == allocd);
     ${transmit}(buf, len, user);
 ");
-    if ($flags =~ m/W/) {
+    if ($flags =~ m/[WA]/) {
 	f_more("${encode}_$name", (<<END.($debug ? <<END : '').<<END));
     int r = ${helper}_getreply(user);
 END
Signature · 1 line
1.7.2.5
Acked-by on v1 8/19
#24 lore raw

Re: [PATCH 08/19] libxl: wait for qemu to acknowledge logdirty command

Quoted 49 lines · Ian Jackson

The current migration code in libxl instructs qemu to start or stop logdirty, but it does not wait for an acknowledgement from qemu before continuing. This might lead to memory corruption (!)

Fix this by waiting for qemu to acknowledge the command.

Unfortunately the necessary ao arrangements for waiting for this command are unique because qemu has a special protocol for this particular operation.

Also, this change means that the switch_qemu_logdirty callback implementation in libxl can no longer synchronously produce its return value, as it now needs to wait for xenstore. So we tell the marshalling code generator that it is a message which does not need a reply. This turns the callback function called by the marshaller into one which returns void; the callback function arranges to later explicitly sends the reply to the helper, when the xs watch triggers and the appropriate value is read from xenstore.

---
 tools/libxl/libxl_dom.c            |  176 +++++++++++++++++++++++++++++++++---
 tools/libxl/libxl_internal.h       |   18 ++++-
 tools/libxl/libxl_save_callout.c   |    8 ++
 tools/libxl/libxl_save_msgs_gen.pl |    7 +-
 4 files changed, 193 insertions(+), 16 deletions(-)
tools/libxl/libxl_dom.c +13 -1
index a597627..d5ac79f 100644
@@ -528,30 +528,180 @@ int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
 static void domain_suspend_done(libxl__egc *egc,
                         libxl__domain_suspend_state *dss, int rc);
 
-/*----- callbacks, called by xc_domain_save -----*/
+/*----- complicated callback, called by xc_domain_save -----*/
+
+/*
+ * We implement the other end of protocol for controlling qemu-dm's
+ * logdirty.  There is no documentation for this protocol, but our
+ * counterparty's implementation is in
+ * qemu-xen-traditional.git:xenstore.c in the function
+ * xenstore_process_logdirty_event
+ */
+
+static void switch_logdirty_timeout(libxl__egc *egc, libxl__ev_time *ev,
+                                    const struct timeval *requested_abs);
+static void switch_logdirty_xswatch(libxl__egc *egc, libxl__ev_xswatch*,

tools/libxl/libxl_dom.c int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf, · line 552

Quoted 10 lines
tools/libxl/libxl_dom.c +8 -1
+                            const char *watch_path, const char *event_path);
+static void switch_logdirty_done(libxl__egc *egc,
+                                 libxl__domain_suspend_state *dss, int ok);
 
-int libxl__domain_suspend_common_switch_qemu_logdirty
+static void logdirty_init(libxl__logdirty_switch *lds)
+{
+    lds->cmd_path = 0;
+    libxl__ev_xswatch_init(&lds->watch);
+    libxl__ev_time_init(&lds->timeout);

I meant to mention this once before when reviewing some patch or other but I'm not sure I actually did, so at the risk of repeating myself:

This watch with timeout pattern seems to be reasonably common (in fact, I'm not sure we have any watches without a timeout). It might be a candidate for a specific helper routine in the future?

[...]

Quoted 52 lines
tools/libxl/libxl_dom.c +50 -0
+static void switch_logdirty_timeout(libxl__egc *egc, libxl__ev_time *ev,
+                                    const struct timeval *requested_abs)
+{
+    libxl__domain_suspend_state *dss = CONTAINER_OF(ev, *dss, logdirty.timeout);
+    STATE_AO_GC(dss->ao);
+    LOG(ERROR,"logdirty switch: wait for device model timed out");
+    switch_logdirty_done(egc,dss,0);
 }
 
+static void switch_logdirty_xswatch(libxl__egc *egc, libxl__ev_xswatch *watch,
+                            const char *watch_path, const char *event_path)
+{
+    libxl__domain_suspend_state *dss =
+        CONTAINER_OF(watch, *dss, logdirty.watch);
+    libxl__logdirty_switch *lds = &dss->logdirty;
+    STATE_AO_GC(dss->ao);
+    const char *got;
+    xs_transaction_t t = 0;
+    int rc;
+
+    for (;;) {
+        rc = libxl__xs_transaction_start(gc, &t);
+        if (rc) goto out;
+
+        rc = libxl__xs_read_checked(gc, t, lds->ret_path, &got);
+        if (rc) goto out;
+
+        if (!got) {
+            rc = +1;
+            goto out;
+        }
+
+        if (strcmp(got, lds->cmd)) {
+            LOG(ERROR,"logdirty switch: sent command `%s' but got reply `%s'"
+                " (xenstore paths `%s' / `%s')", lds->cmd, got,
+                lds->cmd_path, lds->ret_path);
+            rc = ERROR_FAIL;
+            goto out;
+        }
+
+        rc = libxl__xs_rm_checked(gc, t, lds->cmd_path);
+        if (rc) goto out;
+
+        rc = libxl__xs_rm_checked(gc, t, lds->ret_path);
+        if (rc) goto out;
+
+        rc = libxl__xs_transaction_commit(gc, &t);
+        if (!rc) break;
+        if (rc<0) goto out;
+    }
+
+ out:

tools/libxl/libxl_dom.c int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf, · line 686

Quoted 10 lines
tools/libxl/libxl_dom.c +10 -0
+    /* rc < 0: error
+     * rc == 0: ok, we are done
+     * rc == +1: need to keep waiting
+     */
+    libxl__xs_transaction_abort(gc, &t);
+
+    if (!rc) {
+        switch_logdirty_done(egc,dss,1);
+    } else if (rc < 0) {
+        LOG(ERROR,"logdirty switch: response read failed (rc=%d)",rc);

Is it only "response read failed" which can cause us to end up here, looks like the read, rm etc could do it?

Anyway, I've got no substantive comments so:

Quoted 3 lines
tools/libxl/libxl_dom.c +3 -0
+        switch_logdirty_done(egc,dss,0);
+    }
+}

[...]

#25 lore raw

Re: [PATCH 08/19] libxl: wait for qemu to acknowledge logdirty command

Ian Campbell writes ("Re: [Xen-devel] [PATCH 08/19] libxl: wait for qemu to acknowledge logdirty command"):

Quoted 4 lines · Ian Jackson
Quoted 3 lines

The current migration code in libxl instructs qemu to start or stop logdirty, but it does not wait for an acknowledgement from qemu before continuing. This might lead to memory corruption (!)

...

Quoted 9 lines

tools/libxl/libxl_dom.c int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf, · line 552

Quoted 5 lines
tools/libxl/libxl_dom.c +5 -0
+static void logdirty_init(libxl__logdirty_switch *lds)
+{
+    lds->cmd_path = 0;
+    libxl__ev_xswatch_init(&lds->watch);
+    libxl__ev_time_init(&lds->timeout);

I meant to mention this once before when reviewing some patch or other but I'm not sure I actually did, so at the risk of repeating myself:

Quoted 3 lines

This watch with timeout pattern seems to be reasonably common (in fact, I'm not sure we have any watches without a timeout). It might be a candidate for a specific helper routine in the future?

Perhaps. We should think about this. I'm not sure it's necessary now. The benefit might be relatively small, as the callback function would more complicated. Perhaps we should integrate the single xs read which most of these callers also have.

Quoted 3 lines
Quoted 3 lines
tools/libxl/libxl_dom.c +3 -0
+static void switch_logdirty_xswatch(libxl__egc *egc, libxl__ev_xswatch *watch,
+                            const char *watch_path, const char *event_path)
+{

...

Quoted 12 lines

tools/libxl/libxl_dom.c int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf, · line 686

Quoted 11 lines

+ out:

tools/libxl/libxl_dom.c +10 -0
+    /* rc < 0: error
+     * rc == 0: ok, we are done
+     * rc == +1: need to keep waiting
+     */
+    libxl__xs_transaction_abort(gc, &t);
+
+    if (!rc) {
+        switch_logdirty_done(egc,dss,1);
+    } else if (rc < 0) {
+        LOG(ERROR,"logdirty switch: response read failed (rc=%d)",rc);
Quoted 2 lines

Is it only "response read failed" which can cause us to end up here, looks like the read, rm etc could do it?

Oh yes. I should fix that message. (All of these paths have already logged something already, but another message probably doesn't hurt.)

Thanks,
Ian.

#26 lore raw

Re: [PATCH 08/19] libxl: wait for qemu to acknowledge logdirty command

Quoted 15 lines · Ian Jackson

Ian Campbell writes ("Re: [Xen-devel] [PATCH 08/19] libxl: wait for qemu to acknowledge logdirty command"):

Quoted 4 lines · Ian Jackson
Quoted 3 lines

The current migration code in libxl instructs qemu to start or stop logdirty, but it does not wait for an acknowledgement from qemu before continuing. This might lead to memory corruption (!)

...

Quoted 9 lines

tools/libxl/libxl_dom.c int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf, · line 552

Quoted 5 lines
tools/libxl/libxl_dom.c +5 -0
+static void logdirty_init(libxl__logdirty_switch *lds)
+{
+    lds->cmd_path = 0;
+    libxl__ev_xswatch_init(&lds->watch);
+    libxl__ev_time_init(&lds->timeout);

I meant to mention this once before when reviewing some patch or other but I'm not sure I actually did, so at the risk of repeating myself:

Quoted 5 lines
Quoted 3 lines

This watch with timeout pattern seems to be reasonably common (in fact, I'm not sure we have any watches without a timeout). It might be a candidate for a specific helper routine in the future?

Perhaps. We should think about this.

Yes, I should have said the phrase "4.3" in there somewhere.

Quoted 3 lines

I'm not sure it's necessary
now. The benefit might be relatively small, as the callback function would more complicated.

Could still have two callbacks, and just helpers for the setup & teardown phases?

Quoted 1 line

Perhaps we should integrate the single xs read which most of these callers also have.

You mean pass in the value of the watched key? That's also a possibility.

Quoted 25 lines
Quoted 4 lines
Quoted 4 lines
tools/libxl/libxl_dom.c +3 -0
+static void switch_logdirty_xswatch(libxl__egc *egc, libxl__ev_xswatch *watch,
+                            const char *watch_path, const char *event_path)
+{

...

Quoted 12 lines

tools/libxl/libxl_dom.c int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf, · line 686

Quoted 11 lines

+ out:

tools/libxl/libxl_dom.c +10 -0
+    /* rc < 0: error
+     * rc == 0: ok, we are done
+     * rc == +1: need to keep waiting
+     */
+    libxl__xs_transaction_abort(gc, &t);
+
+    if (!rc) {
+        switch_logdirty_done(egc,dss,1);
+    } else if (rc < 0) {
+        LOG(ERROR,"logdirty switch: response read failed (rc=%d)",rc);
Quoted 2 lines

Is it only "response read failed" which can cause us to end up here, looks like the read, rm etc could do it?

Oh yes. I should fix that message. (All of these paths have already logged something already, but another message probably doesn't hurt.)

Thanks,
Ian.

#27 lore raw

PATCH 9/19 libxl: datacopier: provide "prefix data" facility

In reply to Ian Jackson

This will be used to write the qemu data banner to the save/migration stream.

Changes in v3:
* Clarified and added comments explaining the `immediately' constraint and the lack of a reentrancy/threading hazard.
* Fixed subject line typo.

---
 tools/libxl/libxl_aoutils.c  |   22 ++++++++++++++++++++++
 tools/libxl/libxl_internal.h |    6 ++++++
 2 files changed, 28 insertions(+), 0 deletions(-)
tools/libxl/libxl_aoutils.c +22 -0
index ee0df57..7f8d6d3 100644
@@ -74,6 +74,28 @@ static void datacopier_check_state(libxl__egc *egc, libxl__datacopier_state *dc)
     }
 }
 
+void libxl__datacopier_prefixdata(libxl__egc *egc, libxl__datacopier_state *dc,
+                                  const void *data, size_t len)
+{
+    libxl__datacopier_buf *buf;
+    /*
+     * It is safe for this to be called immediately after _start, as
+     * is documented in the public comment.  _start's caller must have
+     * the ctx locked, so other threads don't get to mess with the
+     * contents, and the fd events cannot happen reentrantly.  So we
+     * are guaranteed to beat the first data from the read fd.
+     */
+
+    assert(len < dc->maxsz - dc->used);
+
+    buf = libxl__zalloc(0, sizeof(*buf) - sizeof(buf->buf) + len);
+    buf->used = len;
+    memcpy(buf->buf, data, len);
+
+    dc->used += len;
+    LIBXL_TAILQ_INSERT_TAIL(&dc->bufs, buf, entry);
+}
+
 static void datacopier_readable(libxl__egc *egc, libxl__ev_fd *ev,
                                 int fd, short events, short revents) {
     libxl__datacopier_state *dc = CONTAINER_OF(ev, *dc, toread);
tools/libxl/libxl_internal.h +6 -0
index 3b4d250..7e0ab11 100644
@@ -1811,6 +1811,12 @@ _hidden void libxl__datacopier_init(libxl__datacopier_state *dc);
 _hidden void libxl__datacopier_kill(libxl__datacopier_state *dc);
 _hidden int libxl__datacopier_start(libxl__datacopier_state *dc);
 
+/* Inserts literal data into the output stream.  The data is copied.
+ * May safely be used only immediately after libxl__datacopier_start
+ * (before the ctx is unlocked).  But may be called multiple times.
+ * NB exceeding maxsz will fail an assertion! */
+_hidden void libxl__datacopier_prefixdata(libxl__egc*, libxl__datacopier_state*,
+                                          const void *data, size_t len);
 
 /*----- Save/restore helper (used by creation and suspend) -----*/
 
Signature · 1 line
1.7.2.5
#29 lore raw

PATCH 10/19 libxl: prepare for asynchronous writing of qemu save file

In reply to Ian Jackson

* Combine the various calls to libxl__device_model_savefile into one at the start of libxl__domain_suspend, storing the result in the dss. Consequently a few functions take a dss instead of some or all of their other arguments.

* Make libxl__domain_save_device_model's API into an asynchronous style which takes a callback. The function is, however, still synchronous; it will be made actually async in the next patch.

* Consequently make libxl__remus_domain_checkpoint_callback into an asynchronous callback.

---
 tools/libxl/libxl_dom.c            |   54 ++++++++++++++++++++++++++----------
 tools/libxl/libxl_internal.h       |   18 ++++++++++--
 tools/libxl/libxl_save_msgs_gen.pl |    2 +-
 3 files changed, 55 insertions(+), 19 deletions(-)
tools/libxl/libxl_dom.c +39 -15
index d5ac79f..3a53f97 100644
@@ -702,11 +702,13 @@ static void switch_logdirty_done(libxl__egc *egc,
 
 /*----- callbacks, called by xc_domain_save -----*/
 
-int libxl__domain_suspend_device_model(libxl__gc *gc, uint32_t domid)
+int libxl__domain_suspend_device_model(libxl__gc *gc,
+                                       libxl__domain_suspend_state *dss)
 {
     libxl_ctx *ctx = libxl__gc_owner(gc);
     int ret = 0;
-    const char *filename = libxl__device_model_savefile(gc, domid);
+    uint32_t const domid = dss->domid;
+    const char *const filename = dss->dm_savefile;
 
     switch (libxl__device_model_version_running(gc, domid)) {
     case LIBXL_DEVICE_MODEL_VERSION_QEMU_XEN_TRADITIONAL: {
@@ -875,7 +877,7 @@ int libxl__domain_suspend_common_callback(void *user)
 
  guest_suspended:
     if (dss->hvm) {
-        ret = libxl__domain_suspend_device_model(gc, dss->domid);
+        ret = libxl__domain_suspend_device_model(gc, dss);
         if (ret) {
             LOG(ERROR, "libxl__domain_suspend_device_model failed ret=%d", ret);
             return 0;
@@ -990,19 +992,32 @@ static int libxl__remus_domain_resume_callback(void *data)
     return 1;
 }
 
-static int libxl__remus_domain_checkpoint_callback(void *data)
+/*----- remus asynchronous checkpoint callback -----*/
+
+static void remus_checkpoint_dm_saved(libxl__egc *egc,
+                                      libxl__domain_suspend_state *dss, int rc);
+
+static void libxl__remus_domain_checkpoint_callback(void *data)
 {
     libxl__domain_suspend_state *dss = data;
+    libxl__egc *egc = dss->shs.egc;
     STATE_AO_GC(dss->ao);
 
     /* This would go into tailbuf. */
-    if (dss->hvm &&
-        libxl__domain_save_device_model(gc, dss->domid, dss->fd))
-        return 0;
+    if (dss->hvm) {
+        libxl__domain_save_device_model(egc, dss, remus_checkpoint_dm_saved);
+    } else {
+        remus_checkpoint_dm_saved(egc, dss, 0);
+    }
+}
 
+static void remus_checkpoint_dm_saved(libxl__egc *egc,
+                                      libxl__domain_suspend_state *dss, int rc)
+{
     /* TODO: Wait for disk and memory ack, release network buffer */
+    /* TODO: make this asynchronous */
     usleep(dss->interval * 1000);
-    return 1;
+    libxl__xc_domain_saverestore_async_callback_done(egc, &dss->shs, 1);
 }
 
 /*----- main code for suspending, in order of execution -----*/
@@ -1052,6 +1067,7 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
 
     dss->suspend_eventchn = -1;
     dss->guest_responded = 0;
+    dss->dm_savefile = libxl__device_model_savefile(gc, domid);
 
     if (r_info != NULL) {
         dss->interval = r_info->interval;
@@ -1101,7 +1117,6 @@ void libxl__xc_domain_save_done(libxl__egc *egc, void *dss_void,
 
     /* Convenience aliases */
     const libxl_domain_type type = dss->type;
-    const uint32_t domid = dss->domid;
 
     if (rc)
         goto out;
@@ -1119,11 +1134,11 @@ void libxl__xc_domain_save_done(libxl__egc *egc, void *dss_void,
     }
 
     if (type == LIBXL_DOMAIN_TYPE_HVM) {
-        rc = libxl__domain_suspend_device_model(gc, domid);
+        rc = libxl__domain_suspend_device_model(gc, dss);
         if (rc) goto out;
         
-        rc = libxl__domain_save_device_model(gc, domid, dss->fd);
-        if (rc) goto out;
+        libxl__domain_save_device_model(egc, dss, domain_suspend_done);
+        return;
     }
 
     rc = 0;
@@ -1132,14 +1147,22 @@ out:
     domain_suspend_done(egc, dss, rc);
 }
 
-int libxl__domain_save_device_model(libxl__gc *gc, uint32_t domid, int fd)
+void libxl__domain_save_device_model(libxl__egc *egc,
+                                     libxl__domain_suspend_state *dss,
+                                     libxl__save_device_model_cb *callback)
 {
+    STATE_AO_GC(dss->ao);
     int rc, fd2 = -1, c;
     char buf[1024];
-    const char *filename = libxl__device_model_savefile(gc, domid);
     struct stat st;
     uint32_t qemu_state_len;
 
+    dss->save_dm_callback = callback;
+
+    /* Convenience aliases */
+    const char *const filename = dss->dm_savefile;
+    const int fd = dss->fd;
+
     if (stat(filename, &st) < 0)
     {
         LOG(ERROR, "Unable to stat qemu save file\n");
@@ -1181,7 +1204,8 @@ int libxl__domain_save_device_model(libxl__gc *gc, uint32_t domid, int fd)
 out:
     if (fd2 >= 0) close(fd2);
     unlink(filename);
-    return rc;
+
+    dss->save_dm_callback(egc, dss, rc);
 }
 
 static void domain_suspend_done(libxl__egc *egc,
tools/libxl/libxl_internal.h +15 -3
index 7e0ab11..c7fe9e9 100644
@@ -824,10 +824,8 @@ _hidden int libxl__domain_rename(libxl__gc *gc, uint32_t domid,
 
 _hidden int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
                                      uint32_t size, void *data);
-_hidden const char *libxl__device_model_savefile(libxl__gc *gc, uint32_t domid);
-_hidden int libxl__domain_suspend_device_model(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__domain_resume_device_model(libxl__gc *gc, uint32_t domid);
-_hidden int libxl__domain_save_device_model(libxl__gc *gc, uint32_t domid, int fd);
+
 _hidden void libxl__userdata_destroyall(libxl__gc *gc, uint32_t domid);
 
 _hidden int libxl__domain_pvcontrol_available(libxl__gc *gc, uint32_t domid);
@@ -1869,6 +1867,8 @@ typedef struct libxl__domain_suspend_state libxl__domain_suspend_state;
 
 typedef void libxl__domain_suspend_cb(libxl__egc*,
                                       libxl__domain_suspend_state*, int rc);
+typedef void libxl__save_device_model_cb(libxl__egc*,
+                                         libxl__domain_suspend_state*, int rc);
 
 typedef struct libxl__logdirty_switch {
     const char *cmd;
@@ -1895,9 +1895,12 @@ struct libxl__domain_suspend_state {
     int hvm;
     int xcflags;
     int guest_responded;
+    const char *dm_savefile;
     int interval; /* checkpoint interval (for Remus) */
     libxl__save_helper_state shs;
     libxl__logdirty_switch logdirty;
+    /* private for libxl__domain_save_device_model */
+    libxl__save_device_model_cb *save_dm_callback;
 };
 
 
@@ -2053,6 +2056,15 @@ _hidden void libxl__xc_domain_restore(libxl__egc *egc,
 _hidden void libxl__xc_domain_restore_done(libxl__egc *egc, void *dcs_void,
                                            int rc, int retval, int errnoval);
 
+/* Each time the dm needs to be saved, we must call suspend and then save */
+_hidden int libxl__domain_suspend_device_model(libxl__gc *gc,
+                                           libxl__domain_suspend_state *dss);
+_hidden void libxl__domain_save_device_model(libxl__egc *egc,
+                                     libxl__domain_suspend_state *dss,
+                                     libxl__save_device_model_cb *callback);
+
+_hidden const char *libxl__device_model_savefile(libxl__gc *gc, uint32_t domid);
+
 
 /*
  * Convenience macros.
tools/libxl/libxl_save_msgs_gen.pl +1 -1
index 8832c46..3ac6f80 100755
@@ -25,7 +25,7 @@ our @msgs = (
                                                 'unsigned long', 'total'] ],
     [  3, 'scxW',   "suspend", [] ],         
     [  4, 'scxW',   "postcopy", [] ],        
-    [  5, 'scxW',   "checkpoint", [] ],      
+    [  5, 'scxA',   "checkpoint", [] ],      
     [  6, 'scxA',   "switch_qemu_logdirty",  [qw(int domid
                                               unsigned enable)] ],
     #                toolstack_save          done entirely `by hand'
Signature · 1 line
1.7.2.5
Acked-by on v1 10/19
#30 lore raw

Re: [PATCH 10/19] libxl: prepare for asynchronous writing of qemu save file

Quoted 5 lines · Ian Jackson

* Combine the various calls to libxl__device_model_savefile into one at the start of libxl__domain_suspend, storing the result in the dss. Consequently a few functions take a dss instead of some or all of their other arguments.

Quoted 8 lines

* Make libxl__domain_save_device_model's API into an asynchronous style which takes a callback. The function is, however, still synchronous; it will be made actually async in the next patch.

* Consequently make libxl__remus_domain_checkpoint_callback into an asynchronous callback.

Quoted 206 lines
---
 tools/libxl/libxl_dom.c            |   54 ++++++++++++++++++++++++++----------
 tools/libxl/libxl_internal.h       |   18 ++++++++++--
 tools/libxl/libxl_save_msgs_gen.pl |    2 +-
 3 files changed, 55 insertions(+), 19 deletions(-)
tools/libxl/libxl_dom.c +39 -15
index d5ac79f..3a53f97 100644
@@ -702,11 +702,13 @@ static void switch_logdirty_done(libxl__egc *egc,
 
 /*----- callbacks, called by xc_domain_save -----*/
 
-int libxl__domain_suspend_device_model(libxl__gc *gc, uint32_t domid)
+int libxl__domain_suspend_device_model(libxl__gc *gc,
+                                       libxl__domain_suspend_state *dss)
 {
     libxl_ctx *ctx = libxl__gc_owner(gc);
     int ret = 0;
-    const char *filename = libxl__device_model_savefile(gc, domid);
+    uint32_t const domid = dss->domid;
+    const char *const filename = dss->dm_savefile;
 
     switch (libxl__device_model_version_running(gc, domid)) {
     case LIBXL_DEVICE_MODEL_VERSION_QEMU_XEN_TRADITIONAL: {
@@ -875,7 +877,7 @@ int libxl__domain_suspend_common_callback(void *user)
 
  guest_suspended:
     if (dss->hvm) {
-        ret = libxl__domain_suspend_device_model(gc, dss->domid);
+        ret = libxl__domain_suspend_device_model(gc, dss);
         if (ret) {
             LOG(ERROR, "libxl__domain_suspend_device_model failed ret=%d", ret);
             return 0;
@@ -990,19 +992,32 @@ static int libxl__remus_domain_resume_callback(void *data)
     return 1;
 }
 
-static int libxl__remus_domain_checkpoint_callback(void *data)
+/*----- remus asynchronous checkpoint callback -----*/
+
+static void remus_checkpoint_dm_saved(libxl__egc *egc,
+                                      libxl__domain_suspend_state *dss, int rc);
+
+static void libxl__remus_domain_checkpoint_callback(void *data)
 {
     libxl__domain_suspend_state *dss = data;
+    libxl__egc *egc = dss->shs.egc;
     STATE_AO_GC(dss->ao);
 
     /* This would go into tailbuf. */
-    if (dss->hvm &&
-        libxl__domain_save_device_model(gc, dss->domid, dss->fd))
-        return 0;
+    if (dss->hvm) {
+        libxl__domain_save_device_model(egc, dss, remus_checkpoint_dm_saved);
+    } else {
+        remus_checkpoint_dm_saved(egc, dss, 0);
+    }
+}
 
+static void remus_checkpoint_dm_saved(libxl__egc *egc,
+                                      libxl__domain_suspend_state *dss, int rc)
+{
     /* TODO: Wait for disk and memory ack, release network buffer */
+    /* TODO: make this asynchronous */
     usleep(dss->interval * 1000);
-    return 1;
+    libxl__xc_domain_saverestore_async_callback_done(egc, &dss->shs, 1);
 }
 
 /*----- main code for suspending, in order of execution -----*/
@@ -1052,6 +1067,7 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
 
     dss->suspend_eventchn = -1;
     dss->guest_responded = 0;
+    dss->dm_savefile = libxl__device_model_savefile(gc, domid);
 
     if (r_info != NULL) {
         dss->interval = r_info->interval;
@@ -1101,7 +1117,6 @@ void libxl__xc_domain_save_done(libxl__egc *egc, void *dss_void,
 
     /* Convenience aliases */
     const libxl_domain_type type = dss->type;
-    const uint32_t domid = dss->domid;
 
     if (rc)
         goto out;
@@ -1119,11 +1134,11 @@ void libxl__xc_domain_save_done(libxl__egc *egc, void *dss_void,
     }
 
     if (type == LIBXL_DOMAIN_TYPE_HVM) {
-        rc = libxl__domain_suspend_device_model(gc, domid);
+        rc = libxl__domain_suspend_device_model(gc, dss);
         if (rc) goto out;
 
-        rc = libxl__domain_save_device_model(gc, domid, dss->fd);
-        if (rc) goto out;
+        libxl__domain_save_device_model(egc, dss, domain_suspend_done);
+        return;
     }
 
     rc = 0;
@@ -1132,14 +1147,22 @@ out:
     domain_suspend_done(egc, dss, rc);
 }
 
-int libxl__domain_save_device_model(libxl__gc *gc, uint32_t domid, int fd)
+void libxl__domain_save_device_model(libxl__egc *egc,
+                                     libxl__domain_suspend_state *dss,
+                                     libxl__save_device_model_cb *callback)
 {
+    STATE_AO_GC(dss->ao);
     int rc, fd2 = -1, c;
     char buf[1024];
-    const char *filename = libxl__device_model_savefile(gc, domid);
     struct stat st;
     uint32_t qemu_state_len;
 
+    dss->save_dm_callback = callback;
+
+    /* Convenience aliases */
+    const char *const filename = dss->dm_savefile;
+    const int fd = dss->fd;
+
     if (stat(filename, &st) < 0)
     {
         LOG(ERROR, "Unable to stat qemu save file\n");
@@ -1181,7 +1204,8 @@ int libxl__domain_save_device_model(libxl__gc *gc, uint32_t domid, int fd)
 out:
     if (fd2 >= 0) close(fd2);
     unlink(filename);
-    return rc;
+
+    dss->save_dm_callback(egc, dss, rc);
 }
 
 static void domain_suspend_done(libxl__egc *egc,
tools/libxl/libxl_internal.h +15 -3
index 7e0ab11..c7fe9e9 100644
@@ -824,10 +824,8 @@ _hidden int libxl__domain_rename(libxl__gc *gc, uint32_t domid,
 
 _hidden int libxl__toolstack_restore(uint32_t domid, const uint8_t *buf,
                                      uint32_t size, void *data);
-_hidden const char *libxl__device_model_savefile(libxl__gc *gc, uint32_t domid);
-_hidden int libxl__domain_suspend_device_model(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__domain_resume_device_model(libxl__gc *gc, uint32_t domid);
-_hidden int libxl__domain_save_device_model(libxl__gc *gc, uint32_t domid, int fd);
+
 _hidden void libxl__userdata_destroyall(libxl__gc *gc, uint32_t domid);
 
 _hidden int libxl__domain_pvcontrol_available(libxl__gc *gc, uint32_t domid);
@@ -1869,6 +1867,8 @@ typedef struct libxl__domain_suspend_state libxl__domain_suspend_state;
 
 typedef void libxl__domain_suspend_cb(libxl__egc*,
                                       libxl__domain_suspend_state*, int rc);
+typedef void libxl__save_device_model_cb(libxl__egc*,
+                                         libxl__domain_suspend_state*, int rc);
 
 typedef struct libxl__logdirty_switch {
     const char *cmd;
@@ -1895,9 +1895,12 @@ struct libxl__domain_suspend_state {
     int hvm;
     int xcflags;
     int guest_responded;
+    const char *dm_savefile;
     int interval; /* checkpoint interval (for Remus) */
     libxl__save_helper_state shs;
     libxl__logdirty_switch logdirty;
+    /* private for libxl__domain_save_device_model */
+    libxl__save_device_model_cb *save_dm_callback;
 };
 
 
@@ -2053,6 +2056,15 @@ _hidden void libxl__xc_domain_restore(libxl__egc *egc,
 _hidden void libxl__xc_domain_restore_done(libxl__egc *egc, void *dcs_void,
                                            int rc, int retval, int errnoval);
 
+/* Each time the dm needs to be saved, we must call suspend and then save */
+_hidden int libxl__domain_suspend_device_model(libxl__gc *gc,
+                                           libxl__domain_suspend_state *dss);
+_hidden void libxl__domain_save_device_model(libxl__egc *egc,
+                                     libxl__domain_suspend_state *dss,
+                                     libxl__save_device_model_cb *callback);
+
+_hidden const char *libxl__device_model_savefile(libxl__gc *gc, uint32_t domid);
+
 
 /*
  * Convenience macros.
tools/libxl/libxl_save_msgs_gen.pl +1 -1
index 8832c46..3ac6f80 100755
@@ -25,7 +25,7 @@ our @msgs = (
                                                 'unsigned long', 'total'] ],
     [  3, 'scxW',   "suspend", [] ],         
     [  4, 'scxW',   "postcopy", [] ],        
-    [  5, 'scxW',   "checkpoint", [] ],      
+    [  5, 'scxA',   "checkpoint", [] ],      
     [  6, 'scxA',   "switch_qemu_logdirty",  [qw(int domid
                                               unsigned enable)] ],
     #                toolstack_save          done entirely `by hand'
#31 lore raw

PATCH 11/19 libxl: Make libxl__domain_save_device_model asynchronous

In reply to Ian Jackson

Changes in series v3:
* Improve one more a debugging message.

---
 tools/libxl/libxl_dom.c      |  100 +++++++++++++++++++++++++++---------------
 tools/libxl/libxl_internal.h |    1 +
 2 files changed, 66 insertions(+), 35 deletions(-)
tools/libxl/libxl_dom.c +65 -35
index 3a53f97..14eb77e 100644
@@ -1147,15 +1147,17 @@ out:
     domain_suspend_done(egc, dss, rc);
 }
 
+static void save_device_model_datacopier_done(libxl__egc *egc,
+     libxl__datacopier_state *dc, int onwrite, int errnoval);
+
 void libxl__domain_save_device_model(libxl__egc *egc,
                                      libxl__domain_suspend_state *dss,
                                      libxl__save_device_model_cb *callback)
 {
     STATE_AO_GC(dss->ao);
-    int rc, fd2 = -1, c;
-    char buf[1024];
     struct stat st;
     uint32_t qemu_state_len;
+    int rc;
 
     dss->save_dm_callback = callback;
 
@@ -1163,49 +1165,77 @@ void libxl__domain_save_device_model(libxl__egc *egc,
     const char *const filename = dss->dm_savefile;
     const int fd = dss->fd;
 
-    if (stat(filename, &st) < 0)
+    libxl__datacopier_state *dc = &dss->save_dm_datacopier;
+    memset(dc, 0, sizeof(*dc));
+    dc->readwhat = GCSPRINTF("qemu save file %s", filename);
+    dc->ao = ao;
+    dc->readfd = -1;
+    dc->writefd = fd;
+    dc->maxsz = INT_MAX;
+    dc->copywhat = GCSPRINTF("qemu save file for domain %"PRIu32, dss->domid);
+    dc->writewhat = "save/migration stream";
+    dc->callback = save_device_model_datacopier_done;
+
+    dc->readfd = open(filename, O_RDONLY);
+    if (dc->readfd < 0) {
+        LOGE(ERROR, "unable to open %s", dc->readwhat);
+        goto out;
+    }
+
+    if (fstat(dc->readfd, &st))
     {
-        LOG(ERROR, "Unable to stat qemu save file\n");
-        rc = ERROR_FAIL;
+        LOGE(ERROR, "unable to fstat %s", dc->readwhat);
+        goto out;
+    }
+
+    if (!S_ISREG(st.st_mode)) {
+        LOG(ERROR, "%s is not a plain file!", dc->readwhat);
         goto out;
     }
 
     qemu_state_len = st.st_size;
-    LOG(DEBUG, "Qemu state is %d bytes\n", qemu_state_len);
+    LOG(DEBUG, "%s is %d bytes", dc->readwhat, qemu_state_len);
 
-    rc = libxl_write_exactly(CTX, fd, QEMU_SIGNATURE, strlen(QEMU_SIGNATURE),
-                              "saved-state file", "qemu signature");
-    if (rc)
-        goto out;
+    rc = libxl__datacopier_start(dc);
+    if (rc) goto out;
 
-    rc = libxl_write_exactly(CTX, fd, &qemu_state_len, sizeof(qemu_state_len),
-                            "saved-state file", "saved-state length");
-    if (rc)
-        goto out;
+    libxl__datacopier_prefixdata(egc, dc,
+                                 QEMU_SIGNATURE, strlen(QEMU_SIGNATURE));
 
-    fd2 = open(filename, O_RDONLY);
-    if (fd2 < 0) {
-        LOGE(ERROR, "Unable to open qemu save file\n");
-        goto out;
-    }
-    while ((c = read(fd2, buf, sizeof(buf))) != 0) {
-        if (c < 0) {
-            if (errno == EINTR)
-                continue;
-            rc = errno;
-            goto out;
-        }
-        rc = libxl_write_exactly(
-            CTX, fd, buf, c, "saved-state file", "qemu state");
-        if (rc)
-            goto out;
+    libxl__datacopier_prefixdata(egc, dc,
+                                 &qemu_state_len, sizeof(qemu_state_len));
+    return;
+
+ out:
+    save_device_model_datacopier_done(egc, dc, -1, 0);
+}
+
+static void save_device_model_datacopier_done(libxl__egc *egc,
+     libxl__datacopier_state *dc, int onwrite, int errnoval)
+{
+    libxl__domain_suspend_state *dss =
+        CONTAINER_OF(dc, *dss, save_dm_datacopier);
+    STATE_AO_GC(dss->ao);
+
+    /* Convenience aliases */
+    const char *const filename = dss->dm_savefile;
+    int our_rc = 0;
+    int rc;
+
+    libxl__datacopier_kill(dc);
+
+    if (onwrite || errnoval)
+        our_rc = ERROR_FAIL;
+
+    if (dc->readfd >= 0) {
+        close(dc->readfd);
+        dc->readfd = -1;
     }
-    rc = 0;
-out:
-    if (fd2 >= 0) close(fd2);
-    unlink(filename);
 
-    dss->save_dm_callback(egc, dss, rc);
+    rc = libxl__remove_file(gc, filename);
+    if (!our_rc) our_rc = rc;
+
+    dss->save_dm_callback(egc, dss, our_rc);
 }
 
 static void domain_suspend_done(libxl__egc *egc,
tools/libxl/libxl_internal.h +1 -0
index c7fe9e9..f90814a 100644
@@ -1901,6 +1901,7 @@ struct libxl__domain_suspend_state {
     libxl__logdirty_switch logdirty;
     /* private for libxl__domain_save_device_model */
     libxl__save_device_model_cb *save_dm_callback;
+    libxl__datacopier_state save_dm_datacopier;
 };
 
 
Signature · 1 line
1.7.2.5
#33 lore raw

PATCH 12/19 libxl: Add a gc to libxl_get_cpu_topology

In reply to Ian Jackson

In the next patch we are going to change the definition of NOGC to require a local variable libxl__gc *gc.

libxl_get_cpu_topology doesn't have one but does use NOGC. Fix this by:
- introducing an `out' label
- replacing the only call to return' with a suitable assignment to ret and a goto out'.
- adding uses of GC_INIT and GC_FREE.

---
 tools/libxl/libxl.c |    6 +++++-
 1 files changed, 5 insertions(+), 1 deletions(-)
tools/libxl/libxl.c +5 -1
index 7de026b..2a31528 100644
@@ -3202,6 +3202,7 @@ int libxl_get_physinfo(libxl_ctx *ctx, libxl_physinfo *physinfo)
 
 libxl_cputopology *libxl_get_cpu_topology(libxl_ctx *ctx, int *nr)
 {
+    GC_INIT(ctx);
     xc_topologyinfo_t tinfo;
     DECLARE_HYPERCALL_BUFFER(xc_cpu_to_core_t, coremap);
     DECLARE_HYPERCALL_BUFFER(xc_cpu_to_socket_t, socketmap);
@@ -3214,7 +3215,8 @@ libxl_cputopology *libxl_get_cpu_topology(libxl_ctx *ctx, int *nr)
     if (max_cpus == 0)
     {
         LIBXL__LOG(ctx, XTL_ERROR, "Unable to determine number of CPUS");
-        return NULL;
+        ret = NULL;
+        goto out;
     }
 
     coremap = xc_hypercall_buffer_alloc
@@ -3259,6 +3261,8 @@ fail:
 
     if (ret)
         *nr = max_cpus;
+ out:
+    GC_FREE;
     return ret;
 }
 
Signature · 1 line
1.7.2.5
Acked-by on v1 12/19
#34 lore raw

Re: [PATCH 12/19] libxl: Add a gc to libxl_get_cpu_topology

Quoted 11 lines · Ian Jackson

In the next patch we are going to change the definition of NOGC to require a local variable libxl__gc *gc.

libxl_get_cpu_topology doesn't have one but does use NOGC. Fix this by:
- introducing an `out' label
- replacing the only call to return' with a suitable assignment to ret and a goto out'.
- adding uses of GC_INIT and GC_FREE.

Quoted 35 lines
---
 tools/libxl/libxl.c |    6 +++++-
 1 files changed, 5 insertions(+), 1 deletions(-)
tools/libxl/libxl.c +5 -1
index 7de026b..2a31528 100644
@@ -3202,6 +3202,7 @@ int libxl_get_physinfo(libxl_ctx *ctx, libxl_physinfo *physinfo)
 
 libxl_cputopology *libxl_get_cpu_topology(libxl_ctx *ctx, int *nr)
 {
+    GC_INIT(ctx);
     xc_topologyinfo_t tinfo;
     DECLARE_HYPERCALL_BUFFER(xc_cpu_to_core_t, coremap);
     DECLARE_HYPERCALL_BUFFER(xc_cpu_to_socket_t, socketmap);
@@ -3214,7 +3215,8 @@ libxl_cputopology *libxl_get_cpu_topology(libxl_ctx *ctx, int *nr)
     if (max_cpus == 0)
     {
         LIBXL__LOG(ctx, XTL_ERROR, "Unable to determine number of CPUS");
-        return NULL;
+        ret = NULL;
+        goto out;
     }
 
     coremap = xc_hypercall_buffer_alloc
@@ -3259,6 +3261,8 @@ fail:
 
     if (ret)
         *nr = max_cpus;
+ out:
+    GC_FREE;
     return ret;
 }
 
#35 lore raw

PATCH 13/19 libxl: Do not pass NULL as gc_opt; introduce NOGC

In reply to Ian Jackson

In 25182:6c3345d7e9d9 the practice of passing NULL to gc-using memory allocation functions was introduced. However, the arrangements there were not correct as committed, because the error handling and logging depends on getting a ctx from the gc - so an allocation error would in fact result in libxl dereferencing NULL.

Instead, provide a special dummy gc in the ctx, called `nogc_gc'. It is marked out specially by having alloc_maxsize==-1, which is otherwise invalid.

Functions which need to actually look into the gc use the new test function gc_is_real (whose purpose is mainly clarity of the code) to check whether the gc is the dummy one, and do nothing if it is. And we provide a helper macro NOGC which uses the in-scope real gc to find the ctx and hence the dummy gc (and which replaces the previous #define NOGC NULL).

Change all callers which pass 0 or NULL to an allocation function to use NOGC or &ctx->nogc_gc, as applicable in the context.

We add a comment near the definition of LIBXL_INIT_GC pointing out that it isn't any more the only place a libxl__gc struct is initialised, for the benefit of anyone changing the contents of gc's in the future.

Also, actually document that libxl__ptr_add is legal with ptr==NULL, and change a couple of calls not to check for NULL argument.

---
 tools/libxl/libxl.c          |    3 +++
 tools/libxl/libxl_aoutils.c  |    3 ++-
 tools/libxl/libxl_create.c   |    2 +-
 tools/libxl/libxl_event.c    |    5 +++--
 tools/libxl/libxl_exec.c     |    2 +-
 tools/libxl/libxl_fork.c     |    2 +-
 tools/libxl/libxl_internal.c |   11 +++++++++--
 tools/libxl/libxl_internal.h |   37 +++++++++++++++++++++++--------------
 tools/libxl/libxl_utils.c    |    6 ++----
 tools/libxl/libxl_xshelp.c   |    7 ++-----
 10 files changed, 47 insertions(+), 31 deletions(-)
tools/libxl/libxl.c +3 -0
index 2a31528..a257902 100644
@@ -41,6 +41,9 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,
 
     /* First initialise pointers etc. (cannot fail) */
 
+    ctx->nogc_gc.alloc_maxsize = -1;
+    ctx->nogc_gc.owner = ctx;
+
     LIBXL_TAILQ_INIT(&ctx->occurred);
 
     ctx->osevent_hooks = 0;
tools/libxl/libxl_aoutils.c +2 -1
index 7f8d6d3..99972a2 100644
@@ -77,6 +77,7 @@ static void datacopier_check_state(libxl__egc *egc, libxl__datacopier_state *dc)
 void libxl__datacopier_prefixdata(libxl__egc *egc, libxl__datacopier_state *dc,
                                   const void *data, size_t len)
 {
+    EGC_GC;
     libxl__datacopier_buf *buf;
     /*
      * It is safe for this to be called immediately after _start, as
@@ -88,7 +89,7 @@ void libxl__datacopier_prefixdata(libxl__egc *egc, libxl__datacopier_state *dc,
 
     assert(len < dc->maxsz - dc->used);
 
-    buf = libxl__zalloc(0, sizeof(*buf) - sizeof(buf->buf) + len);
+    buf = libxl__zalloc(NOGC, sizeof(*buf) - sizeof(buf->buf) + len);
     buf->used = len;
     memcpy(buf->buf, data, len);
 
tools/libxl/libxl_create.c +1 -1
index 00705d8..ab000bc 100644
@@ -108,7 +108,7 @@ int libxl__domain_build_info_setdefault(libxl__gc *gc,
     }
 
     if (b_info->blkdev_start == NULL)
-        b_info->blkdev_start = libxl__strdup(0, "xvda");
+        b_info->blkdev_start = libxl__strdup(NOGC, "xvda");
 
     if (b_info->type == LIBXL_DOMAIN_TYPE_HVM) {
         if (!b_info->u.hvm.bios)
tools/libxl/libxl_event.c +3 -2
index 565d2c2..eb23a93 100644
@@ -772,7 +772,7 @@ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller,
         if (poller->fd_rindices_allocd < maxfd) {
             assert(ARRAY_SIZE_OK(poller->fd_rindices, maxfd));
             poller->fd_rindices =
-                libxl__realloc(0, poller->fd_rindices,
+                libxl__realloc(NOGC, poller->fd_rindices,
                                maxfd * sizeof(*poller->fd_rindices));
             memset(poller->fd_rindices + poller->fd_rindices_allocd,
                    0,
@@ -1099,9 +1099,10 @@ void libxl_event_free(libxl_ctx *ctx, libxl_event *event)
 libxl_event *libxl__event_new(libxl__egc *egc,
                               libxl_event_type type, uint32_t domid)
 {
+    EGC_GC;
     libxl_event *ev;
 
-    ev = libxl__zalloc(0,sizeof(*ev));
+    ev = libxl__zalloc(NOGC,sizeof(*ev));
     ev->type = type;
     ev->domid = domid;
 
tools/libxl/libxl_exec.c +1 -1
index 082bf44..cfa379c 100644
@@ -280,7 +280,7 @@ int libxl__spawn_spawn(libxl__egc *egc, libxl__spawn_state *ss)
     int status, rc;
 
     libxl__spawn_init(ss);
-    ss->ssd = libxl__zalloc(0, sizeof(*ss->ssd));
+    ss->ssd = libxl__zalloc(NOGC, sizeof(*ss->ssd));
     libxl__ev_child_init(&ss->ssd->mid);
 
     rc = libxl__ev_time_register_rel(gc, &ss->timeout,
tools/libxl/libxl_fork.c +1 -1
index 9ff99e0..044ddad 100644
@@ -92,7 +92,7 @@ libxl__carefd *libxl__carefd_record(libxl_ctx *ctx, int fd)
     libxl__carefd *cf = 0;
 
     libxl_fd_set_cloexec(ctx, fd, 1);
-    cf = libxl__zalloc(NULL, sizeof(*cf));
+    cf = libxl__zalloc(&ctx->nogc_gc, sizeof(*cf));
     cf->fd = fd;
     LIBXL_LIST_INSERT_HEAD(&carefds, cf, entry);
     return cf;
tools/libxl/libxl_internal.c +9 -2
index 8139520..fbff7d0 100644
@@ -30,11 +30,16 @@ void libxl__alloc_failed(libxl_ctx *ctx, const char *func,
 #undef L
 }
 
+static int gc_is_real(const libxl__gc *gc)
+{
+    return gc->alloc_maxsize >= 0;
+}
+
 void libxl__ptr_add(libxl__gc *gc, void *ptr)
 {
     int i;
 
-    if (!gc)
+    if (!gc_is_real(gc))
         return;
 
     if (!ptr)
@@ -66,6 +71,8 @@ void libxl__free_all(libxl__gc *gc)
     void *ptr;
     int i;
 
+    assert(gc_is_real(gc));
+
     for (i = 0; i < gc->alloc_maxsize; i++) {
         ptr = gc->alloc_ptrs[i];
         gc->alloc_ptrs[i] = NULL;
@@ -104,7 +111,7 @@ void *libxl__realloc(libxl__gc *gc, void *ptr, size_t new_size)
 
     if (ptr == NULL) {
         libxl__ptr_add(gc, new_ptr);
-    } else if (new_ptr != ptr && gc != NULL) {
+    } else if (new_ptr != ptr && gc_is_real(gc)) {
         for (i = 0; i < gc->alloc_maxsize; i++) {
             if (gc->alloc_ptrs[i] == ptr) {
                 gc->alloc_ptrs[i] = new_ptr;
tools/libxl/libxl_internal.h +23 -14
index f90814a..e69482c 100644
@@ -277,10 +277,18 @@ struct libxl__poller {
     int wakeup_pipe[2]; /* 0 means no fd allocated */
 };
 
+struct libxl__gc {
+    /* mini-GC */
+    int alloc_maxsize; /* -1 means this is the dummy non-gc gc */
+    void **alloc_ptrs;
+    libxl_ctx *owner;
+};
+
 struct libxl__ctx {
     xentoollog_logger *lg;
     xc_interface *xch;
     struct xs_handle *xsh;
+    libxl__gc nogc_gc;
 
     const libxl_event_hooks *event_hooks;
     void *event_hooks_user;
@@ -356,13 +364,6 @@ typedef struct {
 
 #define PRINTF_ATTRIBUTE(x, y) __attribute__((format(printf, x, y)))
 
-struct libxl__gc {
-    /* mini-GC */
-    int alloc_maxsize;
-    void **alloc_ptrs;
-    libxl_ctx *owner;
-};
-
 struct libxl__egc {
     /* For event-generating functions only.
      * The egc and its gc may be accessed only on the creating thread. */
@@ -420,6 +421,7 @@ struct libxl__ao {
         (gc).alloc_ptrs = 0;                    \
         (gc).owner = (ctx);                     \
     } while(0)
+    /* NB, also, a gc struct ctx->nogc_gc is initialised in libxl_ctx_alloc */
 
 static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)
 {
@@ -438,13 +440,20 @@ static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)
  * All pointers returned by these functions are registered for garbage
  * collection on exit from the outermost libxl callframe.
  *
- * However, where the argument is stated to be "gc_opt", NULL may be
- * passed instead, in which case no garbage collection will occur; the
- * pointer must later be freed with free().  This is for memory
- * allocations of types (b) and (c).
+ * However, where the argument is stated to be "gc_opt", &ctx->nogc_gc
+ * may be passed instead, in which case no garbage collection will
+ * occur; the pointer must later be freed with free().  (Passing NULL
+ * for gc_opt is not permitted.)  This is for memory allocations of
+ * types (b) and (c).  The convenience macro NOGC should be used where
+ * possible.
+ *
+ * NOGC (and ctx->nogc_gc) may ONLY be used with functions which
+ * explicitly declare that it's OK.  Use with nonconsenting functions
+ * may result in leaks of those functions' internal allocations on the
+ * psuedo-gc.
  */
-/* register @ptr in @gc for free on exit from outermost libxl callframe. */
-_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr);
+/* register ptr in gc for free on exit from outermost libxl callframe. */
+_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr /* may be NULL */);
 /* if this is the outermost libxl callframe then free all pointers in @gc */
 _hidden void libxl__free_all(libxl__gc *gc);
 /* allocate and zero @bytes. (similar to a gc'd malloc(3)+memzero()) */
@@ -2110,7 +2119,7 @@ _hidden const char *libxl__device_model_savefile(libxl__gc *gc, uint32_t domid);
 #define GC_INIT(ctx)  libxl__gc gc[1]; LIBXL_INIT_GC(gc[0],ctx)
 #define GC_FREE       libxl__free_all(gc)
 #define CTX           libxl__gc_owner(gc)
-#define NOGC          NULL
+#define NOGC          (&CTX->nogc_gc) /* pass only to consenting functions */
 
 /* Allocation macros all of which use the gc. */
 
tools/libxl/libxl_utils.c +2 -4
index 67ef82c..08c7dac 100644
@@ -58,8 +58,7 @@ char *libxl_domid_to_name(libxl_ctx *ctx, uint32_t domid)
 char *libxl__domid_to_name(libxl__gc *gc, uint32_t domid)
 {
     char *s = libxl_domid_to_name(libxl__gc_owner(gc), domid);
-    if ( s )
-        libxl__ptr_add(gc, s);
+    libxl__ptr_add(gc, s);
     return s;
 }
 
@@ -107,8 +106,7 @@ char *libxl_cpupoolid_to_name(libxl_ctx *ctx, uint32_t poolid)
 char *libxl__cpupoolid_to_name(libxl__gc *gc, uint32_t poolid)
 {
     char *s = libxl_cpupoolid_to_name(libxl__gc_owner(gc), poolid);
-    if ( s )
-        libxl__ptr_add(gc, s);
+    libxl__ptr_add(gc, s);
     return s;
 }
 
tools/libxl/libxl_xshelp.c +2 -5
index 993f527..7fdf164 100644
@@ -86,11 +86,8 @@ char * libxl__xs_read(libxl__gc *gc, xs_transaction_t t, const char *path)
     char *ptr;
 
     ptr = xs_read(ctx->xsh, t, path, NULL);
-    if (ptr != NULL) {
-        libxl__ptr_add(gc, ptr);
-        return ptr;
-    }
-    return 0;
+    libxl__ptr_add(gc, ptr);
+    return ptr;
 }
 
 char *libxl__xs_get_dompath(libxl__gc *gc, uint32_t domid)
Signature · 1 line
1.7.2.5
Acked-by on v1 13/19
#36 lore raw

Re: [PATCH 13/19] libxl: Do not pass NULL as gc_opt; introduce NOGC

Quoted 25 lines · Ian Jackson

In 25182:6c3345d7e9d9 the practice of passing NULL to gc-using memory allocation functions was introduced. However, the arrangements there were not correct as committed, because the error handling and logging depends on getting a ctx from the gc - so an allocation error would in fact result in libxl dereferencing NULL.

Instead, provide a special dummy gc in the ctx, called `nogc_gc'. It is marked out specially by having alloc_maxsize==-1, which is otherwise invalid.

Functions which need to actually look into the gc use the new test function gc_is_real (whose purpose is mainly clarity of the code) to check whether the gc is the dummy one, and do nothing if it is. And we provide a helper macro NOGC which uses the in-scope real gc to find the ctx and hence the dummy gc (and which replaces the previous #define NOGC NULL).

Change all callers which pass 0 or NULL to an allocation function to use NOGC or &ctx->nogc_gc, as applicable in the context.

We add a comment near the definition of LIBXL_INIT_GC pointing out that it isn't any more the only place a libxl__gc struct is initialised, for the benefit of anyone changing the contents of gc's in the future.

Quoted 6 lines

Also, actually document that libxl__ptr_add is legal with ptr==NULL, and change a couple of calls not to check for NULL argument.

Quoted 275 lines
---
 tools/libxl/libxl.c          |    3 +++
 tools/libxl/libxl_aoutils.c  |    3 ++-
 tools/libxl/libxl_create.c   |    2 +-
 tools/libxl/libxl_event.c    |    5 +++--
 tools/libxl/libxl_exec.c     |    2 +-
 tools/libxl/libxl_fork.c     |    2 +-
 tools/libxl/libxl_internal.c |   11 +++++++++--
 tools/libxl/libxl_internal.h |   37 +++++++++++++++++++++++--------------
 tools/libxl/libxl_utils.c    |    6 ++----
 tools/libxl/libxl_xshelp.c   |    7 ++-----
 10 files changed, 47 insertions(+), 31 deletions(-)
tools/libxl/libxl.c +3 -0
index 2a31528..a257902 100644
@@ -41,6 +41,9 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,
 
     /* First initialise pointers etc. (cannot fail) */
 
+    ctx->nogc_gc.alloc_maxsize = -1;
+    ctx->nogc_gc.owner = ctx;
+
     LIBXL_TAILQ_INIT(&ctx->occurred);
 
     ctx->osevent_hooks = 0;
tools/libxl/libxl_aoutils.c +2 -1
index 7f8d6d3..99972a2 100644
@@ -77,6 +77,7 @@ static void datacopier_check_state(libxl__egc *egc, libxl__datacopier_state *dc)
 void libxl__datacopier_prefixdata(libxl__egc *egc, libxl__datacopier_state *dc,
                                   const void *data, size_t len)
 {
+    EGC_GC;
     libxl__datacopier_buf *buf;
     /*
      * It is safe for this to be called immediately after _start, as
@@ -88,7 +89,7 @@ void libxl__datacopier_prefixdata(libxl__egc *egc, libxl__datacopier_state *dc,
 
     assert(len < dc->maxsz - dc->used);
 
-    buf = libxl__zalloc(0, sizeof(*buf) - sizeof(buf->buf) + len);
+    buf = libxl__zalloc(NOGC, sizeof(*buf) - sizeof(buf->buf) + len);
     buf->used = len;
     memcpy(buf->buf, data, len);
 
tools/libxl/libxl_create.c +1 -1
index 00705d8..ab000bc 100644
@@ -108,7 +108,7 @@ int libxl__domain_build_info_setdefault(libxl__gc *gc,
     }
 
     if (b_info->blkdev_start == NULL)
-        b_info->blkdev_start = libxl__strdup(0, "xvda");
+        b_info->blkdev_start = libxl__strdup(NOGC, "xvda");
 
     if (b_info->type == LIBXL_DOMAIN_TYPE_HVM) {
         if (!b_info->u.hvm.bios)
tools/libxl/libxl_event.c +3 -2
index 565d2c2..eb23a93 100644
@@ -772,7 +772,7 @@ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller,
         if (poller->fd_rindices_allocd < maxfd) {
             assert(ARRAY_SIZE_OK(poller->fd_rindices, maxfd));
             poller->fd_rindices =
-                libxl__realloc(0, poller->fd_rindices,
+                libxl__realloc(NOGC, poller->fd_rindices,
                                maxfd * sizeof(*poller->fd_rindices));
             memset(poller->fd_rindices + poller->fd_rindices_allocd,
                    0,
@@ -1099,9 +1099,10 @@ void libxl_event_free(libxl_ctx *ctx, libxl_event *event)
 libxl_event *libxl__event_new(libxl__egc *egc,
                               libxl_event_type type, uint32_t domid)
 {
+    EGC_GC;
     libxl_event *ev;
 
-    ev = libxl__zalloc(0,sizeof(*ev));
+    ev = libxl__zalloc(NOGC,sizeof(*ev));
     ev->type = type;
     ev->domid = domid;
 
tools/libxl/libxl_exec.c +1 -1
index 082bf44..cfa379c 100644
@@ -280,7 +280,7 @@ int libxl__spawn_spawn(libxl__egc *egc, libxl__spawn_state *ss)
     int status, rc;
 
     libxl__spawn_init(ss);
-    ss->ssd = libxl__zalloc(0, sizeof(*ss->ssd));
+    ss->ssd = libxl__zalloc(NOGC, sizeof(*ss->ssd));
     libxl__ev_child_init(&ss->ssd->mid);
 
     rc = libxl__ev_time_register_rel(gc, &ss->timeout,
tools/libxl/libxl_fork.c +1 -1
index 9ff99e0..044ddad 100644
@@ -92,7 +92,7 @@ libxl__carefd *libxl__carefd_record(libxl_ctx *ctx, int fd)
     libxl__carefd *cf = 0;
 
     libxl_fd_set_cloexec(ctx, fd, 1);
-    cf = libxl__zalloc(NULL, sizeof(*cf));
+    cf = libxl__zalloc(&ctx->nogc_gc, sizeof(*cf));
     cf->fd = fd;
     LIBXL_LIST_INSERT_HEAD(&carefds, cf, entry);
     return cf;
tools/libxl/libxl_internal.c +9 -2
index 8139520..fbff7d0 100644
@@ -30,11 +30,16 @@ void libxl__alloc_failed(libxl_ctx *ctx, const char *func,
 #undef L
 }
 
+static int gc_is_real(const libxl__gc *gc)
+{
+    return gc->alloc_maxsize >= 0;
+}
+
 void libxl__ptr_add(libxl__gc *gc, void *ptr)
 {
     int i;
 
-    if (!gc)
+    if (!gc_is_real(gc))
         return;
 
     if (!ptr)
@@ -66,6 +71,8 @@ void libxl__free_all(libxl__gc *gc)
     void *ptr;
     int i;
 
+    assert(gc_is_real(gc));
+
     for (i = 0; i < gc->alloc_maxsize; i++) {
         ptr = gc->alloc_ptrs[i];
         gc->alloc_ptrs[i] = NULL;
@@ -104,7 +111,7 @@ void *libxl__realloc(libxl__gc *gc, void *ptr, size_t new_size)
 
     if (ptr == NULL) {
         libxl__ptr_add(gc, new_ptr);
-    } else if (new_ptr != ptr && gc != NULL) {
+    } else if (new_ptr != ptr && gc_is_real(gc)) {
         for (i = 0; i < gc->alloc_maxsize; i++) {
             if (gc->alloc_ptrs[i] == ptr) {
                 gc->alloc_ptrs[i] = new_ptr;
tools/libxl/libxl_internal.h +23 -14
index f90814a..e69482c 100644
@@ -277,10 +277,18 @@ struct libxl__poller {
     int wakeup_pipe[2]; /* 0 means no fd allocated */
 };
 
+struct libxl__gc {
+    /* mini-GC */
+    int alloc_maxsize; /* -1 means this is the dummy non-gc gc */
+    void **alloc_ptrs;
+    libxl_ctx *owner;
+};
+
 struct libxl__ctx {
     xentoollog_logger *lg;
     xc_interface *xch;
     struct xs_handle *xsh;
+    libxl__gc nogc_gc;
 
     const libxl_event_hooks *event_hooks;
     void *event_hooks_user;
@@ -356,13 +364,6 @@ typedef struct {
 
 #define PRINTF_ATTRIBUTE(x, y) __attribute__((format(printf, x, y)))
 
-struct libxl__gc {
-    /* mini-GC */
-    int alloc_maxsize;
-    void **alloc_ptrs;
-    libxl_ctx *owner;
-};
-
 struct libxl__egc {
     /* For event-generating functions only.
      * The egc and its gc may be accessed only on the creating thread. */
@@ -420,6 +421,7 @@ struct libxl__ao {
         (gc).alloc_ptrs = 0;                    \
         (gc).owner = (ctx);                     \
     } while(0)
+    /* NB, also, a gc struct ctx->nogc_gc is initialised in libxl_ctx_alloc */
 
 static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)
 {
@@ -438,13 +440,20 @@ static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)
  * All pointers returned by these functions are registered for garbage
  * collection on exit from the outermost libxl callframe.
  *
- * However, where the argument is stated to be "gc_opt", NULL may be
- * passed instead, in which case no garbage collection will occur; the
- * pointer must later be freed with free().  This is for memory
- * allocations of types (b) and (c).
+ * However, where the argument is stated to be "gc_opt", &ctx->nogc_gc
+ * may be passed instead, in which case no garbage collection will
+ * occur; the pointer must later be freed with free().  (Passing NULL
+ * for gc_opt is not permitted.)  This is for memory allocations of
+ * types (b) and (c).  The convenience macro NOGC should be used where
+ * possible.
+ *
+ * NOGC (and ctx->nogc_gc) may ONLY be used with functions which
+ * explicitly declare that it's OK.  Use with nonconsenting functions
+ * may result in leaks of those functions' internal allocations on the
+ * psuedo-gc.
  */
-/* register @ptr in @gc for free on exit from outermost libxl callframe. */
-_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr);
+/* register ptr in gc for free on exit from outermost libxl callframe. */
+_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr /* may be NULL */);
 /* if this is the outermost libxl callframe then free all pointers in @gc */
 _hidden void libxl__free_all(libxl__gc *gc);
 /* allocate and zero @bytes. (similar to a gc'd malloc(3)+memzero()) */
@@ -2110,7 +2119,7 @@ _hidden const char *libxl__device_model_savefile(libxl__gc *gc, uint32_t domid);
 #define GC_INIT(ctx)  libxl__gc gc[1]; LIBXL_INIT_GC(gc[0],ctx)
 #define GC_FREE       libxl__free_all(gc)
 #define CTX           libxl__gc_owner(gc)
-#define NOGC          NULL
+#define NOGC          (&CTX->nogc_gc) /* pass only to consenting functions */
 
 /* Allocation macros all of which use the gc. */
 
tools/libxl/libxl_utils.c +2 -4
index 67ef82c..08c7dac 100644
@@ -58,8 +58,7 @@ char *libxl_domid_to_name(libxl_ctx *ctx, uint32_t domid)
 char *libxl__domid_to_name(libxl__gc *gc, uint32_t domid)
 {
     char *s = libxl_domid_to_name(libxl__gc_owner(gc), domid);
-    if ( s )
-        libxl__ptr_add(gc, s);
+    libxl__ptr_add(gc, s);
     return s;
 }
 
@@ -107,8 +106,7 @@ char *libxl_cpupoolid_to_name(libxl_ctx *ctx, uint32_t poolid)
 char *libxl__cpupoolid_to_name(libxl__gc *gc, uint32_t poolid)
 {
     char *s = libxl_cpupoolid_to_name(libxl__gc_owner(gc), poolid);
-    if ( s )
-        libxl__ptr_add(gc, s);
+    libxl__ptr_add(gc, s);
     return s;
 }
 
tools/libxl/libxl_xshelp.c +2 -5
index 993f527..7fdf164 100644
@@ -86,11 +86,8 @@ char * libxl__xs_read(libxl__gc *gc, xs_transaction_t t, const char *path)
     char *ptr;
 
     ptr = xs_read(ctx->xsh, t, path, NULL);
-    if (ptr != NULL) {
-        libxl__ptr_add(gc, ptr);
-        return ptr;
-    }
-    return 0;
+    libxl__ptr_add(gc, ptr);
+    return ptr;
 }
 
 char *libxl__xs_get_dompath(libxl__gc *gc, uint32_t domid)
#37 lore raw

PATCH 14/19 libxl: Get compiler to warn about gc_opt==NULL

In reply to Ian Jackson

Since it used to be legal to pass gc_opt==NULL, and there are various patches floating about and under developmetn which do so, add a compiler annotation which makes the build fail when that is done.

This turns a runtime crash into a build failure, and should ensure that we don't accidentally commit a broken combination of patches.

This is something of an annoying approach because it adds a macro invocation to the RHS of every declaration of a function taking a gc_opt. So it should be reverted after Xen 4.2rc1.

---
 tools/libxl/libxl_internal.h |   21 +++++++++++++--------
 1 files changed, 13 insertions(+), 8 deletions(-)
tools/libxl/libxl_internal.h +13 -8
index e69482c..8635764 100644
@@ -453,28 +453,33 @@ static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)
  * psuedo-gc.
  */
 /* register ptr in gc for free on exit from outermost libxl callframe. */
-_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr /* may be NULL */);
+
+#define NN1 __attribute__((nonnull(1)))
+ /* It used to be legal to pass NULL for gc_opt.  Get the compiler to
+  * warn about this if any slip through. */
+
+_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr /* may be NULL */) NN1;
 /* if this is the outermost libxl callframe then free all pointers in @gc */
 _hidden void libxl__free_all(libxl__gc *gc);
 /* allocate and zero @bytes. (similar to a gc'd malloc(3)+memzero()) */
-_hidden void *libxl__zalloc(libxl__gc *gc_opt, int bytes);
+_hidden void *libxl__zalloc(libxl__gc *gc_opt, int bytes) NN1;
 /* allocate and zero memory for an array of @nmemb members of @size each.
  * (similar to a gc'd calloc(3)). */
-_hidden void *libxl__calloc(libxl__gc *gc_opt, size_t nmemb, size_t size);
+_hidden void *libxl__calloc(libxl__gc *gc_opt, size_t nmemb, size_t size) NN1;
 /* change the size of the memory block pointed to by @ptr to @new_size bytes.
  * unlike other allocation functions here any additional space between the
  * oldsize and @new_size is not initialised (similar to a gc'd realloc(3)). */
-_hidden void *libxl__realloc(libxl__gc *gc_opt, void *ptr, size_t new_size);
+_hidden void *libxl__realloc(libxl__gc *gc_opt, void *ptr, size_t new_size) NN1;
 /* print @fmt into an allocated string large enoughto contain the result.
  * (similar to gc'd asprintf(3)). */
-_hidden char *libxl__sprintf(libxl__gc *gc_opt, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3);
+_hidden char *libxl__sprintf(libxl__gc *gc_opt, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3) NN1;
 /* duplicate the string @c (similar to a gc'd strdup(3)). */
-_hidden char *libxl__strdup(libxl__gc *gc_opt, const char *c);
+_hidden char *libxl__strdup(libxl__gc *gc_opt, const char *c) NN1;
 /* duplicate at most @n bytes of string @c (similar to a gc'd strndup(3)). */
-_hidden char *libxl__strndup(libxl__gc *gc_opt, const char *c, size_t n);
+_hidden char *libxl__strndup(libxl__gc *gc_opt, const char *c, size_t n) NN1;
 /* strip the last path component from @s and return as a newly allocated
  * string. (similar to a gc'd dirname(3)). */
-_hidden char *libxl__dirname(libxl__gc *gc_opt, const char *s);
+_hidden char *libxl__dirname(libxl__gc *gc_opt, const char *s) NN1;
 
 /* Each of these logs errors and returns a libxl error code.
  * They do not mind if path is already removed.
Signature · 1 line
1.7.2.5
Acked-by on v1 14/19
#38 lore raw

Re: [PATCH 14/19] libxl: Get compiler to warn about gc_opt==NULL

Quoted 2 lines · Ian Jackson

Since it used to be legal to pass gc_opt==NULL, and there are various patches floating about and under developmetn which do so, add a

development

Quoted 8 lines

compiler annotation which makes the build fail when that is done.

This turns a runtime crash into a build failure, and should ensure that we don't accidentally commit a broken combination of patches.

This is something of an annoying approach because it adds a macro invocation to the RHS of every declaration of a function taking a gc_opt. So it should be reverted after Xen 4.2rc1.

This patch will itself break the build until a subsequent patch, won't it? Shuffle it afterwards?

Quoted 1 line

Wherever it ends up in the sequence:

Quoted 50 lines
---
 tools/libxl/libxl_internal.h |   21 +++++++++++++--------
 1 files changed, 13 insertions(+), 8 deletions(-)
tools/libxl/libxl_internal.h +13 -8
index e69482c..8635764 100644
@@ -453,28 +453,33 @@ static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)
  * psuedo-gc.
  */
 /* register ptr in gc for free on exit from outermost libxl callframe. */
-_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr /* may be NULL */);
+
+#define NN1 __attribute__((nonnull(1)))
+ /* It used to be legal to pass NULL for gc_opt.  Get the compiler to
+  * warn about this if any slip through. */
+
+_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr /* may be NULL */) NN1;
 /* if this is the outermost libxl callframe then free all pointers in @gc */
 _hidden void libxl__free_all(libxl__gc *gc);
 /* allocate and zero @bytes. (similar to a gc'd malloc(3)+memzero()) */
-_hidden void *libxl__zalloc(libxl__gc *gc_opt, int bytes);
+_hidden void *libxl__zalloc(libxl__gc *gc_opt, int bytes) NN1;
 /* allocate and zero memory for an array of @nmemb members of @size each.
  * (similar to a gc'd calloc(3)). */
-_hidden void *libxl__calloc(libxl__gc *gc_opt, size_t nmemb, size_t size);
+_hidden void *libxl__calloc(libxl__gc *gc_opt, size_t nmemb, size_t size) NN1;
 /* change the size of the memory block pointed to by @ptr to @new_size bytes.
  * unlike other allocation functions here any additional space between the
  * oldsize and @new_size is not initialised (similar to a gc'd realloc(3)). */
-_hidden void *libxl__realloc(libxl__gc *gc_opt, void *ptr, size_t new_size);
+_hidden void *libxl__realloc(libxl__gc *gc_opt, void *ptr, size_t new_size) NN1;
 /* print @fmt into an allocated string large enoughto contain the result.
  * (similar to gc'd asprintf(3)). */
-_hidden char *libxl__sprintf(libxl__gc *gc_opt, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3);
+_hidden char *libxl__sprintf(libxl__gc *gc_opt, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3) NN1;
 /* duplicate the string @c (similar to a gc'd strdup(3)). */
-_hidden char *libxl__strdup(libxl__gc *gc_opt, const char *c);
+_hidden char *libxl__strdup(libxl__gc *gc_opt, const char *c) NN1;
 /* duplicate at most @n bytes of string @c (similar to a gc'd strndup(3)). */
-_hidden char *libxl__strndup(libxl__gc *gc_opt, const char *c, size_t n);
+_hidden char *libxl__strndup(libxl__gc *gc_opt, const char *c, size_t n) NN1;
 /* strip the last path component from @s and return as a newly allocated
  * string. (similar to a gc'd dirname(3)). */
-_hidden char *libxl__dirname(libxl__gc *gc_opt, const char *s);
+_hidden char *libxl__dirname(libxl__gc *gc_opt, const char *s) NN1;
 
 /* Each of these logs errors and returns a libxl error code.
  * They do not mind if path is already removed.
#39 lore raw

Re: [PATCH 14/19] libxl: Get compiler to warn about gc_opt==NULL

Quoted 11 lines · Ian Campbell
Quoted 2 lines · Ian Jackson

Since it used to be legal to pass gc_opt==NULL, and there are various patches floating about and under developmetn which do so, add a

development

Quoted 5 lines

compiler annotation which makes the build fail when that is done.

This turns a runtime crash into a build failure, and should ensure that we don't accidentally commit a broken combination of patches.

Quoted 6 lines
Quoted 3 lines

This is something of an annoying approach because it adds a macro invocation to the RHS of every declaration of a function taking a gc_opt. So it should be reverted after Xen 4.2rc1.

This patch will itself break the build until a subsequent patch, won't it? Shuffle it afterwards?

Nevermind, I accidentally skipped #13...

Quoted 57 lines
Quoted 2 lines

Wherever it ends up in the sequence:

Quoted 50 lines
---
 tools/libxl/libxl_internal.h |   21 +++++++++++++--------
 1 files changed, 13 insertions(+), 8 deletions(-)
tools/libxl/libxl_internal.h +13 -8
index e69482c..8635764 100644
@@ -453,28 +453,33 @@ static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)
  * psuedo-gc.
  */
 /* register ptr in gc for free on exit from outermost libxl callframe. */
-_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr /* may be NULL */);
+
+#define NN1 __attribute__((nonnull(1)))
+ /* It used to be legal to pass NULL for gc_opt.  Get the compiler to
+  * warn about this if any slip through. */
+
+_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr /* may be NULL */) NN1;
 /* if this is the outermost libxl callframe then free all pointers in @gc */
 _hidden void libxl__free_all(libxl__gc *gc);
 /* allocate and zero @bytes. (similar to a gc'd malloc(3)+memzero()) */
-_hidden void *libxl__zalloc(libxl__gc *gc_opt, int bytes);
+_hidden void *libxl__zalloc(libxl__gc *gc_opt, int bytes) NN1;
 /* allocate and zero memory for an array of @nmemb members of @size each.
  * (similar to a gc'd calloc(3)). */
-_hidden void *libxl__calloc(libxl__gc *gc_opt, size_t nmemb, size_t size);
+_hidden void *libxl__calloc(libxl__gc *gc_opt, size_t nmemb, size_t size) NN1;
 /* change the size of the memory block pointed to by @ptr to @new_size bytes.
  * unlike other allocation functions here any additional space between the
  * oldsize and @new_size is not initialised (similar to a gc'd realloc(3)). */
-_hidden void *libxl__realloc(libxl__gc *gc_opt, void *ptr, size_t new_size);
+_hidden void *libxl__realloc(libxl__gc *gc_opt, void *ptr, size_t new_size) NN1;
 /* print @fmt into an allocated string large enoughto contain the result.
  * (similar to gc'd asprintf(3)). */
-_hidden char *libxl__sprintf(libxl__gc *gc_opt, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3);
+_hidden char *libxl__sprintf(libxl__gc *gc_opt, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3) NN1;
 /* duplicate the string @c (similar to a gc'd strdup(3)). */
-_hidden char *libxl__strdup(libxl__gc *gc_opt, const char *c);
+_hidden char *libxl__strdup(libxl__gc *gc_opt, const char *c) NN1;
 /* duplicate at most @n bytes of string @c (similar to a gc'd strndup(3)). */
-_hidden char *libxl__strndup(libxl__gc *gc_opt, const char *c, size_t n);
+_hidden char *libxl__strndup(libxl__gc *gc_opt, const char *c, size_t n) NN1;
 /* strip the last path component from @s and return as a newly allocated
  * string. (similar to a gc'd dirname(3)). */
-_hidden char *libxl__dirname(libxl__gc *gc_opt, const char *s);
+_hidden char *libxl__dirname(libxl__gc *gc_opt, const char *s) NN1;
 
 /* Each of these logs errors and returns a libxl error code.
  * They do not mind if path is already removed.
#40 lore raw

Re: [PATCH 14/19] libxl: Get compiler to warn about gc_opt==NULL

Ian Campbell writes ("Re: [Xen-devel] [PATCH 14/19] libxl: Get compiler to warn about gc_opt==NULL"):

Quoted 5 lines · Ian Campbell
Quoted 2 lines

This patch will itself break the build until a subsequent patch, won't it? Shuffle it afterwards?

Nevermind, I accidentally skipped #13...

:-).

Quoted 4 lines
Quoted 4 lines
Quoted 1 line

Wherever it ends up in the sequence:

Thanks,
Ian.

#41 lore raw

PATCH 15/19 xl: Handle return value from libxl_domain_suspend correctly

In reply to Ian Jackson

libxl_domain_suspend returns a libxl error code. So it must be wrapped with MUST and not CHK_ERRNO.

---
 tools/libxl/xl_cmdimpl.c |    2 +-
 1 files changed, 1 insertions(+), 1 deletions(-)
tools/libxl/xl_cmdimpl.c +1 -1
index 19daa1c..a9125cc 100644
@@ -2846,7 +2846,7 @@ static int save_domain(const char *p, const char *filename, int checkpoint,
 
     save_domain_core_writeconfig(fd, filename, config_data, config_len);
 
-    CHK_ERRNO(libxl_domain_suspend(ctx, domid, fd, 0, NULL));
+    MUST(libxl_domain_suspend(ctx, domid, fd, 0, NULL));
     close(fd);
 
     if (checkpoint)
Signature · 1 line
1.7.2.5
#42 lore raw

PATCH 16/19 libxl: do not leak dms->saved_state

In reply to Ian Jackson

This was allocated using asprintf but never freed. Use GCSPRINTF.

---
 tools/libxl/libxl_create.c |    3 +--
 1 files changed, 1 insertions(+), 2 deletions(-)
tools/libxl/libxl_create.c +1 -2
index ab000bc..5618293 100644
@@ -740,9 +740,8 @@ void libxl__xc_domain_restore_done(libxl__egc *egc, void *dcs_void,
         goto out;
 
     if (info->type == LIBXL_DOMAIN_TYPE_HVM) {
-        ret = asprintf(&state->saved_state,
+        state->saved_state = GCSPRINTF(
                        XC_DEVICE_MODEL_RESTORE_FILE".%d", domid);
-        ret = (ret < 0) ? ERROR_FAIL : 0;
     }
 
 out:
Signature · 1 line
1.7.2.5
#43 lore raw

PATCH 17/19 libxl: do not leak spawned middle children

In reply to Ian Jackson

libxl__spawn_spawn would, when libxl__spawn_detach was called, make the spawn become idle immediately. However it still has a child process which needs to be waited for: the `detachable' spawned child.

This is wrong because the ultimate in-libxl caller may return to the application, with a child process still forked but not reaped libxl contrary to the documented behaviour of libxl.

Instead, replace libxl__spawn_detach with libxl__spawn_initiate_detach which is asynchronous. The detachable spawned children are abolished; instead, we defer calling back to the in-libxl user until the middle child has been reaped.

Also, remove erroneous comment suggesting that `death' callback parameter to libxl__ev_child_fork may be NULL. It may not, and there are no callers which pass NULL.

Changes in v3 of series:
* Now also remove erroneous comment about NULL fork death callback.

---
 tools/libxl/libxl_dm.c       |   14 ++++-
 tools/libxl/libxl_exec.c     |  124 ++++++++++++++++++++++++------------------
 tools/libxl/libxl_internal.h |   43 ++++++++-------
 3 files changed, 104 insertions(+), 77 deletions(-)
tools/libxl/libxl_dm.c +11 -3
index 340fcfa..b3de145 100644
@@ -908,6 +908,8 @@ static void device_model_confirm(libxl__egc *egc, libxl__spawn_state *spawn,
                                  const char *xsdata);
 static void device_model_startup_failed(libxl__egc *egc,
                                         libxl__spawn_state *spawn);
+static void device_model_detached(libxl__egc *egc,
+                                  libxl__spawn_state *spawn);
 
 /* our "next step" function, called from those callbacks and elsewhere */
 static void device_model_spawn_outcome(libxl__egc *egc,
@@ -1015,6 +1017,7 @@ retry_transaction:
     spawn->midproc_cb = libxl__spawn_record_pid;
     spawn->confirm_cb = device_model_confirm;
     spawn->failure_cb = device_model_startup_failed;
+    spawn->detached_cb = device_model_detached;
 
     rc = libxl__spawn_spawn(egc, spawn);
     if (rc < 0)
@@ -1048,9 +1051,7 @@ static void device_model_confirm(libxl__egc *egc, libxl__spawn_state *spawn,
     if (strcmp(xsdata, "running"))
         return;
 
-    libxl__spawn_detach(gc, spawn);
-
-    device_model_spawn_outcome(egc, dmss, 0);
+    libxl__spawn_initiate_detach(gc, spawn);
 }
 
 static void device_model_startup_failed(libxl__egc *egc,
@@ -1060,6 +1061,13 @@ static void device_model_startup_failed(libxl__egc *egc,
     device_model_spawn_outcome(egc, dmss, ERROR_FAIL);
 }
 
+static void device_model_detached(libxl__egc *egc,
+                                  libxl__spawn_state *spawn)
+{
+    libxl__dm_spawn_state *dmss = CONTAINER_OF(spawn, *dmss, spawn);
+    device_model_spawn_outcome(egc, dmss, 0);
+}
+
 static void device_model_spawn_outcome(libxl__egc *egc,
                                        libxl__dm_spawn_state *dmss,
                                        int rc)
tools/libxl/libxl_exec.c +71 -53

209 lines not on this page · raw message

tools/libxl/libxl_internal.h +22 -21

105 lines not on this page · raw message

Signature · 1 line
1.7.2.5
Acked-by on v1 17/19
#44 lore raw

Re: [PATCH 17/19] libxl: do not leak spawned middle children

Quoted 14 lines · Ian Jackson

libxl__spawn_spawn would, when libxl__spawn_detach was called, make the spawn become idle immediately. However it still has a child process which needs to be waited for: the `detachable' spawned child.

This is wrong because the ultimate in-libxl caller may return to the application, with a child process still forked but not reaped libxl contrary to the documented behaviour of libxl.

Instead, replace libxl__spawn_detach with libxl__spawn_initiate_detach which is asynchronous. The detachable spawned children are abolished; instead, we defer calling back to the in-libxl user until the middle child has been reaped.

Quoted 5 lines

Also, remove erroneous comment suggesting that `death' callback parameter to libxl__ev_child_fork may be NULL. It may not, and there are no callers which pass NULL.

(couple of tiny queries below)

[...]

Quoted 33 lines
tools/libxl/libxl_exec.c +9 -8
index cfa379c..bb85682 100644
@@ -238,15 +238,16 @@ err:
 /*
  * Full set of possible states of a libxl__spawn_state and its _detachable:
  *
- *               ss->        ss->        ss->    | ssd->       ssd->
- *               timeout     xswatch     ssd     |  mid         ss
- *  - Undefined   undef       undef       no     |  -           -
- *  - Idle        Idle        Idle        no     |  -           -
- *  - Active      Active      Active      yes    |  Active      yes
- *  - Partial     Active/Idle Active/Idle maybe  |  Active/Idle yes  (if exists)
- *  - Detached    -           -           -      |  Active      no
+ *                   detaching failed  mid     timeout      xswatch
+ *  - Undefined         undef   undef   -        undef        undef
+ *  - Idle              any     any     Idle     Idle         Idle
+ *  - Attached OK       0       0       Active   Active       Active
+ *  - Attached Failed   0       1       Active   Idle         Idle
+ *  - Detaching         1       maybe   Active   Idle         Idle
+ *  - Partial           any     any     Idle     Active/Idle  Active/Idle
  *
- * When in state Detached, the middle process has been sent a SIGKILL.
+ * When in states Detaching or Attached Failed, the middle process has
+ * been sent a SIGKILL.
  */
 
 /* Event callbacks. */
@@ -257,19 +258,18 @@ static void spawn_timeout(libxl__egc *egc, libxl__ev_time *ev,
 static void spawn_middle_death(libxl__egc *egc, libxl__ev_child *childw,
                                pid_t pid, int status);
 

tools/libxl/libxl_exec.c static void spawn_timeout(libxl__egc *egc, libxl__ev_time *ev, · line 265

Quoted 10 lines
tools/libxl/libxl_exec.c +3 -5
-/* Precondition: Partial.  Results: Detached. */
+/* Precondition: Partial.  Results: Idle. */
 static void spawn_cleanup(libxl__gc *gc, libxl__spawn_state *ss);
 
-/* Precondition: Partial; caller has logged failure reason.
- * Results: Caller notified of failure;
- *  after return, ss may be completely invalid as caller may reuse it */
-static void spawn_failed(libxl__egc *egc, libxl__spawn_state *ss);
+/* Precondition: Attached or Detaching; caller has logged failure reason.
+ * Results: Detaching, or Attached Failing */

Is it Failing or Failed? You use Failed elsewhere.

[...]

tools/libxl/libxl_exec.c _hidden int libxl__device_pci_destroy_all(libxl__gc *gc, uint32_t domid); · line 1001

Quoted 8 lines
tools/libxl/libxl_exec.c +2 -2
@@ -998,8 +997,8 @@ _hidden int libxl__device_pci_destroy_all(libxl__gc *gc, uint32_t domid);
  *
  * Higher-level double-fork and separate detach eg as for device models
  *
- * Each libxl__spawn_state is in one of the conventional states
- *    Undefined, Idle, Active
+ * Each libxl__spawn_state is in one of these states
+ *    Undefined, Idle, Attached, Detaching

"Attached OK" and "Attached Failed" as described above aren't really full states, just sub-states?

Ian.

#45 lore raw

Re: [PATCH 17/19] libxl: do not leak spawned middle children

Ian Campbell writes ("Re: [Xen-devel] [PATCH 17/19] libxl: do not leak spawned middle children"):

Quoted 6 lines · Ian Jackson
Quoted 3 lines

Also, remove erroneous comment suggesting that `death' callback parameter to libxl__ev_child_fork may be NULL. It may not, and there are no callers which pass NULL.

Thanks.

Quoted 5 lines

tools/libxl/libxl_exec.c static void spawn_timeout(libxl__egc *egc, libxl__ev_time *ev, · line 265

Quoted 3 lines
tools/libxl/libxl_exec.c +2 -1
-static void spawn_failed(libxl__egc *egc, libxl__spawn_state *ss);
+/* Precondition: Attached or Detaching; caller has logged failure reason.
+ * Results: Detaching, or Attached Failing */

Is it Failing or Failed? You use Failed elsewhere.

`Failed' will do. Fixed.

Quoted 12 lines

[...]

tools/libxl/libxl_internal.h _hidden int libxl__device_pci_destroy_all(libxl__gc *gc, uint32_t domid); · line 1001

Quoted 8 lines
tools/libxl/libxl_internal.h +2 -2
@@ -998,8 +997,8 @@ _hidden int libxl__device_pci_destroy_all(libxl__gc *gc, uint32_t domid);
  *
  * Higher-level double-fork and separate detach eg as for device models
  *
- * Each libxl__spawn_state is in one of the conventional states
- *    Undefined, Idle, Active
+ * Each libxl__spawn_state is in one of these states
+ *    Undefined, Idle, Attached, Detaching

"Attached OK" and "Attached Failed" as described above aren't really full states, just sub-states?

Yes. I have clarified this:

* The difference between Attached OK and Attached Failed is not
* directly visible to callers - callers see these two the same,
* although of course Attached OK will hopefully eventually result in
* a call to detached_cb, whereas Attached Failed will end up
* in a call to failure_cb.

Ian.

#46 lore raw

PATCH 18/19 libxl: do not leak an event struct on ignored ao progress

In reply to Ian Jackson

On entry to libxl__ao_progress_report, the caller has allocated an event. If the progress report is to be ignored, we need to free it.

---
 tools/libxl/libxl_event.c |    1 +
 1 files changed, 1 insertions(+), 0 deletions(-)
tools/libxl/libxl_event.c +1 -0
index eb23a93..1957505 100644
@@ -1602,6 +1602,7 @@ void libxl__ao_progress_report(libxl__egc *egc, libxl__ao *ao,
     ev->for_user = how->for_event;
     if (how->callback == dummy_asyncprogress_callback_ignore) {
         LOG(DEBUG,"ao %p: progress report: ignored",ao);
+        libxl_event_free(CTX,ev);
         /* ignore */
     } else if (how->callback) {
         libxl__aop_occurred *aop = libxl__zalloc(&egc->gc, sizeof(*aop));
Signature · 1 line
1.7.2.5
#47 lore raw

PATCH 19/19 libxl: DO NOT APPLY enforce prohibition on internal

In reply to Ian Jackson

DO NOT APPLY THIS PATCH.
It contains -Wno-error. Without that it would break the build.

Subject [PATCH] libxl: enforce prohibitions of internal callers

libxl_internal.h says:

* Functions using LIBXL__INIT_EGC may *not* generally be called from
* within libxl, because libxl__egc_cleanup may call back into the
* application. ...

and

* ... [Functions which take an ao_how] MAY NOT
* be called from inside libxl, because they can cause reentrancy
* callbacks.

However, this was not enforced. Particularly the latter restriction is easy to overlook, especially since during the transition period to the new event system we have bent this rule a couple of times, and the bad pattern simply involves passing 0 or NULL for the ao_how.

So use the compiler to enforce this property, as follows:

- Mark all functions which take a libxl_asyncop_how, or which use EGC_INIT or LIBXL__INIT_EGC, with a new annotation LIBXL_EXTERNAL_CALLERS_ONLY in the public header.

- Change the documentation comment for asynch operations and egcs to say that this should always be done.

- Arrange that if libxl.h is included via libxl_internal.h, LIBXL_EXTERNAL_CALLERS_ONLY expands to __attribute__((warning(...))), which generates a message like this:
libxl.c:1772: warning: call to 'libxl_device_disk_remove'
declared with attribute warning:
may not be called from within libxl
Otherwise, the annotation expands to nothing, so external callers are unaffected.

- Forbid inclusion of both libxl.h and libxl_internal.h unless libxl_internal.h came first, so that the above check doesn't have any loopholes. Files which include libxl_internal.h should not include libxl.h as well.

This is enforced explicitly using #error. However, in practice with the current tree it just changes the error message when this mistake is made; otherwise we would carry on to immediately following #define which would cause the compiler to complain that LIBXL_EXTERNAL_CALLERS_ONLY was redefined. Then the developer might be tempted to add a #ifndef which would be wrong - it would leave the affected translation unit unprotected by the new enforcement regime. So let's be explicit.

- Fix the one source of files which violate the above principle, the output from the idl compiler, by removing the redundant inclusion of libxl.h from the output.

In the tree I am using as a base at the time of writing, this new restriction catches three errors: two in libxl_device_disk_remove and one in libxl__device_disk_local_detach. To avoid entirely breaking my build I have also done this:

- Temporarily change -Werror to -Wno-error in the libxl Makefile.

This patch should not be applied in this form.

Cc Roger Pau Monne <[email protected]>
Cc Ian Campbell <[email protected]>
---
 tools/libxl/Makefile         |    2 +-
 tools/libxl/gentypes.py      |    1 -
 tools/libxl/libxl.h          |   34 +++++++++++++++++++++++++---------
 tools/libxl/libxl_event.h    |   21 ++++++++++++++-------
 tools/libxl/libxl_internal.h |   14 ++++++++++----
 5 files changed, 50 insertions(+), 22 deletions(-)
tools/libxl/Makefile +1 -1
index 1b81963..deff6f8 100644
@@ -11,7 +11,7 @@ MINOR = 0
 XLUMAJOR = 1.0
 XLUMINOR = 0
 
-CFLAGS += -Werror -Wno-format-zero-length -Wmissing-declarations \
+CFLAGS += -Wno-error -Wno-format-zero-length -Wmissing-declarations \
 	-Wno-declaration-after-statement -Wformat-nonliteral
 CFLAGS += -I. -fPIC
 
tools/libxl/gentypes.py +0 -1
index 3c561ba..6e83b21 100644
@@ -341,7 +341,6 @@ if __name__ == '__main__':
 #include <stdlib.h>
 #include <string.h>
 
-#include "libxl.h"
 #include "libxl_internal.h"
 
 #define LIBXL_DTOR_POISON 0xa5
tools/libxl/libxl.h +25 -9
index 10d7115..1a32d9e 100644
@@ -266,6 +266,13 @@
 #endif
 #endif
 
+/* Functions annotated with LIBXL_EXTERNAL_CALLERS_ONLY may not be
+ * called from within libxl itself. Callers outside libxl, who
+ * do not #include libxl_internal.h, are fine. */
+#ifndef LIBXL_EXTERNAL_CALLERS_ONLY
+#define LIBXL_EXTERNAL_CALLERS_ONLY /* disappears for callers outside libxl */
+#endif
+
 typedef uint8_t libxl_mac[6];
 #define LIBXL_MAC_FMT "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx"
 #define LIBXL_MAC_FMTLEN ((2*6)+5) /* 6 hex bytes plus 5 colons */
@@ -495,11 +502,13 @@ int libxl_ctx_free(libxl_ctx *ctx /* 0 is OK */);
 int libxl_domain_create_new(libxl_ctx *ctx, libxl_domain_config *d_config,
                             uint32_t *domid,
                             const libxl_asyncop_how *ao_how,
-                            const libxl_asyncprogress_how *aop_console_how);
+                            const libxl_asyncprogress_how *aop_console_how)
+                            LIBXL_EXTERNAL_CALLERS_ONLY;
 int libxl_domain_create_restore(libxl_ctx *ctx, libxl_domain_config *d_config,
                                 uint32_t *domid, int restore_fd,
                                 const libxl_asyncop_how *ao_how,
-                                const libxl_asyncprogress_how *aop_console_how);
+                                const libxl_asyncprogress_how *aop_console_how)
+                                LIBXL_EXTERNAL_CALLERS_ONLY;
   /* A progress report will be made via ao_console_how, of type
    * domain_create_console_available, when the domain's primary
    * console is available and can be connected to.
@@ -510,7 +519,8 @@ void libxl_domain_config_dispose(libxl_domain_config *d_config);
 
 int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd,
                          int flags, /* LIBXL_SUSPEND_* */
-                         const libxl_asyncop_how *ao_how);
+                         const libxl_asyncop_how *ao_how)
+                         LIBXL_EXTERNAL_CALLERS_ONLY;
 #define LIBXL_SUSPEND_DEBUG 1
 #define LIBXL_SUSPEND_LIVE 2
 
@@ -522,7 +532,8 @@ int libxl_domain_resume(libxl_ctx *ctx, uint32_t domid, int suspend_cancel);
 
 int libxl_domain_remus_start(libxl_ctx *ctx, libxl_domain_remus_info *info,
                              uint32_t domid, int send_fd, int recv_fd,
-                             const libxl_asyncop_how *ao_how);
+                             const libxl_asyncop_how *ao_how)
+                             LIBXL_EXTERNAL_CALLERS_ONLY;
 
 int libxl_domain_shutdown(libxl_ctx *ctx, uint32_t domid);
 int libxl_domain_reboot(libxl_ctx *ctx, uint32_t domid);
@@ -544,7 +555,8 @@ int libxl_domain_unpause(libxl_ctx *ctx, uint32_t domid);
 
 int libxl_domain_core_dump(libxl_ctx *ctx, uint32_t domid,
                            const char *filename,
-                           const libxl_asyncop_how *ao_how);
+                           const libxl_asyncop_how *ao_how)
+                           LIBXL_EXTERNAL_CALLERS_ONLY;
 
 int libxl_domain_setmaxmem(libxl_ctx *ctx, uint32_t domid, uint32_t target_memkb);
 int libxl_set_memory_target(libxl_ctx *ctx, uint32_t domid, int32_t target_memkb, int relative, int enforce);
@@ -653,7 +665,8 @@ void libxl_vminfo_list_free(libxl_vminfo *list, int nr);
 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,
-                             const libxl_asyncop_how *ao_how);
+                             const libxl_asyncop_how *ao_how)
+                             LIBXL_EXTERNAL_CALLERS_ONLY;
 int libxl_device_disk_destroy(libxl_ctx *ctx, uint32_t domid,
                               libxl_device_disk *disk);
 
@@ -671,7 +684,8 @@ int libxl_cdrom_insert(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk);
 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,
-                            const libxl_asyncop_how *ao_how);
+                            const libxl_asyncop_how *ao_how)
+                            LIBXL_EXTERNAL_CALLERS_ONLY;
 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);
@@ -682,14 +696,16 @@ int libxl_device_nic_getinfo(libxl_ctx *ctx, uint32_t domid,
 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,
-                            const libxl_asyncop_how *ao_how);
+                            const libxl_asyncop_how *ao_how)
+                            LIBXL_EXTERNAL_CALLERS_ONLY;
 int libxl_device_vkb_destroy(libxl_ctx *ctx, uint32_t domid, libxl_device_vkb *vkb);
 
 /* Framebuffer */
 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,
-                            const libxl_asyncop_how *ao_how);
+                            const libxl_asyncop_how *ao_how)
+                            LIBXL_EXTERNAL_CALLERS_ONLY;
 int libxl_device_vfb_destroy(libxl_ctx *ctx, uint32_t domid, libxl_device_vfb *vfb);
 
 /* PCI Passthrough */
tools/libxl/libxl_event.h +14 -7
index 713d96d..3344bc8 100644
@@ -37,7 +37,8 @@ typedef int libxl_event_predicate(const libxl_event*, void *user);
 
 int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r,
                       uint64_t typemask,
-                      libxl_event_predicate *predicate, void *predicate_user);
+                      libxl_event_predicate *predicate, void *predicate_user)
+                      LIBXL_EXTERNAL_CALLERS_ONLY;
   /* 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
@@ -48,7 +49,8 @@ int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r,
 
 int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r,
                      uint64_t typemask,
-                     libxl_event_predicate *predicate, void *predicate_user);
+                     libxl_event_predicate *predicate, void *predicate_user)
+                     LIBXL_EXTERNAL_CALLERS_ONLY;
   /* 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
@@ -256,7 +258,8 @@ struct pollfd;
  */
 int libxl_osevent_beforepoll(libxl_ctx *ctx, int *nfds_io,
                              struct pollfd *fds, int *timeout_upd,
-                             struct timeval now);
+                             struct timeval now)
+                             LIBXL_EXTERNAL_CALLERS_ONLY;
 
 /* nfds and fds[0..nfds] must be from the most recent call to
  * _beforepoll, as modified by poll.  (It is therefore not possible
@@ -271,7 +274,8 @@ int libxl_osevent_beforepoll(libxl_ctx *ctx, int *nfds_io,
  * libxl_event_check.
  */
 void libxl_osevent_afterpoll(libxl_ctx *ctx, int nfds, const struct pollfd *fds,
-                             struct timeval now);
+                             struct timeval now)
+                             LIBXL_EXTERNAL_CALLERS_ONLY;
 
 
 typedef struct libxl_osevent_hooks {
@@ -357,14 +361,16 @@ void libxl_osevent_register_hooks(libxl_ctx *ctx,
  */
 
 void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl,
-                               int fd, short events, short revents);
+                               int fd, short events, short revents)
+                               LIBXL_EXTERNAL_CALLERS_ONLY;
 
 /* Implicitly, on entry to this function the timeout has been
  * deregistered.  If _occurred_timeout is called, libxl will not
  * call timeout_deregister; if it wants to requeue the timeout it
  * will call timeout_register again.
  */
-void libxl_osevent_occurred_timeout(libxl_ctx *ctx, void *for_libxl);
+void libxl_osevent_occurred_timeout(libxl_ctx *ctx, void *for_libxl)
+                                    LIBXL_EXTERNAL_CALLERS_ONLY;
 
 
 /*======================================================================*/
@@ -506,7 +512,8 @@ void libxl_childproc_setmode(libxl_ctx *ctx, const libxl_childproc_hooks *hooks,
  * certainly need to use the self-pipe trick (or a working pselect or
  * ppoll) to implement this.
  */
-int libxl_childproc_reaped(libxl_ctx *ctx, pid_t, int status);
+int libxl_childproc_reaped(libxl_ctx *ctx, pid_t, int status)
+                           LIBXL_EXTERNAL_CALLERS_ONLY;
 
 
 /*
tools/libxl/libxl_internal.h +10 -4
index f9ee949..0972f0e 100644
@@ -52,6 +52,12 @@
 
 #include <xen/io/xenbus.h>
 
+#ifdef LIBXL_H
+# error libxl.h should be included via libxl_internal.h, not separately
+#endif
+#define LIBXL_EXTERNAL_CALLERS_ONLY \
+    __attribute__((warning("may not be called from within libxl")))
+
 #include "libxl.h"
 #include "_paths.h"
 #include "_libxl_save_msgs_callout.h"
@@ -1537,10 +1543,10 @@ libxl__device_model_version_running(libxl__gc *gc, uint32_t domid);
  *
  * Functions using LIBXL__INIT_EGC may *not* generally be called from
  * within libxl, because libxl__egc_cleanup may call back into the
- * application.  This should be documented near the function
- * prototype(s) for callers of LIBXL__INIT_EGC and EGC_INIT.  You
- * should in any case not find it necessary to call egc-creators from
- * within libxl.
+ * application.  This should be enforced by declaring all such
+ * functions in libxl.h or libxl_event.h with
+ * LIBXL_EXTERNAL_CALLERS_ONLY.  You should in any case not find it
+ * necessary to call egc-creators from within libxl.
  *
  * The callbacks must all take place with the ctx unlocked because
  * the application is entitled to reenter libxl from them.  This
Signature · 1 line
1.7.2.5
#48 lore raw

PATCH 1/1 libxl: further fixups re LIBXL_DOMAIN_TYPE process

In reply to Ian Jackson

Here's another patch which needs to go on top of my async save/restore series.

Ian.

From: Ian Jackson <[email protected]>
Subject: [PATCH] libxl: further fixups re LIBXL_DOMAIN_TYPE

* Abolish the macro LIBXL__DOMAIN_IS_TYPE which had incorrect error handlng. At every call site, replace it with an open-coded call to libxl_domain_type and check against LIBXL_DOMAIN_TYPE_INVALID.

* This involves adding an `out:' to libxl_domain_unpause.

* In libxl_domain_destroy and do_pci_add, do not `default: abort();' if the domain type cannot be found. Instead switch on LIBXL_DOMAIN_TYPE_INVALID specifically and do some actual error handling.

* In libxl__primary_console_find, remove a spurious default clause from the domain type switch.

* In libxl_domain_suspend (as reorganised) error check, check for LIBXL_DOMAIN_TYPE_INVALID and remove a pointless extra log message.

---
 tools/libxl/libxl.c          |   33 ++++++++++++++++++++++++---------
 tools/libxl/libxl_internal.h |    5 +++--
 tools/libxl/libxl_pci.c      |   18 +++++++++++++-----
 3 files changed, 40 insertions(+), 16 deletions(-)
tools/libxl/libxl.c +24 -9
index a257902..cd2dbda 100644
@@ -390,7 +390,13 @@ int libxl_domain_resume(libxl_ctx *ctx, uint32_t domid, int suspend_cancel)
         goto out;
     }
 
-    if (LIBXL__DOMAIN_IS_TYPE(gc,  domid, HVM)) {
+    libxl_domain_type type = libxl__domain_type(gc, domid);
+    if (type == LIBXL_DOMAIN_TYPE_INVALID) {
+        rc = ERROR_FAIL;
+        goto out;
+    }
+
+    if (type == LIBXL_DOMAIN_TYPE_HVM) {
         rc = libxl__domain_resume_device_model(gc, domid);
         if (rc) {
             LIBXL__LOG(ctx, LIBXL__LOG_ERROR,
@@ -723,8 +729,7 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
     int rc;
 
     libxl_domain_type type = libxl__domain_type(gc, domid);
-    if (type < 0) {
-        LOG(ERROR,"domain %"PRIu32": unable to determine domain type", domid);
+    if (type == LIBXL_DOMAIN_TYPE_INVALID) {
         rc = ERROR_FAIL;
         goto out_err;
     }
@@ -789,7 +794,13 @@ int libxl_domain_unpause(libxl_ctx *ctx, uint32_t domid)
     char *state;
     int ret, rc = 0;
 
-    if (LIBXL__DOMAIN_IS_TYPE(gc,  domid, HVM)) {
+    libxl_domain_type type = libxl__domain_type(gc, domid);
+    if (type == LIBXL_DOMAIN_TYPE_INVALID) {
+        rc = ERROR_FAIL;
+        goto out;
+    }
+
+    if (type == LIBXL_DOMAIN_TYPE_HVM) {
         path = libxl__sprintf(gc, "/local/domain/0/device-model/%d/state", domid);
         state = libxl__xs_read(gc, XBT_NULL, path);
         if (state != NULL && !strcmp(state, "paused")) {
@@ -803,6 +814,7 @@ int libxl_domain_unpause(libxl_ctx *ctx, uint32_t domid)
         LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "unpausing domain %d", domid);
         rc = ERROR_FAIL;
     }
+ out:
     GC_FREE;
     return rc;
 }
@@ -814,7 +826,11 @@ int libxl__domain_pvcontrol_available(libxl__gc *gc, uint32_t domid)
     unsigned long pvdriver = 0;
     int ret;
 
-    if (LIBXL__DOMAIN_IS_TYPE(gc, domid, PV))
+    libxl_domain_type domtype = libxl__domain_type(gc, domid);
+    if (domtype == LIBXL_DOMAIN_TYPE_INVALID)
+        return ERROR_FAIL;
+
+    if (domtype == LIBXL_DOMAIN_TYPE_PV)
         return 1;
 
     ret = xc_get_hvm_param(ctx->xch, domid, HVM_PARAM_CALLBACK_IRQ, &pvdriver);
@@ -1214,8 +1230,9 @@ int libxl_domain_destroy(libxl_ctx *ctx, uint32_t domid)
         pid = libxl__xs_read(gc, XBT_NULL, libxl__sprintf(gc, "/local/domain/%d/image/device-model-pid", domid));
         dm_present = (pid != NULL);
         break;
-    default:
-        abort();
+    case LIBXL_DOMAIN_TYPE_INVALID:
+        rc = ERROR_FAIL;
+        goto out;
     }
 
     dom_path = libxl__xs_get_dompath(gc, domid);
@@ -1363,8 +1380,6 @@ static int libxl__primary_console_find(libxl_ctx *ctx, uint32_t domid_vm,
         case LIBXL_DOMAIN_TYPE_INVALID:
             rc = ERROR_INVAL;
             goto out;
-        default:
-            abort();
         }
     }
 
tools/libxl/libxl_internal.h +3 -2
index f9ee949..c9725a3 100644
@@ -797,8 +797,7 @@ _hidden int libxl__domain_cpupool(libxl__gc *gc, uint32_t domid);
 _hidden libxl_scheduler libxl__domain_scheduler(libxl__gc *gc, uint32_t domid);
 _hidden int libxl__sched_set_params(libxl__gc *gc, uint32_t domid,
                                     libxl_domain_sched_params *scparams);
-#define LIBXL__DOMAIN_IS_TYPE(gc, domid, type) \
-    libxl__domain_type((gc), (domid)) == LIBXL_DOMAIN_TYPE_##type
+
 typedef struct {
     uint32_t store_port;
     uint32_t store_domid;
@@ -841,7 +840,9 @@ _hidden int libxl__domain_resume_device_model(libxl__gc *gc, uint32_t domid);
 
 _hidden void libxl__userdata_destroyall(libxl__gc *gc, uint32_t domid);
 
+/* returns 0 or 1, or a libxl error code */
 _hidden int libxl__domain_pvcontrol_available(libxl__gc *gc, uint32_t domid);
+
 _hidden char * libxl__domain_pvcontrol_read(libxl__gc *gc,
                                             xs_transaction_t t, uint32_t domid);
 _hidden int libxl__domain_pvcontrol_write(libxl__gc *gc, xs_transaction_t t,
tools/libxl/libxl_pci.c +13 -5
index de1b79f..81438be 100644
@@ -128,7 +128,11 @@ static int libxl__device_pci_add_xenstore(libxl__gc *gc, uint32_t domid, libxl_d
     if (!num_devs)
         return libxl__create_pci_backend(gc, domid, pcidev, 1);
 
-    if (!starting && LIBXL__DOMAIN_IS_TYPE(gc, domid, PV)) {
+    libxl_domain_type domtype = libxl__domain_type(gc, domid);
+    if (domtype == LIBXL_DOMAIN_TYPE_INVALID)
+        return ERROR_FAIL;
+
+    if (!starting && domtype == LIBXL_DOMAIN_TYPE_PV) {
         if (libxl__wait_for_backend(gc, be_path, "4") < 0)
             return ERROR_FAIL;
     }
@@ -171,7 +175,11 @@ static int libxl__device_pci_remove_xenstore(libxl__gc *gc, uint32_t domid, libx
         return ERROR_INVAL;
     num = atoi(num_devs);
 
-    if (LIBXL__DOMAIN_IS_TYPE(gc, domid, PV)) {
+    libxl_domain_type domtype = libxl__domain_type(gc, domid);
+    if (domtype == LIBXL_DOMAIN_TYPE_INVALID)
+        return ERROR_FAIL;
+
+    if (domtype == LIBXL_DOMAIN_TYPE_PV) {
         if (libxl__wait_for_backend(gc, be_path, "4") < 0) {
             LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "pci backend at %s is not ready", be_path);
             return ERROR_FAIL;
@@ -199,7 +207,7 @@ retry_transaction:
         if (errno == EAGAIN)
             goto retry_transaction;
 
-    if (LIBXL__DOMAIN_IS_TYPE(gc, domid, PV)) {
+    if (domtype == LIBXL_DOMAIN_TYPE_PV) {
         if (libxl__wait_for_backend(gc, be_path, "4") < 0) {
             LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "pci backend at %s is not ready", be_path);
             return ERROR_FAIL;
@@ -939,8 +947,8 @@ static int do_pci_add(libxl__gc *gc, uint32_t domid, libxl_device_pci *pcidev, i
         }
         break;
     }
-    default:
-        abort();
+    case LIBXL_DOMAIN_TYPE_INVALID:
+        return ERROR_FAIL;
     }
 out:
     if (!libxl_is_stubdom(ctx, domid, NULL)) {
Signature · 1 line
tg: (966769c..) t/xen/xl.domain-type-fixups-v2 (depends on: t/xen/xl.ao.progress-ignored-free-event)
Acked-by on v1 1/1
#49 lore raw

Re: [PATCH] libxl: further fixups re LIBXL_DOMAIN_TYPE process

Quoted 10 lines · Ian Jackson

Here's another patch which needs to go on top of my async save/restore series.

Ian.

From: Ian Jackson <[email protected]>
Subject: [PATCH] libxl: further fixups re LIBXL_DOMAIN_TYPE

* Abolish the macro LIBXL__DOMAIN_IS_TYPE which had incorrect error handlng. At every call site, replace it with an open-coded call to

handling

Quoted 9 lines

libxl_domain_type and check against LIBXL_DOMAIN_TYPE_INVALID.

* This involves adding an `out:' to libxl_domain_unpause.

* In libxl_domain_destroy and do_pci_add, do not `default: abort();' if the domain type cannot be found. Instead switch on LIBXL_DOMAIN_TYPE_INVALID specifically and do some actual error handling.

Quoted 7 lines

* In libxl__primary_console_find, remove a spurious default clause from the domain type switch.

* In libxl_domain_suspend (as reorganised) error check, check for LIBXL_DOMAIN_TYPE_INVALID and remove a pointless extra log message.

#50 lore raw
In reply to Ian Jackson
Quoted 2 lines · Ian Jackson

This is v3 of my series to asyncify save/restore, rebased to current tip, retested, and with all comments addressed.

There's quite a lot of combinations which need testing here (PV, HVM, HVM w/ stub dm, old vs new qemu etc etc), which of those have you tried?

I tried a simple localhost migrate of a PV guest and:

        # xl -vvv migrate d32-1 localhost
        migration target: Ready to receive domain.
        Saving to migration stream new xl format (info 0x0/0x0/3541)
        libxl: debug: libxl.c:722:libxl_domain_suspend: ao 0x8069720: create: how=(nil) callback=(nil) poller=0x80696c8
        Loading new save file <incoming migration stream> (new xl fmt info 0x0/0x0/3541)
         Savefile contains xl domain config
        libxl: debug: libxl_dom.c:969:libxl__toolstack_save: domain=2 toolstack data size=8
        libxl: debug: libxl.c:745:libxl_domain_suspend: ao 0x8069720: inprogress: poller=0x80696c8, flags=i
        libxl-save-helper: debug: starting save: Success
        xc: detail: Had 0 unexplained entries in p2m table
        xc: Saving memory: iter 0 (last sent 0 skipped 0): 0/131072    0%

at which point it appears to just stop.

        # strace -p 2872 # /usr/lib/xen/bin/libxl-save-helper --save-domain 8 2 0 0 1 0 0 12 8 72
        Process 2872 attached - interrupt to quit
        write(8, 0xb5d31000, 1974272^C <unfinished ...>
        Process 2872 detached
        # strace -p 2866 # /usr/lib/xen/bin/libxl-save-helper --restore-domain 0 3 1 0 2 0 0 1 0 0 0
        Process 2866 attached - interrupt to quit
        read(0, ^C <unfinished ...>
        # strace -p 4070 # xl -vvv migrate d32-1 localhost
        Process 4070 attached - interrupt to quit
        restart_syscall(<... resuming interrupted call ...>
        # strace -p 4074 # xl migrate-receive
        Process 4074 attached - interrupt to quit
        restart_syscall(<... resuming interrupted call ...>

So the saver seems to be blocked writing to fd 8, which is argv[1] == io_fd.

Also FWIW:

        # xl list
        Name                                        ID   Mem VCPUs	State	Time(s)
        Domain-0                                     0   511     4     r-----      24.5
        d32-1                                        2   128     4     -b----       0.4
        d32-1--incoming                              3     0     0     --p---       0.0

/var/log/xen/xl-d32-1.log is just "Waiting for domain d32-1 (domid 9) to die [pid 4045]" (nb: this was a newer attempt than the ones above, to be sure I was looking at the right log, so the domid's don't match, 9 == d32-1 not the incoming one). There is no xl log for the incoming domain.

Also it'd be worth pinging/CCing Shriram next time to get him to sanity test the Remus cases too.

I'm in the middle of reviewing #5/19 (the meat), I'll keep going although I doubt I'll spot the cause of this...

Ian.

#51 lore raw
Quoted 20 lines · Ian Campbell
Quoted 2 lines · Ian Jackson

This is v3 of my series to asyncify save/restore, rebased to current tip, retested, and with all comments addressed.

There's quite a lot of combinations which need testing here (PV, HVM, HVM w/ stub dm, old vs new qemu etc etc), which of those have you tried?

I tried a simple localhost migrate of a PV guest and:

        # xl -vvv migrate d32-1 localhost
        migration target: Ready to receive domain.
        Saving to migration stream new xl format (info 0x0/0x0/3541)
        libxl: debug: libxl.c:722:libxl_domain_suspend: ao 0x8069720: create: how=(nil) callback=(nil) poller=0x80696c8
        Loading new save file <incoming migration stream> (new xl fmt info 0x0/0x0/3541)
         Savefile contains xl domain config
        libxl: debug: libxl_dom.c:969:libxl__toolstack_save: domain=2 toolstack data size=8
        libxl: debug: libxl.c:745:libxl_domain_suspend: ao 0x8069720: inprogress: poller=0x80696c8, flags=i
        libxl-save-helper: debug: starting save: Success
        xc: detail: Had 0 unexplained entries in p2m table
        xc: Saving memory: iter 0 (last sent 0 skipped 0): 0/131072    0%
Quoted 7 lines

at which point it appears to just stop.

        # strace -p 2872 # /usr/lib/xen/bin/libxl-save-helper --save-domain 8 2 0 0 1 0 0 12 8 72
        Process 2872 attached - interrupt to quit
        write(8, 0xb5d31000, 1974272^C <unfinished ...>
        Process 2872 detached
        # strace -p 2866 # /usr/lib/xen/bin/libxl-save-helper --restore-domain 0 3 1 0 2 0 0 1 0 0 0

The first zero here is restore_fd, I think. But I read in the comment in the helper:
> + * The helper talks on stdin and stdout, in binary in machine > + * endianness. The helper speaks first, and only when it has a > + * callback to make. It writes a 16-bit number being the message > + * length, and then the message body.

So restore_fd == stdin => running two protocols over the same fd?

Quoted 37 lines

Process 2866 attached - interrupt to quit read(0, ^C <unfinished ...>
# strace -p 4070 # xl -vvv migrate d32-1 localhost Process 4070 attached - interrupt to quit restart_syscall(<... resuming interrupted call ...> # strace -p 4074 # xl migrate-receive Process 4074 attached - interrupt to quit restart_syscall(<... resuming interrupted call ...>

So the saver seems to be blocked writing to fd 8, which is argv[1] == io_fd.

Also FWIW:

        # xl list
        Name                                        ID   Mem VCPUs	State	Time(s)
        Domain-0                                     0   511     4     r-----      24.5
        d32-1                                        2   128     4     -b----       0.4
        d32-1--incoming                              3     0     0     --p---       0.0

/var/log/xen/xl-d32-1.log is just "Waiting for domain d32-1 (domid 9) to die [pid 4045]" (nb: this was a newer attempt than the ones above, to be sure I was looking at the right log, so the domid's don't match, 9 == d32-1 not the incoming one). There is no xl log for the incoming domain.

Also it'd be worth pinging/CCing Shriram next time to get him to sanity test the Remus cases too.

I'm in the middle of reviewing #5/19 (the meat), I'll keep going although I doubt I'll spot the cause of this...

Ian.

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

#52 lore raw
Quoted 29 lines · Ian Campbell
Quoted 20 lines · Ian Campbell
Quoted 2 lines · Ian Jackson

This is v3 of my series to asyncify save/restore, rebased to current tip, retested, and with all comments addressed.

There's quite a lot of combinations which need testing here (PV, HVM, HVM w/ stub dm, old vs new qemu etc etc), which of those have you tried?

I tried a simple localhost migrate of a PV guest and:

        # xl -vvv migrate d32-1 localhost
        migration target: Ready to receive domain.
        Saving to migration stream new xl format (info 0x0/0x0/3541)
        libxl: debug: libxl.c:722:libxl_domain_suspend: ao 0x8069720: create: how=(nil) callback=(nil) poller=0x80696c8
        Loading new save file <incoming migration stream> (new xl fmt info 0x0/0x0/3541)
         Savefile contains xl domain config
        libxl: debug: libxl_dom.c:969:libxl__toolstack_save: domain=2 toolstack data size=8
        libxl: debug: libxl.c:745:libxl_domain_suspend: ao 0x8069720: inprogress: poller=0x80696c8, flags=i
        libxl-save-helper: debug: starting save: Success
        xc: detail: Had 0 unexplained entries in p2m table
        xc: Saving memory: iter 0 (last sent 0 skipped 0): 0/131072    0%
Quoted 7 lines

at which point it appears to just stop.

        # strace -p 2872 # /usr/lib/xen/bin/libxl-save-helper --save-domain 8 2 0 0 1 0 0 12 8 72
        Process 2872 attached - interrupt to quit
        write(8, 0xb5d31000, 1974272^C <unfinished ...>
        Process 2872 detached
        # strace -p 2866 # /usr/lib/xen/bin/libxl-save-helper --restore-domain 0 3 1 0 2 0 0 1 0 0 0
Quoted 8 lines

The first zero here is restore_fd, I think. But I read in the comment in the helper:
> + * The helper talks on stdin and stdout, in binary in machine > + * endianness. The helper speaks first, and only when it has a > + * callback to make. It writes a 16-bit number being the message > + * length, and then the message body.

So restore_fd == stdin => running two protocols over the same fd?

Oh, right, migrate-receive takes the migration fd on stdin doesn't it, so that's where it comes from. I still suspect it is wrong. Might need to dup the input onto a safe fd?

BTW, since I've been ctrl-c'ing "xl migrate" a bunch I noticed that we seem to leak an "xl migrate-receive" and the restore side helper process. Probably pre-existing but I thought it worth mentioning.

Quoted 45 lines
Quoted 30 lines

Process 2866 attached - interrupt to quit read(0, ^C <unfinished ...>
# strace -p 4070 # xl -vvv migrate d32-1 localhost Process 4070 attached - interrupt to quit restart_syscall(<... resuming interrupted call ...> # strace -p 4074 # xl migrate-receive Process 4074 attached - interrupt to quit restart_syscall(<... resuming interrupted call ...>

So the saver seems to be blocked writing to fd 8, which is argv[1] == io_fd.

Also FWIW:

        # xl list
        Name                                        ID   Mem VCPUs	State	Time(s)
        Domain-0                                     0   511     4     r-----      24.5
        d32-1                                        2   128     4     -b----       0.4
        d32-1--incoming                              3     0     0     --p---       0.0

/var/log/xen/xl-d32-1.log is just "Waiting for domain d32-1 (domid 9) to die [pid 4045]" (nb: this was a newer attempt than the ones above, to be sure I was looking at the right log, so the domid's don't match, 9 == d32-1 not the incoming one). There is no xl log for the incoming domain.

Also it'd be worth pinging/CCing Shriram next time to get him to sanity test the Remus cases too.

I'm in the middle of reviewing #5/19 (the meat), I'll keep going although I doubt I'll spot the cause of this...

Quoted 8 lines

Ian.

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

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

#53 lore raw
In reply to Ian Campbell
Quoted 8 lines · Ian Campbell
Quoted 2 lines · Ian Jackson

This is v3 of my series to asyncify save/restore, rebased to current tip, retested, and with all comments addressed.

There's quite a lot of combinations which need testing here (PV, HVM, HVM w/ stub dm, old vs new qemu etc etc), which of those have you tried?

I tried a simple localhost migrate of a PV guest and:

As a separate issue in "xl -vvv save d32-1 /scratch/SAVE" I no longer see the progress messages (xxx% complete etc). I saw something which looked like support for logging progress messages so I was a bit surprised...

The complete output is

        # xl -vvv save d32-1 /scratch/SAVE
        Saving to /scratch/SAVE new xl format (info 0x0/0x0/3541)
        libxl: debug: libxl.c:722:libxl_domain_suspend: ao 0x80696c8: create: how=(nil) callback=(nil) poller=0x8069708
        libxl: debug: libxl_dom.c:969:libxl__toolstack_save: domain=14 toolstack data size=8
        libxl: debug: libxl.c:745:libxl_domain_suspend: ao 0x80696c8: inprogress: poller=0x8069708, flags=i
        libxl-save-helper: debug: starting save: Success
        libxl: debug: libxl_dom.c:798:libxl__domain_suspend_common_callback: issuing PV suspend request via XenBus control node
        libxl: debug: libxl_dom.c:802:libxl__domain_suspend_common_callback: wait for the guest to acknowledge suspend request
        libxl: debug: libxl_dom.c:849:libxl__domain_suspend_common_callback: guest acknowledged suspend request
        libxl: debug: libxl_dom.c:853:libxl__domain_suspend_common_callback: wait for the guest to suspend
        libxl: debug: libxl_dom.c:867:libxl__domain_suspend_common_callback: guest has suspended
        xc: detail: Had 0 unexplained entries in p2m table
        xc: debug: outbuf_write: 4194304 > 4177904@12599312
        xc: debug: outbuf_write: 2527232 > 2514932@14262284
        xc: debug: outbuf_write: 4194304 > 1650672@15126544
        xc: debug: outbuf_write: 4194304 > 4182004@12595212
        xc: debug: outbuf_write: 4194304 > 4182004@12595212
        xc: debug: outbuf_write: 4194304 > 4182004@12595212
        xc: debug: outbuf_write: 4194304 > 4182004@12595212
        xc: debug: outbuf_write: 3424256 > 3411956@13365260
        xc: debug: outbuf_write: 753664 > 753648@16023568
        xc: detail: delta 90669ms, dom0 2%, target 0%, sent 11Mb/s, dirtied 0Mb/s 0 pages
        xc: detail: Total pages sent= 32768 (0.25x)
        xc: detail: (of which 0 were fixups)
        xc: detail: All memory is saved
        xc: detail: Save exit rc=0
        libxl-save-helper: debug: complete r=0: Success
        libxl: debug: libxl_event.c:1434:libxl__ao_complete: ao 0x80696c8: complete, rc=0
        libxl: debug: libxl_event.c:1406:libxl__ao__destroy: ao 0x80696c8: destroy
        libxl: debug: libxl_dm.c:1139:libxl__destroy_device_model: Device Model signaled

Restore worked BTW but was a bit spammy with:

        xc: debug: batch 1024

(maybe not your fault...)

Ian.

#54 lore raw

Ian Campbell writes ("Re: [Xen-devel] [PATCH v3 00/18] libxl: domain save/restore: run in a separate process"):

Quoted 3 lines · Ian Campbell
Quoted 2 lines

There's quite a lot of combinations which need testing here (PV, HVM, HVM w/ stub dm, old vs new qemu etc etc), which of those have you tried?

I haven't tried stub dm or new qemu. I have tried save/restore of both PV and HVM. I have also done localhost migration - although perhaps not as often or in as many combinations.

Quoted 6 lines
Quoted 1 line

I tried a simple localhost migrate of a PV guest and:

As a separate issue in "xl -vvv save d32-1 /scratch/SAVE" I no longer see the progress messages (xxx% complete etc). I saw something which looked like support for logging progress messages so I was a bit surprised...

I'll look into this. I think you're right about the fd bug too. I don't know why this didn't go wrong for me.

Ian.

#55 lore raw

Re: [PATCH v3 00/18] libxl: domain save/restore: run in a separate process [and 4 more messages]

In reply to Ian Campbell

To: Ian Campbell <[email protected]>
Cc: "[email protected]" <[email protected]>
Subject: Re: [Xen-devel] [PATCH v3 00/18] libxl: domain save/restore: run in
a separate process
In-Reply-To: <[email protected]>
References: <[email protected]>

	<[email protected]>

X-Mailer: VM 8.1.0 under 23.2.1 (i486-pc-linux-gnu)
FCC: ~/mail/Outbound
--text follows this line--
Ian Campbell writes ("Re: [Xen-devel] [PATCH v3 00/18] libxl: domain save/restore: run in a separate process"):

Quoted 8 lines · Ian Jackson
Quoted 2 lines

This is v3 of my series to asyncify save/restore, rebased to current tip, retested, and with all comments addressed.

There's quite a lot of combinations which need testing here (PV, HVM, HVM w/ stub dm, old vs new qemu etc etc), which of those have you tried?

I tried a simple localhost migrate of a PV guest and:

Thanks for looking at all this and for testing it. I thought I had tested localhost migration, but my shell history reveals, now that it is pointed out to me, that in my tests the migration receiver process had been running the old version of libxl.

Ian Campbell writes ("Re: [Xen-devel] [PATCH v3 00/18] libxl: domain save/restore: run in a separate process"):

Quoted 8 lines

The first zero here is restore_fd, I think. But I read in the comment in the helper:
> + * The helper talks on stdin and stdout, in binary in machine > + * endianness. The helper speaks first, and only when it has a > + * callback to make. It writes a 16-bit number being the message > + * length, and then the message body.

So restore_fd == stdin => running two protocols over the same fd?

This is indeed why it's not working. I have repro'd the failure and my tree now has a fix in it.

Ian Campbell writes ("Re: [Xen-devel] [PATCH v3 00/18] libxl: domain save/restore: run in a separate process"):

Quoted 3 lines

Oh, right, migrate-receive takes the migration fd on stdin doesn't it, so that's where it comes from. I still suspect it is wrong. Might need to dup the input onto a safe fd?

Indeed.

Quoted 3 lines

BTW, since I've been ctrl-c'ing "xl migrate" a bunch I noticed that we seem to leak an "xl migrate-receive" and the restore side helper process. Probably pre-existing but I thought it worth mentioning.

I'll look into this.

Thanks,
Ian.

#56 lore raw

Re: [PATCH v3 00/18] libxl: domain save/restore: run in a separate process [and 4 more messages]

Ian Jackson writes ("Re: [Xen-devel] [PATCH v3 00/18] libxl: domain save/restore: run in a separate process [and 4 more messages]"):

Quoted 2 lines

To: Ian Campbell <[email protected]>
Cc: "[email protected]" <[email protected]>

Uh, sorry about the duplicated header.

Quoted 6 lines

Ian Campbell writes ("Re: [Xen-devel] [PATCH v3 00/18] libxl: domain save/restore: run in a separate process"):

Quoted 3 lines

BTW, since I've been ctrl-c'ing "xl migrate" a bunch I noticed that we seem to leak an "xl migrate-receive" and the restore side helper process. Probably pre-existing but I thought it worth mentioning.

I'll look into this.

This seems better now, at the tip of my series, at least. If I ctrl-c xl migrate running via ssh then all the receiver processes, and the relevant domain, seem to get cleaned up.

If I do xl migrate not running via ssh, eg
xl migrate -s '' debian.guest.osstest 'xl migrate-recieve'
then both the sender and receiver get my ^C so we leak the domain. I think that's the expected behaviour.

Ian.