Skip to contentSkip to conversation

Libxl migration v2

PATCH Superseded Andrew Cooper 4 participants 62 messages Jul 13, 2015 – Jul 14, 2015

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v3 cover Libxl migration v2

This series adds support for the libxl migration v2 stream, and untangles the existing layering violations of the toolstack and qemu records.

It can be found on the branch "libxl-migv2-v3"
git://xenbits.xen.org/people/andrewcoop/xen.git
http://xenbits.xen.org/git-http/people/andrewcoop/xen.git

No major changes over v2, but a lot of minor changes following review.

At the end of the series, legacy migration is no longer used.

The Remus code is untested by me. All other combinations of suspend/migrate/resume have been tested with PV and HVM guests (qemu-trad and qemu-upstream), including 32 -> 64 bit migration (which was the underlying bug causing us to write migration v2 in the first place).

Anyway, thoughts/comments welcome. Please test!

~Andrew

Summary of Acks/Modified/New from v2

A bsd-sys-queue-h-seddery: Massage `offsetof'
A tools/libxc: Always compile the compat qemu variables into xc_sr_context
A tools/libxl: Introduce ROUNDUP()
AM tools/libxl: Introduce libxl__kill()
A tools/libxl: Stash all restore parameters in domain_create_state
A tools/libxl: Split libxl__domain_create_state.restore_fd in two
M tools/libxl: Extra management APIs for the save helper
N tools/libxl: Add save_helper_state pointers to libxl__xc_domain_{save,restore}()
A tools/xl: Mandatory flag indicating the format of the migration stream
A docs: Libxl migration v2 stream specification
A tools/python: Libxc migration v2 infrastructure
A tools/python: Libxl migration v2 infrastructure
A tools/python: Other migration infrastructure
A tools/python: Verification utility for v2 stream spec compliance
A tools/python: Conversion utility for legacy migration streams
A tools/libxl: Migration v2 stream format

 M  tools/libxl: Infrastructure for reading a libxl migration v2 stream
 M  tools/libxl: Infrastructure to convert a legacy stream
 M  tools/libxl: Convert a legacy stream if needed
 M  tools/libxc+libxl+xl: Restore v2 streams
 M  tools/libxl: Infrastructure for writing a v2 stream
 M  tools/libxc+libxl+xl: Save v2 streams
A   docs/libxl: Introduce CHECKPOINT_END to support migration v2 remus streams
AM  tools/libxl: Write checkpoint records into the stream
 M  tools/libx{c,l}: Introduce restore_callbacks.checkpoint()
 M  tools/libxl: Handle checkpoint records in a libxl migration v2 stream
A   tools/libxc: Drop all XG_LIBXL_HVM_COMPAT code from libxc
A   tools/libxl: Drop all knowledge of toolstack callbacks

Andrew Cooper (24):
tools/libxc: Always compile the compat qemu variables into xc_sr_context tools/libxl: Introduce ROUNDUP()
tools/libxl: Introduce libxl__kill()
tools/libxl: Stash all restore parameters in domain_create_state tools/libxl: Split libxl__domain_create_state.restore_fd in two tools/libxl: Extra management APIs for the save helper
tools/libxl: Add save_helper_state pointers to libxl__xc_domain_{save,restore}() tools/xl: Mandatory flag indicating the format of the migration stream
docs: Libxl migration v2 stream specification
tools/python: Libxc migration v2 infrastructure
tools/python: Libxl migration v2 infrastructure
tools/python: Other migration infrastructure
tools/python: Verification utility for v2 stream spec compliance tools/python: Conversion utility for legacy migration streams tools/libxl: Infrastructure to convert a legacy stream
tools/libxl: Convert a legacy stream if needed tools/libxc+libxl+xl: Restore v2 streams
tools/libxc+libxl+xl: Save v2 streams
docs/libxl: Introduce CHECKPOINT_END to support migration v2 remus streams tools/libxl: Write checkpoint records into the stream tools/libx{c,l}: Introduce restore_callbacks.checkpoint() tools/libxl: Handle checkpoint records in a libxl migration v2 stream tools/libxc: Drop all XG_LIBXL_HVM_COMPAT code from libxc tools/libxl: Drop all knowledge of toolstack callbacks

Ian Jackson (1):
bsd-sys-queue-h-seddery: Massage `offsetof'

Ross Lagerwall (3):
tools/libxl: Migration v2 stream format
tools/libxl: Infrastructure for reading a libxl migration v2 stream tools/libxl: Infrastructure for writing a v2 stream

 docs/specs/libxl-migration-stream.pandoc           |  217 ++++++
 tools/include/xen-external/bsd-sys-queue-h-seddery |    2 +
 tools/libxc/Makefile                               |    2 -
 tools/libxc/include/xenguest.h                     |    7 +
 tools/libxc/xc_sr_common.h                         |   12 +-
 tools/libxc/xc_sr_restore.c                        |   71 +-
 tools/libxc/xc_sr_restore_x86_hvm.c                |  124 ----
 tools/libxc/xc_sr_save_x86_hvm.c                   |   36 -
 tools/libxl/Makefile                               |    7 +
 tools/libxl/libxl.h                                |   19 +
 tools/libxl/libxl_aoutils.c                        |   15 +
 tools/libxl/libxl_convert_callout.c                |  158 ++++
 tools/libxl/libxl_create.c                         |   91 ++-
 tools/libxl/libxl_dom.c                            |  107 +--
 tools/libxl/libxl_internal.h                       |  172 ++++-
 tools/libxl/libxl_no_convert_callout.c             |   35 +
 tools/libxl/libxl_save_callout.c                   |  117 ++-
 tools/libxl/libxl_save_helper.c                    |   33 +-
 tools/libxl/libxl_save_msgs_gen.pl                 |    9 +-
 tools/libxl/libxl_sr_stream_format.h               |   58 ++
 tools/libxl/libxl_stream_read.c                    |  768 ++++++++++++++++++++
 tools/libxl/libxl_stream_write.c                   |  525 +++++++++++++
 tools/libxl/libxl_types.idl                        |    1 +
 tools/libxl/xl_cmdimpl.c                           |    9 +-
 tools/python/Makefile                              |    4 +
 tools/python/scripts/convert-legacy-stream         |  678 +++++++++++++++++
 tools/python/scripts/verify-stream-v2              |  174 +++++
 tools/python/setup.py                              |    1 +
 tools/python/xen/migration/legacy.py               |  279 +++++++
 tools/python/xen/migration/libxc.py                |  446 ++++++++++++
 tools/python/xen/migration/libxl.py                |  199 +++++
 tools/python/xen/migration/public.py               |   21 +
 tools/python/xen/migration/tests.py                |   54 ++
 tools/python/xen/migration/verify.py               |   37 +
 tools/python/xen/migration/xl.py                   |   12 +
 35 files changed, 4071 insertions(+), 429 deletions(-)
 create mode 100644 docs/specs/libxl-migration-stream.pandoc
 create mode 100644 tools/libxl/libxl_convert_callout.c
 create mode 100644 tools/libxl/libxl_no_convert_callout.c
 create mode 100644 tools/libxl/libxl_sr_stream_format.h
 create mode 100644 tools/libxl/libxl_stream_read.c
 create mode 100644 tools/libxl/libxl_stream_write.c
 create mode 100755 tools/python/scripts/convert-legacy-stream
 create mode 100755 tools/python/scripts/verify-stream-v2
 create mode 100644 tools/python/xen/migration/__init__.py
 create mode 100644 tools/python/xen/migration/legacy.py
 create mode 100644 tools/python/xen/migration/libxc.py
 create mode 100644 tools/python/xen/migration/libxl.py
 create mode 100644 tools/python/xen/migration/public.py
 create mode 100644 tools/python/xen/migration/tests.py
 create mode 100644 tools/python/xen/migration/verify.py
 create mode 100644 tools/python/xen/migration/xl.py

--
1.7.10.4

#1 lore raw

PATCH v3 1/28 bsd-sys-queue-h-seddery: Massage `offsetof'

From: Ian Jackson <[email protected]>

For some reason BSD's queue.h uses `__offsetof'. It expects it to work just like offsetof. So use offsetof.

---
 tools/include/xen-external/bsd-sys-queue-h-seddery |    2 ++
 1 file changed, 2 insertions(+)
tools/include/xen-external/bsd-sys-queue-h-seddery +2 -0
index 7a957e3..3f8716d 100755
@@ -69,4 +69,6 @@ s/\b struct \s+ type \b/type/xg;
 
 s,^\#include.*sys/cdefs.*,/* $& */,xg;
 
+s,\b __offsetof \b ,offsetof,xg;
+
 s/\b( NULL )/0/xg;
Signature · 1 line
1.7.10.4
#2 lore raw

PATCH v3 2/28 tools/libxc: Always compile the compat qemu variables into xc_sr_context

In reply to Andrew Cooper

This is safe (as the variables will simply be unused), and is required for correct compilation when midway through untangling the libxc/libxl interaction.

The #define is left in place to highlight that the variables can be removed once the untangling is complete.

---
 tools/libxc/xc_sr_common.h |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tools/libxc/xc_sr_common.h +2 -2
index 565c5da..08c66db 100644
@@ -307,10 +307,10 @@ struct xc_sr_context
                     void *context;
                     size_t contextsz;
 
-#ifdef XG_LIBXL_HVM_COMPAT
+/* #ifdef XG_LIBXL_HVM_COMPAT */
                     uint32_t qlen;
                     void *qbuf;
-#endif
+/* #endif */
                 } restore;
             };
         } x86_hvm;
Signature · 1 line
1.7.10.4
#3 lore raw

PATCH v3 3/28 tools/libxl: Introduce ROUNDUP()

In reply to Andrew Cooper

This is the same as is used by libxc.

---
 tools/libxl/libxl_internal.h |    3 +++
 1 file changed, 3 insertions(+)
tools/libxl/libxl_internal.h +3 -0
index 5235d25..19fc425 100644
@@ -110,6 +110,9 @@
 
 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
 
+#define ROUNDUP(_val, _order)                                           \
+    (((unsigned long)(_val)+(1UL<<(_order))-1) & ~((1UL<<(_order))-1))
+
 #define min(X, Y) ({                             \
             const typeof (X) _x = (X);           \
             const typeof (Y) _y = (Y);           \
Signature · 1 line
1.7.10.4
#4 lore raw

PATCH v3 4/28 tools/libxl: Introduce libxl__kill()

In reply to Andrew Cooper

as a wrapper to kill(2), and use it in preference to sendsig in libxl_save_callout.c.

---
v3: Fix typo, add _hidden

Logically new in v2 - split out from a v1 change which was itself a cherrypick-and-modify from the AO Abort series

---
 tools/libxl/libxl_aoutils.c      |   15 +++++++++++++++
 tools/libxl/libxl_internal.h     |    2 ++
 tools/libxl/libxl_save_callout.c |   10 ++--------
 3 files changed, 19 insertions(+), 8 deletions(-)
tools/libxl/libxl_aoutils.c +15 -0
index 0931eee..274ef39 100644
@@ -621,3 +621,18 @@ bool libxl__async_exec_inuse(const libxl__async_exec_state *aes)
     assert(time_inuse == child_inuse);
     return child_inuse;
 }
+
+void libxl__kill(libxl__gc *gc, pid_t pid, int sig, const char *what)
+{
+    int r = kill(pid, sig);
+    if (r) LOGE(WARN, "failed to kill() %s [%lu] (signal %d)",
+                what, (unsigned long)pid, sig);
+}
+
+/*
+ * Local variables:
+ * mode: C
+ * c-basic-offset: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
tools/libxl/libxl_internal.h +2 -0
index 19fc425..7ccbf55 100644
@@ -2244,6 +2244,8 @@ struct libxl__async_exec_state {
 int libxl__async_exec_start(libxl__async_exec_state *aes);
 bool libxl__async_exec_inuse(const libxl__async_exec_state *aes);
 
+_hidden void libxl__kill(libxl__gc *gc, pid_t pid, int sig, const char *what);
+
 /*----- device addition/removal -----*/
 
 typedef struct libxl__ao_device libxl__ao_device;
tools/libxl/libxl_save_callout.c +2 -8
index 087c2d5..b82a5c1 100644
@@ -244,12 +244,6 @@ static void run_helper(libxl__egc *egc, libxl__save_helper_state *shs,
     libxl__carefd_close(childs_pipes[1]);
     helper_failed(egc, shs, rc);;
 }
-static void sendsig(libxl__gc *gc, libxl__save_helper_state *shs, int sig)
-{
-    int r = kill(shs->child.pid, sig);
-    if (r) LOGE(WARN, "failed to kill save/restore helper [%lu] (signal %d)",
-                (unsigned long)shs->child.pid, sig);
-}
 
 static void helper_failed(libxl__egc *egc, libxl__save_helper_state *shs,
                           int rc)
@@ -266,7 +260,7 @@ static void helper_failed(libxl__egc *egc, libxl__save_helper_state *shs,
         return;
     }
 
-    sendsig(gc, shs, SIGKILL);
+    libxl__kill(gc, shs->child.pid, SIGKILL, "save/restore helper");
 }
 
 static void helper_stop(libxl__egc *egc, libxl__ao_abortable *abrt, int rc)
@@ -282,7 +276,7 @@ static void helper_stop(libxl__egc *egc, libxl__ao_abortable *abrt, int rc)
     if (!shs->rc)
         shs->rc = rc;
 
-    sendsig(gc, shs, SIGTERM);
+    libxl__kill(gc, shs->child.pid, SIGTERM, "save/restore helper");
 }
 
 static void helper_stdout_readable(libxl__egc *egc, libxl__ev_fd *ev,
Signature · 1 line
1.7.10.4
#5 lore raw

PATCH v3 5/28 tools/libxl: Stash all restore parameters in domain_create_state

In reply to Andrew Cooper

Shortly more parameters will appear, and this saves unboxing each one. libxl_domain_restore_params is mandatory for restore streams, and ignored for plain creation. The old 'checkpointed_stream' was incorrectly identified as a private parameter when it was infact public.

No functional change.

---
Since v1:
* Gate validity on restore_fd being valid.

---
 tools/libxl/libxl_create.c       |   13 +++++++------
 tools/libxl/libxl_internal.h     |    2 +-
 tools/libxl/libxl_save_callout.c |    2 +-
 3 files changed, 9 insertions(+), 8 deletions(-)
tools/libxl/libxl_create.c +7 -6
index b785ddd..61515da 100644
@@ -1512,8 +1512,8 @@ static void domain_create_cb(libxl__egc *egc,
                              int rc, uint32_t domid);
 
 static int do_domain_create(libxl_ctx *ctx, libxl_domain_config *d_config,
-                            uint32_t *domid,
-                            int restore_fd, int checkpointed_stream,
+                            uint32_t *domid, int restore_fd,
+                            const libxl_domain_restore_params *params,
                             const libxl_asyncop_how *ao_how,
                             const libxl_asyncprogress_how *aop_console_how)
 {
@@ -1526,8 +1526,9 @@ static int do_domain_create(libxl_ctx *ctx, libxl_domain_config *d_config,
     libxl_domain_config_init(&cdcs->dcs.guest_config_saved);
     libxl_domain_config_copy(ctx, &cdcs->dcs.guest_config_saved, d_config);
     cdcs->dcs.restore_fd = restore_fd;
+    if (restore_fd > -1)
+        cdcs->dcs.restore_params = *params;
     cdcs->dcs.callback = domain_create_cb;
-    cdcs->dcs.checkpointed_stream = checkpointed_stream;
     libxl__ao_progress_gethow(&cdcs->dcs.aop_console_how, aop_console_how);
     cdcs->domid_out = domid;
 
@@ -1553,7 +1554,7 @@ int libxl_domain_create_new(libxl_ctx *ctx, libxl_domain_config *d_config,
                             const libxl_asyncop_how *ao_how,
                             const libxl_asyncprogress_how *aop_console_how)
 {
-    return do_domain_create(ctx, d_config, domid, -1, 0,
+    return do_domain_create(ctx, d_config, domid, -1, NULL,
                             ao_how, aop_console_how);
 }
 
@@ -1563,8 +1564,8 @@ int libxl_domain_create_restore(libxl_ctx *ctx, libxl_domain_config *d_config,
                                 const libxl_asyncop_how *ao_how,
                                 const libxl_asyncprogress_how *aop_console_how)
 {
-    return do_domain_create(ctx, d_config, domid, restore_fd,
-                            params->checkpointed_stream, ao_how, aop_console_how);
+    return do_domain_create(ctx, d_config, domid, restore_fd, params,
+                            ao_how, aop_console_how);
 }
 
 /*
tools/libxl/libxl_internal.h +1 -1
index 7ccbf55..6428757 100644
@@ -3217,11 +3217,11 @@ struct libxl__domain_create_state {
     libxl_domain_config *guest_config;
     libxl_domain_config guest_config_saved; /* vanilla config */
     int restore_fd;
+    libxl_domain_restore_params restore_params;
     libxl__domain_create_cb *callback;
     libxl_asyncprogress_how aop_console_how;
     /* private to domain_create */
     int guest_domid;
-    int checkpointed_stream;
     libxl__domain_build_state build_state;
     libxl__bootloader_state bl;
     libxl__stub_dm_spawn_state dmss;
tools/libxl/libxl_save_callout.c +1 -1
index b82a5c1..80aae1b 100644
@@ -60,7 +60,7 @@ void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs,
         state->store_domid, state->console_port,
         state->console_domid,
         hvm, pae, superpages,
-        cbflags, dcs->checkpointed_stream,
+        cbflags, dcs->restore_params.checkpointed_stream,
     };
 
     dcs->shs.ao = ao;
Signature · 1 line
1.7.10.4
#6 lore raw

PATCH v3 6/28 tools/libxl: Split libxl__domain_create_state.restore_fd in two

In reply to Andrew Cooper

In a future patch, we shall support automatically converting a legacy stream to a v2 stream, in which case libxc needs to read from a different fd.

Simply overwriting restore_fd does not work; the two fd's have different circumstances. The restore_fd needs to be returned to its original state before libxl_domain_create_restore() returns, while in the converted case, the fd needs allocating and deallocating appropriately.

No functional change.

---
New in v2

---
 tools/libxl/libxl_create.c       |    2 +-
 tools/libxl/libxl_internal.h     |    2 +-
 tools/libxl/libxl_save_callout.c |    2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)
tools/libxl/libxl_create.c +1 -1
index 61515da..be13204 100644
@@ -1525,7 +1525,7 @@ static int do_domain_create(libxl_ctx *ctx, libxl_domain_config *d_config,
     cdcs->dcs.guest_config = d_config;
     libxl_domain_config_init(&cdcs->dcs.guest_config_saved);
     libxl_domain_config_copy(ctx, &cdcs->dcs.guest_config_saved, d_config);
-    cdcs->dcs.restore_fd = restore_fd;
+    cdcs->dcs.restore_fd = cdcs->dcs.libxc_fd = restore_fd;
     if (restore_fd > -1)
         cdcs->dcs.restore_params = *params;
     cdcs->dcs.callback = domain_create_cb;
tools/libxl/libxl_internal.h +1 -1
index 6428757..e5599a3 100644
@@ -3216,7 +3216,7 @@ struct libxl__domain_create_state {
     libxl__ao *ao;
     libxl_domain_config *guest_config;
     libxl_domain_config guest_config_saved; /* vanilla config */
-    int restore_fd;
+    int restore_fd, libxc_fd;
     libxl_domain_restore_params restore_params;
     libxl__domain_create_cb *callback;
     libxl_asyncprogress_how aop_console_how;
tools/libxl/libxl_save_callout.c +1 -1
index 80aae1b..1136b79 100644
@@ -48,7 +48,7 @@ void libxl__xc_domain_restore(libxl__egc *egc, libxl__domain_create_state *dcs,
 
     /* Convenience aliases */
     const uint32_t domid = dcs->guest_domid;
-    const int restore_fd = dcs->restore_fd;
+    const int restore_fd = dcs->libxc_fd;
     libxl__domain_build_state *const state = &dcs->build_state;
 
     unsigned cbflags = libxl__srm_callout_enumcallbacks_restore
Signature · 1 line
1.7.10.4
#7 lore raw

PATCH v3 7/28 tools/libxl: Extra management APIs for the save helper

In reply to Andrew Cooper

With migration v2, there are several moving parts needing to be juggled at once. This requires the error handling logic to be able to query the state of each moving part, possibly before they have been started, and be able to cancel them.

CC Ian Campbell <[email protected]>
CC Ian Jackson <[email protected]>
CC Wei Liu <[email protected]>

---
v3: Adjust helper_{stop,failed,done} to use libxl__save_helper_inuse()
v2: Add an _init() function which allows _inuse() to be safe to call even
before the save helper has started.

---
 tools/libxl/libxl_create.c       |    1 +
 tools/libxl/libxl_dom.c          |    1 +
 tools/libxl/libxl_internal.h     |    9 +++++++++
 tools/libxl/libxl_save_callout.c |   22 ++++++++++++++++------
 4 files changed, 27 insertions(+), 6 deletions(-)
tools/libxl/libxl_create.c +1 -0
index be13204..1f43b43 100644
@@ -988,6 +988,7 @@ static void domcreate_bootloader_done(libxl__egc *egc,
         rc = ERROR_INVAL;
         goto out;
     }
+    libxl__save_helper_init(&dcs->shs);
     libxl__xc_domain_restore(egc, dcs,
                              hvm, pae, superpages);
     return;
tools/libxl/libxl_dom.c +1 -0
index 8642192..63e2f47 100644
@@ -2117,6 +2117,7 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
     callbacks->switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
     dss->shs.callbacks.save.toolstack_save = libxl__toolstack_save;
 
+    libxl__save_helper_init(&dss->shs);
     libxl__xc_domain_save(egc, dss);
     return;
 
tools/libxl/libxl_internal.h +9 -0
index e5599a3..8ce3d49 100644
@@ -3272,6 +3272,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);
 
+_hidden void libxl__save_helper_init(libxl__save_helper_state *shs);
+_hidden void libxl__save_helper_abort(libxl__egc *egc,
+                                      libxl__save_helper_state *shs);
+
+static inline bool libxl__save_helper_inuse(const libxl__save_helper_state *shs)
+{
+    return libxl__ev_child_inuse(&shs->child);
+}
+
 /* 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);
tools/libxl/libxl_save_callout.c +16 -6
index 1136b79..0fb1fdc 100644
@@ -146,6 +146,13 @@ void libxl__xc_domain_saverestore_async_callback_done(libxl__egc *egc,
     shs->egc = 0;
 }
 
+void libxl__save_helper_init(libxl__save_helper_state *shs)
+{
+    libxl__ao_abortable_init(&shs->abrt);
+    libxl__ev_fd_init(&shs->readable);
+    libxl__ev_child_init(&shs->child);
+}
+
 /*----- helper execution -----*/
 
 static void run_helper(libxl__egc *egc, libxl__save_helper_state *shs,
@@ -167,9 +174,6 @@ static void run_helper(libxl__egc *egc, libxl__save_helper_state *shs,
     shs->rc = 0;
     shs->completed = 0;
     shs->pipes[0] = shs->pipes[1] = 0;
-    libxl__ao_abortable_init(&shs->abrt);
-    libxl__ev_fd_init(&shs->readable);
-    libxl__ev_child_init(&shs->child);
 
     shs->abrt.ao = shs->ao;
     shs->abrt.callback = helper_stop;
@@ -255,7 +259,7 @@ static void helper_failed(libxl__egc *egc, libxl__save_helper_state *shs,
 
     libxl__ev_fd_deregister(gc, &shs->readable);
 
-    if (!libxl__ev_child_inuse(&shs->child)) {
+    if (!libxl__save_helper_inuse(shs)) {
         helper_done(egc, shs);
         return;
     }
@@ -268,7 +272,7 @@ static void helper_stop(libxl__egc *egc, libxl__ao_abortable *abrt, int rc)
     libxl__save_helper_state *shs = CONTAINER_OF(abrt, *shs, abrt);
     STATE_AO_GC(shs->ao);
 
-    if (!libxl__ev_child_inuse(&shs->child)) {
+    if (!libxl__save_helper_inuse(shs)) {
         helper_failed(egc, shs, rc);
         return;
     }
@@ -279,6 +283,12 @@ static void helper_stop(libxl__egc *egc, libxl__ao_abortable *abrt, int rc)
     libxl__kill(gc, shs->child.pid, SIGTERM, "save/restore helper");
 }
 
+void libxl__save_helper_abort(libxl__egc *egc,
+                              libxl__save_helper_state *shs)
+{
+    helper_stop(egc, &shs->abrt, ERROR_FAIL);
+}
+
 static void helper_stdout_readable(libxl__egc *egc, libxl__ev_fd *ev,
                                    int fd, short events, short revents)
 {
@@ -356,7 +366,7 @@ static void helper_done(libxl__egc *egc, libxl__save_helper_state *shs)
     libxl__ev_fd_deregister(gc, &shs->readable);
     libxl__carefd_close(shs->pipes[0]);  shs->pipes[0] = 0;
     libxl__carefd_close(shs->pipes[1]);  shs->pipes[1] = 0;
-    assert(!libxl__ev_child_inuse(&shs->child));
+    assert(!libxl__save_helper_inuse(shs));
     if (shs->toolstack_data_file) fclose(shs->toolstack_data_file);
 
     shs->egc = egc;
Signature · 1 line
1.7.10.4
#10 lore raw

PATCH v3 8/28 tools/libxl: Add save_helper_state pointers to libxl__xc_domain_{save, restore}()

In reply to Andrew Cooper

Currently, libxl__xc_domain_{save,restore}() have specific knowledge of where the libxl__save_helper_state lives inside a libxl__domain_{create,save}_state object.

In later changes, the logical ownership of the libxl__save_helper_state will change and will no longer be d{c,s}s->shs.

No functional change.

CC Ian Campbell <[email protected]>
CC Ian Jackson <[email protected]>
CC Wei Liu <[email protected]>

---
New in v3

---
 tools/libxl/libxl_create.c       |    4 +--
 tools/libxl/libxl_dom.c          |   20 +++++++-------
 tools/libxl/libxl_internal.h     |    5 +++-
 tools/libxl/libxl_save_callout.c |   54 ++++++++++++++++++++------------------
 4 files changed, 44 insertions(+), 39 deletions(-)
tools/libxl/libxl_create.c +2 -2
index 1f43b43..5d57bc3 100644
@@ -989,7 +989,7 @@ static void domcreate_bootloader_done(libxl__egc *egc,
         goto out;
     }
     libxl__save_helper_init(&dcs->shs);
-    libxl__xc_domain_restore(egc, dcs,
+    libxl__xc_domain_restore(egc, dcs, &dcs->shs,
                              hvm, pae, superpages);
     return;
 
@@ -1001,7 +1001,7 @@ void libxl__srm_callout_callback_restore_results(unsigned long store_mfn,
           unsigned long console_mfn, void *user)
 {
     libxl__save_helper_state *shs = user;
-    libxl__domain_create_state *dcs = CONTAINER_OF(shs, *dcs, shs);
+    libxl__domain_create_state *dcs = shs->caller_state;
     STATE_AO_GC(dcs->ao);
     libxl__domain_build_state *const state = &dcs->build_state;
 
tools/libxl/libxl_dom.c +10 -10
index 63e2f47..9719837 100644
@@ -1121,7 +1121,7 @@ int libxl__toolstack_restore(uint32_t domid, const uint8_t *ptr,
                              uint32_t size, void *user)
 {
     libxl__save_helper_state *shs = user;
-    libxl__domain_create_state *dcs = CONTAINER_OF(shs, *dcs, shs);
+    libxl__domain_create_state *dcs = shs->caller_state;
     STATE_AO_GC(dcs->ao);
     int ret;
     uint32_t version = 0, bufsize;
@@ -1188,7 +1188,7 @@ static void logdirty_init(libxl__logdirty_switch *lds)
                                 libxl__save_helper_state *shs)
 {
     libxl__egc *egc = shs->egc;
-    libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
+    libxl__domain_suspend_state *dss = shs->caller_state;
     libxl__logdirty_switch *lds = &dss->logdirty;
     STATE_AO_GC(dss->ao);
     int rc;
@@ -1260,7 +1260,7 @@ static void logdirty_init(libxl__logdirty_switch *lds)
                                 libxl__save_helper_state *shs)
 {
     libxl__egc *egc = shs->egc;
-    libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
+    libxl__domain_suspend_state *dss = shs->caller_state;
     STATE_AO_GC(dss->ao);
     int rc;
 
@@ -1279,7 +1279,7 @@ static void logdirty_init(libxl__logdirty_switch *lds)
 {
     libxl__save_helper_state *shs = user;
     libxl__egc *egc = shs->egc;
-    libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
+    libxl__domain_suspend_state *dss = shs->caller_state;
     STATE_AO_GC(dss->ao);
 
     switch (libxl__device_model_version_running(gc, domid)) {
@@ -1832,7 +1832,7 @@ static void libxl__domain_suspend_callback(void *data)
 {
     libxl__save_helper_state *shs = data;
     libxl__egc *egc = shs->egc;
-    libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
+    libxl__domain_suspend_state *dss = shs->caller_state;
 
     dss->callback_common_done = domain_suspend_callback_common_done;
     domain_suspend_callback_common(egc, dss);
@@ -1859,7 +1859,7 @@ static void libxl__remus_domain_suspend_callback(void *data)
 {
     libxl__save_helper_state *shs = data;
     libxl__egc *egc = shs->egc;
-    libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
+    libxl__domain_suspend_state *dss = shs->caller_state;
 
     dss->callback_common_done = remus_domain_suspend_callback_common_done;
     domain_suspend_callback_common(egc, dss);
@@ -1902,7 +1902,7 @@ static void libxl__remus_domain_resume_callback(void *data)
 {
     libxl__save_helper_state *shs = data;
     libxl__egc *egc = shs->egc;
-    libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
+    libxl__domain_suspend_state *dss = shs->caller_state;
     STATE_AO_GC(dss->ao);
 
     libxl__remus_devices_state *const rds = &dss->rds;
@@ -1947,8 +1947,8 @@ static void remus_next_checkpoint(libxl__egc *egc, libxl__ev_time *ev,
 static void libxl__remus_domain_checkpoint_callback(void *data)
 {
     libxl__save_helper_state *shs = data;
-    libxl__domain_suspend_state *dss = CONTAINER_OF(shs, *dss, shs);
-    libxl__egc *egc = dss->shs.egc;
+    libxl__domain_suspend_state *dss = shs->caller_state;
+    libxl__egc *egc = shs->egc;
     STATE_AO_GC(dss->ao);
 
     /* This would go into tailbuf. */
@@ -2118,7 +2118,7 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
     dss->shs.callbacks.save.toolstack_save = libxl__toolstack_save;
 
     libxl__save_helper_init(&dss->shs);
-    libxl__xc_domain_save(egc, dss);
+    libxl__xc_domain_save(egc, dss, &dss->shs);
     return;
 
  out:
tools/libxl/libxl_internal.h +4 -1
index 8ce3d49..3f1fed8 100644
@@ -3241,7 +3241,9 @@ _hidden void libxl__domain_suspend(libxl__egc *egc,
 
 
 /* calls libxl__xc_domain_suspend_done when done */
-_hidden void libxl__xc_domain_save(libxl__egc*, libxl__domain_suspend_state*);
+_hidden void libxl__xc_domain_save(libxl__egc *egc,
+                                   libxl__domain_suspend_state *dss,
+                                   libxl__save_helper_state *shs);
 /* 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. */
@@ -3265,6 +3267,7 @@ _hidden int libxl__toolstack_save(uint32_t domid, uint8_t **buf,
 /* calls libxl__xc_domain_restore_done when done */
 _hidden void libxl__xc_domain_restore(libxl__egc *egc,
                                       libxl__domain_create_state *dcs,
+                                      libxl__save_helper_state *shs,
                                       int hvm, int pae, int superpages);
 /* If rc==0 then retval is the return value from xc_domain_save
  * and errnoval is the errno value it provided.
tools/libxl/libxl_save_callout.c +28 -26

105 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#12 lore raw

PATCH v3 9/28 tools/xl: Mandatory flag indicating the format of the migration stream

In reply to Andrew Cooper

Introduced at this point so the python stream conversion code has a concrete ABI to use. Later when libxl itself starts supporting a v2 stream, it will be added to XL_MANDATORY_FLAG_ALL.

---
v2: Expand commit message

---
 tools/libxl/xl_cmdimpl.c |    1 +
 1 file changed, 1 insertion(+)
tools/libxl/xl_cmdimpl.c +1 -0
index 971209c..26b1e7d 100644
@@ -109,6 +109,7 @@
    */
 
 #define XL_MANDATORY_FLAG_JSON (1U << 0) /* config data is in JSON format */
+#define XL_MANDATORY_FLAG_STREAMv2 (1U << 1) /* stream is v2 */
 #define XL_MANDATORY_FLAG_ALL  (XL_MANDATORY_FLAG_JSON)
 struct save_file_header {
     char magic[32]; /* savefileheader_magic */
Signature · 1 line
1.7.10.4
#13 lore raw

PATCH v3 10/28 docs: Libxl migration v2 stream specification

In reply to Andrew Cooper

---
v3: Spelling fixes

---
 docs/specs/libxl-migration-stream.pandoc |  205 ++++++++++++++++++++++++++++++
 1 file changed, 205 insertions(+)
 create mode 100644 docs/specs/libxl-migration-stream.pandoc
docs/specs/libxl-migration-stream.pandoc new file +205 -0
new file mode 100644
index 0000000..4192950
@@ -0,0 +1,205 @@
+% LibXenLight Domain Image Format
+% Andrew Cooper <<[email protected]>>
+% Draft B
+
+Introduction
+============
+
+For the purposes of this document, `xl` is used as a representation of any
+implementer of the `libxl` API.  `xl` should be considered completely
+interchangeable with alternates, such as `libvirt` or `xenopsd-xl`.
+
+Purpose
+-------
+
+The _domain image format_ is the context of a running domain used for
+snapshots of a domain or for transferring domains between hosts during
+migration.
+
+There are a number of problems with the domain image format used in Xen 4.5
+and earlier (the _legacy format_)
+
+* There is no `libxl` context information.  `xl` is required to send certain
+  pieces of `libxl` context itself.
+
+* The contents of the stream is passed directly through `libxl` to `libxc`.
+  The legacy `libxc` format contained some information which belonged at the
+  `libxl` level, resulting in awkward layer violation to return the
+  information back to `libxl`.
+
+* The legacy `libxc` format was inextensible, causing inextensibility in the
+  legacy `libxl` handling.
+
+This design addresses the above points, allowing for a completely
+self-contained, extensible stream with each layer responsible for its own
+appropriate information.
+
+
+Not Yet Included
+----------------
+
+The following features are not yet fully specified and will be
+included in a future draft.
+
+* Remus
+
+* ARM
+
+
+Overview
+========
+
+The image format consists of a _Header_, followed by 1 or more _Records_.
+Each record consists of a type and length field, followed by any type-specific
+data.
+
+\clearpage
+
+Header
+======
+
+The header identifies the stream as a `libxl` stream, including the version of
+this specification that it complies with.
+
+All fields in this header shall be in _big-endian_ byte order, regardless of
+the setting of the endianness bit.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+    | ident                                           |
+    +-----------------------+-------------------------+
+    | version               | options                 |
+    +-----------------------+-------------------------+
+
+--------------------------------------------------------------------
+Field       Description
+----------- --------------------------------------------------------
+ident       0x4c6962786c466d74 ("LibxlFmt" in ASCII).
+
+version     0x00000002.  The version of this specification.
+
+options     bit 0: Endianness.    0 = little-endian, 1 = big-endian.
+
+            bit 1: Legacy Format. If set, this stream was created by
+                                  the legacy conversion tool.
+
+            bits 2-31: Reserved.
+--------------------------------------------------------------------
+
+The endianness shall be 0 (little-endian) for images generated on an
+i386, x86_64, or arm host.
+
+\clearpage
+
+
+Records
+=======
+
+A record has a record header, type specific data and a trailing footer.  If
+`length` is not a multiple of 8, the body is padded with zeroes to align the
+end of the record on an 8 octet boundary.
+
+     0     1     2     3     4     5     6     7 octet
+    +-----------------------+-------------------------+
+    | type                  | body_length             |
+    +-----------+-----------+-------------------------+
+    | body...                                         |
+    ...
+    |           | padding (0 to 7 octets)             |
+    +-----------+-------------------------------------+
+
+--------------------------------------------------------------------
+Field        Description
+-----------  -------------------------------------------------------
+type         0x00000000: END
+
+             0x00000001: LIBXC_CONTEXT
+
+             0x00000002: XENSTORE_DATA
+
+             0x00000003: EMULATOR_CONTEXT
+
+             0x00000004 - 0x7FFFFFFF: Reserved for future _mandatory_
+             records.
+
+             0x80000000 - 0xFFFFFFFF: Reserved for future _optional_
+             records.
+
+body_length  Length in octets of the record body.
+
+body         Content of the record.
+
+padding      0 to 7 octets of zeros to pad the whole record to a multiple
+             of 8 octets.
+--------------------------------------------------------------------
+
+\clearpage
+
+END
+----
+
+A end record marks the end of the image, and shall be the final record
+in the stream.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+
+The end record contains no fields; its body_length is 0.
+
+LIBXC\_CONTEXT
+--------------
+
+A libxc context record is a marker, indicating that the stream should be
+handed to `xc_domain_restore()`.  `libxc` shall be responsible for reading its
+own image format from the stream.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+
+The libxc context record contains no fields; its body_length is 0[^1].
+
+
+[^1]: The sending side cannot calculate ahead of time how much data `libxc`
+might write into the stream, especially for live migration where the quantity
+of data is partially proportional to the elapsed time.
+
+XENSTORE\_DATA
+-------------
+
+A record containing xenstore key/value pairs of data.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+    | xenstore key/value pairs                        |
+    ...
+    +-------------------------------------------------+
+
+EMULATOR\_CONTEXT
+----------------
+
+A context blob for a specific emulator associated with the domain.
+
+     0     1     2     3     4     5     6     7 octet
+    +------------------------+------------------------+
+    | emulator_id            | index                  |
+    +------------------------+------------------------+
+    | emulator_ctx                                    |
+    ...
+    +-------------------------------------------------+
+
+--------------------------------------------------------------------
+Field            Description
+------------     ---------------------------------------------------
+emulator_id      0x00000000: Unknown (In the case of a legacy stream)
+
+                 0x00000001: Qemu Traditional
+
+                 0x00000002: Qemu Upstream
+
+                 0x00000003 - 0xFFFFFFFF: Reserved for future emulators.
+
+index            Index of this emulator for the domain, if multiple
+                 emulators are in use.
+
+emulator_ctx     Emulator context blob.
+--------------------------------------------------------------------
Signature · 1 line
1.7.10.4
#14 lore raw

PATCH v3 11/28 tools/python: Libxc migration v2 infrastructure

In reply to Andrew Cooper

Contains:
* Python implementation of the libxc migration v2 records
* Verification code for spec compliance
* Unit tests

---
 tools/python/setup.py                |    1 +
 tools/python/xen/migration/libxc.py  |  446 ++++++++++++++++++++++++++++++++++
 tools/python/xen/migration/tests.py  |   41 ++++
 tools/python/xen/migration/verify.py |   37 +++
 4 files changed, 525 insertions(+)
 create mode 100644 tools/python/xen/migration/__init__.py
 create mode 100644 tools/python/xen/migration/libxc.py
 create mode 100644 tools/python/xen/migration/tests.py
 create mode 100644 tools/python/xen/migration/verify.py
tools/python/setup.py +1 -0
index 439c429..5bf81be 100644
@@ -43,6 +43,7 @@ setup(name            = 'xen',
       version         = '3.0',
       description     = 'Xen',
       packages        = ['xen',
+                         'xen.migration',
                          'xen.lowlevel',
                         ],
       ext_package = "xen.lowlevel",
tools/python/xen/migration/__init__.py new file +0 -0
new file mode 100644
index 0000000..e69de29
tools/python/xen/migration/libxc.py new file +446 -0

446 lines not on this page · raw message

tools/python/xen/migration/tests.py new file +41 -0

41 lines not on this page · raw message

tools/python/xen/migration/verify.py new file +37 -0
new file mode 100644
index 0000000..7a42dbf
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Common verification infrastructure for v2 streams
+"""
+
+from struct import calcsize, unpack
+
+class StreamError(StandardError):
+    """Error with the stream"""
+    pass
+
+class RecordError(StandardError):
+    """Error with a record in the stream"""
+    pass
+
+
+class VerifyBase(object):
+
+    def __init__(self, info, read):
+
+        self.info = info
+        self.read = read
+
+    def rdexact(self, nr_bytes):
+        """Read exactly nr_bytes from the stream"""
+        _ = self.read(nr_bytes)
+        if len(_) != nr_bytes:
+            raise IOError("Stream truncated")
+        return _
+
+    def unpack_exact(self, fmt):
+        """Unpack a struct format string from the stream"""
+        sz = calcsize(fmt)
+        return unpack(fmt, self.rdexact(sz))
+
Signature · 1 line
1.7.10.4
#15 lore raw

PATCH v3 12/28 tools/python: Libxl migration v2 infrastructure

In reply to Andrew Cooper

Contains:
* Python implementation of the libxl migration v2 records
* Verification code for spec compliance
* Unit tests

---
 tools/python/xen/migration/libxl.py |  188 +++++++++++++++++++++++++++++++++++
 tools/python/xen/migration/tests.py |   13 +++
 2 files changed, 201 insertions(+)
 create mode 100644 tools/python/xen/migration/libxl.py
tools/python/xen/migration/libxl.py new file +188 -0
new file mode 100644
index 0000000..4e1f4f8
@@ -0,0 +1,188 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Libxl Migration v2 streams
+
+Record structures as per docs/specs/libxl-migration-stream.pandoc, and
+verification routines.
+"""
+
+import sys
+
+from struct import calcsize, unpack
+from xen.migration.verify import StreamError, RecordError, VerifyBase
+from xen.migration.libxc import VerifyLibxc
+
+# Header
+HDR_FORMAT = "!QII"
+
+HDR_IDENT = 0x4c6962786c466d74 # "LibxlFmt" in ASCII
+HDR_VERSION = 2
+
+HDR_OPT_BIT_ENDIAN = 0
+HDR_OPT_BIT_LEGACY = 1
+
+HDR_OPT_LE     = (0 << HDR_OPT_BIT_ENDIAN)
+HDR_OPT_BE     = (1 << HDR_OPT_BIT_ENDIAN)
+HDR_OPT_LEGACY = (1 << HDR_OPT_BIT_LEGACY)
+
+HDR_OPT_RESZ_MASK = 0xfffc
+
+# Records
+RH_FORMAT = "II"
+
+REC_TYPE_end              = 0x00000000
+REC_TYPE_libxc_context    = 0x00000001
+REC_TYPE_xenstore_data    = 0x00000002
+REC_TYPE_emulator_context = 0x00000003
+
+rec_type_to_str = {
+    REC_TYPE_end              : "End",
+    REC_TYPE_libxc_context    : "Libxc context",
+    REC_TYPE_xenstore_data    : "Xenstore data",
+    REC_TYPE_emulator_context : "Emulator context",
+}
+
+# emulator_context
+EMULATOR_CONTEXT_FORMAT = "II"
+
+EMULATOR_ID_unknown       = 0x00000000
+EMULATOR_ID_qemu_trad     = 0x00000001
+EMULATOR_ID_qemu_upstream = 0x00000002
+
+emulator_id_to_str = {
+    EMULATOR_ID_unknown       : "Unknown",
+    EMULATOR_ID_qemu_trad     : "Qemu Traditional",
+    EMULATOR_ID_qemu_upstream : "Qemu Upstream",
+}
+
+
+#
+# libxl format
+#
+
+LIBXL_QEMU_SIGNATURE = "DeviceModelRecord0002"
+LIBXL_QEMU_RECORD_HDR = "=%dsI" % (len(LIBXL_QEMU_SIGNATURE), )
+
+class VerifyLibxl(VerifyBase):
+    """ Verify a Libxl v2 stream """
+
+    def __init__(self, info, read):
+        VerifyBase.__init__(self, info, read)
+
+
+    def verify(self):
+        """ Verity a libxl stream """
+
+        self.verify_hdr()
+
+        while self.verify_record() != REC_TYPE_end:
+            pass
+
+
+    def verify_hdr(self):
+        """ Verify a Header """
+        ident, version, options = self.unpack_exact(HDR_FORMAT)
+
+        if ident != HDR_IDENT:
+            raise StreamError("Bad image id: Expected 0x%x, got 0x%x"
+                              % (HDR_IDENT, ident))
+
+        if version != HDR_VERSION:
+            raise StreamError("Unknown image version: Expected %d, got %d"
+                              % (HDR_VERSION, version))
+
+        if options & HDR_OPT_RESZ_MASK:
+            raise StreamError("Reserved bits set in image options field: 0x%x"
+                              % (options & HDR_OPT_RESZ_MASK))
+
+        if ( (sys.byteorder == "little") and
+             ((options & HDR_OPT_BIT_ENDIAN) != HDR_OPT_LE) ):
+            raise StreamError(
+                "Stream is not native endianess - unable to validate")
+
+        endian = ["little", "big"][options & HDR_OPT_LE]
+
+        if options & HDR_OPT_LEGACY:
+            self.info("Libxl Header: %s endian, legacy converted" % (endian, ))
+        else:
+            self.info("Libxl Header: %s endian" % (endian, ))
+
+
+    def verify_record(self):
+        """ Verify an individual record """
+        rtype, length = self.unpack_exact(RH_FORMAT)
+
+        if rtype not in rec_type_to_str:
+            raise StreamError("Unrecognised record type %x" % (rtype, ))
+
+        self.info("Libxl Record: %s, length %d"
+                  % (rec_type_to_str[rtype], length))
+
+        contentsz = (length + 7) & ~7
+        content = self.rdexact(contentsz)
+
+        padding = content[length:]
+        if padding != "\x00" * len(padding):
+            raise StreamError("Padding containing non0 bytes found")
+
+        if rtype not in record_verifiers:
+            raise RuntimeError("No verification function for libxl record '%s'"
+                               % rec_type_to_str[rtype])
+        else:
+            record_verifiers[rtype](self, content[:length])
+
+        return rtype
+
+
+    def verify_record_end(self, content):
+        """ End record """
+
+        if len(content) != 0:
+            raise RecordError("End record with non-zero length")
+
+
+    def verify_record_libxc_context(self, content):
+        """ Libxc context record """
+
+        if len(content) != 0:
+            raise RecordError("Libxc context record with non-zero length")
+
+        # Verify the libxc stream, as we can't seek forwards through it
+        VerifyLibxc(self.info, self.read).verify()
+
+
+    def verify_record_xenstore_data(self, content):
+        """ Xenstore Data record """
+
+        if len(content) == 0:
+            raise RecordError("Xenstore data record with zero length")
+
+
+    def verify_record_emulator_context(self, content):
+        """ Emulator Context record """
+        minsz = calcsize(EMULATOR_CONTEXT_FORMAT)
+
+        if len(content) < minsz:
+            raise RecordError("Length must be at least %d bytes, got %d"
+                              % (minsz, len(content)))
+
+        emu_id, emu_idx = unpack(EMULATOR_CONTEXT_FORMAT, content[:minsz])
+
+        if emu_id not in emulator_id_to_str:
+            raise RecordError("Unrecognised emulator id 0x%x" % (emu_id, ))
+
+        self.info("  Index %d, type %s" % (emu_idx, emulator_id_to_str[emu_id]))
+
+
+record_verifiers = {
+    REC_TYPE_end:
+        VerifyLibxl.verify_record_end,
+    REC_TYPE_libxc_context:
+        VerifyLibxl.verify_record_libxc_context,
+    REC_TYPE_xenstore_data:
+        VerifyLibxl.verify_record_xenstore_data,
+    REC_TYPE_emulator_context:
+        VerifyLibxl.verify_record_emulator_context,
+}
tools/python/xen/migration/tests.py +13 -0
index 3e97268..91044cd 100644
@@ -30,10 +30,23 @@ class TestLibxc(unittest.TestCase):
             self.assertEqual(calcsize(fmt), sz)
 
 
+class TestLibxl(unittest.TestCase):
+
+    def test_format_sizes(self):
+
+        for fmt, sz in ( (libxl.HDR_FORMAT, 16),
+                         (libxl.RH_FORMAT, 8),
+
+                         (libxl.EMULATOR_CONTEXT_FORMAT, 8),
+                         ):
+            self.assertEqual(calcsize(fmt), sz)
+
+
 def test_suite():
     suite = unittest.TestSuite()
 
     suite.addTest(unittest.makeSuite(TestLibxc))
+    suite.addTest(unittest.makeSuite(TestLibxl))
 
     return suite
 
Signature · 1 line
1.7.10.4
#16 lore raw

PATCH v3 13/28 tools/python: Other migration infrastructure

In reply to Andrew Cooper

Contains:
* Reverse-engineered notes of the legacy format from xg_save_restore.h
* Python implementation of the legacy format
* Public HVM Params used in the legacy stream
* XL header format

---
New in v2 - removes various many magic numbers from subsequent scripts

---
 tools/python/xen/migration/legacy.py |  279 ++++++++++++++++++++++++++++++++++
 tools/python/xen/migration/public.py |   21 +++
 tools/python/xen/migration/xl.py     |   12 ++
 3 files changed, 312 insertions(+)
 create mode 100644 tools/python/xen/migration/legacy.py
 create mode 100644 tools/python/xen/migration/public.py
 create mode 100644 tools/python/xen/migration/xl.py
tools/python/xen/migration/legacy.py new file +279 -0
new file mode 100644
index 0000000..2f2240a
@@ -0,0 +1,279 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Libxc legacy migration streams
+
+Documentation and record structures for legacy migration
+"""
+
+"""
+SAVE/RESTORE/MIGRATE PROTOCOL
+=============================
+
+The general form of a stream of chunks is a header followed by a
+body consisting of a variable number of chunks (terminated by a
+chunk with type 0) followed by a trailer.
+
+For a rolling/checkpoint (e.g. remus) migration then the body and
+trailer phases can be repeated until an external event
+(e.g. failure) causes the process to terminate and commit to the
+most recent complete checkpoint.
+
+HEADER
+------
+
+unsigned long        : p2m_size
+
+extended-info (PV-only, optional):
+
+  If first unsigned long == ~0UL then extended info is present,
+  otherwise unsigned long is part of p2m. Note that p2m_size above
+  does not include the length of the extended info.
+
+  extended-info:
+
+    unsigned long    : signature == ~0UL
+    uint32_t	        : number of bytes remaining in extended-info
+
+    1 or more extended-info blocks of form:
+    char[4]          : block identifier
+    uint32_t         : block data size
+    bytes            : block data
+
+    defined extended-info blocks:
+    "vcpu"		: VCPU context info containing vcpu_guest_context_t.
+                       The precise variant of the context structure
+                       (e.g. 32 vs 64 bit) is distinguished by
+                       the block size.
+    "extv"           : Presence indicates use of extended VCPU context in
+                       tail, data size is 0.
+
+p2m (PV-only):
+
+  consists of p2m_size bytes comprising an array of xen_pfn_t sized entries.
+
+BODY PHASE - Format A (for live migration or Remus without compression)
+----------
+
+A series of chunks with a common header:
+  int              : chunk type
+
+If the chunk type is +ve then chunk contains guest memory data, and the
+type contains the number of pages in the batch:
+
+    unsigned long[]  : PFN array, length == number of pages in batch
+                       Each entry consists of XEN_DOMCTL_PFINFO_*
+                       in bits 31-28 and the PFN number in bits 27-0.
+    page data        : PAGE_SIZE bytes for each page marked present in PFN
+                       array
+
+If the chunk type is -ve then chunk consists of one of a number of
+metadata types.  See definitions of XC_SAVE_ID_* below.
+
+If chunk type is 0 then body phase is complete.
+
+
+BODY PHASE - Format B (for Remus with compression)
+----------
+
+A series of chunks with a common header:
+  int              : chunk type
+
+If the chunk type is +ve then chunk contains array of PFNs corresponding
+to guest memory and type contains the number of PFNs in the batch:
+
+    unsigned long[]  : PFN array, length == number of pages in batch
+                       Each entry consists of XEN_DOMCTL_PFINFO_*
+                       in bits 31-28 and the PFN number in bits 27-0.
+
+If the chunk type is -ve then chunk consists of one of a number of
+metadata types.  See definitions of XC_SAVE_ID_* below.
+
+If the chunk type is -ve and equals XC_SAVE_ID_COMPRESSED_DATA, then the
+chunk consists of compressed page data, in the following format:
+
+    unsigned long        : Size of the compressed chunk to follow
+    compressed data :      variable length data of size indicated above.
+                           This chunk consists of compressed page data.
+                           The number of pages in one chunk depends on
+                           the amount of space available in the sender's
+                           output buffer.
+
+Format of compressed data:
+  compressed_data = <deltas>*
+  delta           = <marker, run*>
+  marker          = (RUNFLAG|SKIPFLAG) bitwise-or RUNLEN [1 byte marker]
+  RUNFLAG         = 0
+  SKIPFLAG        = 1 << 7
+  RUNLEN          = 7-bit unsigned value indicating number of WORDS in the run
+  run             = string of bytes of length sizeof(WORD) * RUNLEN
+
+   If marker contains RUNFLAG, then RUNLEN * sizeof(WORD) bytes of data following
+  the marker is copied into the target page at the appropriate offset indicated by
+  the offset_ptr
+   If marker contains SKIPFLAG, then the offset_ptr is advanced
+  by RUNLEN * sizeof(WORD).
+
+If chunk type is 0 then body phase is complete.
+
+There can be one or more chunks with type XC_SAVE_ID_COMPRESSED_DATA,
+containing compressed pages. The compressed chunks are collated to form
+one single compressed chunk for the entire iteration. The number of pages
+present in this final compressed chunk will be equal to the total number
+of valid PFNs specified by the +ve chunks.
+
+At the sender side, compressed pages are inserted into the output stream
+in the same order as they would have been if compression logic was absent.
+
+Until last iteration, the BODY is sent in Format A, to maintain live
+migration compatibility with receivers of older Xen versions.
+At the last iteration, if Remus compression was enabled, the sender sends
+a trigger, XC_SAVE_ID_ENABLE_COMPRESSION to tell the receiver to parse the
+BODY in Format B from the next iteration onwards.
+
+An example sequence of chunks received in Format B:
+    +16                              +ve chunk
+    unsigned long[16]                PFN array
+    +100                             +ve chunk
+    unsigned long[100]               PFN array
+    +50                              +ve chunk
+    unsigned long[50]                PFN array
+
+    XC_SAVE_ID_COMPRESSED_DATA       TAG
+      N                              Length of compressed data
+      N bytes of DATA                Decompresses to 166 pages
+
+    XC_SAVE_ID_*                     other xc save chunks
+    0                                END BODY TAG
+
+Corner case with checkpoint compression:
+    At sender side, after pausing the domain, dirty pages are usually
+  copied out to a temporary buffer. After the domain is resumed,
+  compression is done and the compressed chunk(s) are sent, followed by
+  other XC_SAVE_ID_* chunks.
+    If the temporary buffer gets full while scanning for dirty pages,
+  the sender stops buffering of dirty pages, compresses the temporary
+  buffer and sends the compressed data with XC_SAVE_ID_COMPRESSED_DATA.
+  The sender then resumes the buffering of dirty pages and continues
+  scanning for the dirty pages.
+    For e.g., assume that the temporary buffer can hold 4096 pages and
+  there are 5000 dirty pages. The following is the sequence of chunks
+  that the receiver will see:
+
+    +1024                       +ve chunk
+    unsigned long[1024]         PFN array
+    +1024                       +ve chunk
+    unsigned long[1024]         PFN array
+    +1024                       +ve chunk
+    unsigned long[1024]         PFN array
+    +1024                       +ve chunk
+    unsigned long[1024]         PFN array
+
+    XC_SAVE_ID_COMPRESSED_DATA  TAG
+     N                          Length of compressed data
+     N bytes of DATA            Decompresses to 4096 pages
+
+    +4                          +ve chunk
+    unsigned long[4]            PFN array
+
+    XC_SAVE_ID_COMPRESSED_DATA  TAG
+     M                          Length of compressed data
+     M bytes of DATA            Decompresses to 4 pages
+
+    XC_SAVE_ID_*                other xc save chunks
+    0                           END BODY TAG
+
+    In other words, XC_SAVE_ID_COMPRESSED_DATA can be interleaved with
+  +ve chunks arbitrarily. But at the receiver end, the following condition
+  always holds true until the end of BODY PHASE:
+   num(PFN entries +ve chunks) >= num(pages received in compressed form)
+
+TAIL PHASE
+----------
+
+Content differs for PV and HVM guests.
+
+HVM TAIL:
+
+ "Magic" pages:
+    uint64_t         : I/O req PFN
+    uint64_t         : Buffered I/O req PFN
+    uint64_t         : Store PFN
+ Xen HVM Context:
+    uint32_t         : Length of context in bytes
+    bytes            : Context data
+ Qemu context:
+    char[21]         : Signature:
+      "QemuDeviceModelRecord" : Read Qemu save data until EOF
+      "DeviceModelRecord0002" : uint32_t length field followed by that many
+                                bytes of Qemu save data
+      "RemusDeviceModelState" : Currently the same as "DeviceModelRecord0002".
+
+PV TAIL:
+
+ Unmapped PFN list   : list of all the PFNs that were not in map at the close
+    unsigned int     : Number of unmapped pages
+    unsigned long[]  : PFNs of unmapped pages
+
+ VCPU context data   : A series of VCPU records, one per present VCPU
+                       Maximum and present map supplied in XC_SAVE_ID_VCPUINFO
+    bytes:           : VCPU context structure. Size is determined by size
+                       provided in extended-info header
+    bytes[128]       : Extended VCPU context (present IFF "extv" block
+                       present in extended-info header)
+
+ Shared Info Page    : 4096 bytes of shared info page
+"""
+
+CHUNK_end                       = 0
+CHUNK_enable_verify_mode        = -1
+CHUNK_vcpu_info                 = -2
+CHUNK_hvm_ident_pt              = -3
+CHUNK_hvm_vm86_tss              = -4
+CHUNK_tmem                      = -5
+CHUNK_tmem_extra                = -6
+CHUNK_tsc_info                  = -7
+CHUNK_hvm_console_pfn           = -8
+CHUNK_last_checkpoint           = -9
+CHUNK_hvm_acpi_ioports_location = -10
+CHUNK_hvm_viridian              = -11
+CHUNK_compressed_data           = -12
+CHUNK_enable_compression        = -13
+CHUNK_hvm_generation_id_addr    = -14
+CHUNK_hvm_paging_ring_pfn       = -15
+CHUNK_hvm_monitor_ring_pfn      = -16
+CHUNK_hvm_sharing_ring_pfn      = -17
+CHUNK_toolstack                 = -18
+CHUNK_hvm_ioreq_server_pfn      = -19
+CHUNK_hvm_nr_ioreq_server_pages = -20
+
+chunk_type_to_str = {
+    CHUNK_end                       : "end",
+    CHUNK_enable_verify_mode        : "enable_verify_mode",
+    CHUNK_vcpu_info                 : "vcpu_info",
+    CHUNK_hvm_ident_pt              : "hvm_ident_pt",
+    CHUNK_hvm_vm86_tss              : "hvm_vm86_tss",
+    CHUNK_tmem                      : "tmem",
+    CHUNK_tmem_extra                : "tmem_extra",
+    CHUNK_tsc_info                  : "tsc_info",
+    CHUNK_hvm_console_pfn           : "hvm_console_pfn",
+    CHUNK_last_checkpoint           : "last_checkpoint",
+    CHUNK_hvm_acpi_ioports_location : "hvm_acpi_ioports_location",
+    CHUNK_hvm_viridian              : "hvm_viridian",
+    CHUNK_compressed_data           : "compressed_data",
+    CHUNK_enable_compression        : "enable_compression",
+    CHUNK_hvm_generation_id_addr    : "hvm_generation_id_addr",
+    CHUNK_hvm_paging_ring_pfn       : "hvm_paging_ring_pfn",
+    CHUNK_hvm_monitor_ring_pfn      : "hvm_monitor_ring_pfn",
+    CHUNK_hvm_sharing_ring_pfn      : "hvm_sharing_ring_pfn",
+    CHUNK_toolstack                 : "toolstack",
+    CHUNK_hvm_ioreq_server_pfn      : "hvm_ioreq_server_pfn",
+    CHUNK_hvm_nr_ioreq_server_pages : "hvm_nr_ioreq_server_pages",
+}
+
+# Up to 1024 pages (4MB) at a time
+MAX_BATCH = 1024
+
+# Maximum #VCPUs currently supported for save/restore
+MAX_VCPU_ID = 4095
tools/python/xen/migration/public.py new file +21 -0
new file mode 100644
index 0000000..fab2f84
@@ -0,0 +1,21 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Xen public ABI constants, used in migration
+"""
+
+HVM_PARAM_STORE_PFN             = 1
+HVM_PARAM_IOREQ_PFN             = 5
+HVM_PARAM_BUFIOREQ_PFN          = 6
+HVM_PARAM_VIRIDIAN              = 9
+HVM_PARAM_IDENT_PT              = 12
+HVM_PARAM_VM86_TSS              = 15
+HVM_PARAM_CONSOLE_PFN           = 17
+HVM_PARAM_ACPI_IOPORTS_LOCATION = 19
+HVM_PARAM_PAGING_RING_PFN       = 27
+HVM_PARAM_MONITOR_RING_PFN      = 28
+HVM_PARAM_SHARING_RING_PFN      = 29
+HVM_PARAM_IOREQ_SERVER_PFN      = 32
+HVM_PARAM_NR_IOREQ_SERVER_PAGES = 33
+HVM_PARAM_VM_GENERATION_ID_ADDR = 34
tools/python/xen/migration/xl.py new file +12 -0
new file mode 100644
index 0000000..978e744
@@ -0,0 +1,12 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+XL migration stream format
+"""
+
+MAGIC = "Xen saved domain, xl format\n \0 \r"
+
+HEADER_FORMAT = "=IIII"
+
+MANDATORY_FLAG_STREAMV2 = 2
Signature · 1 line
1.7.10.4
#17 lore raw

PATCH v3 14/28 tools/python: Verification utility for v2 stream spec compliance

In reply to Andrew Cooper

---
This is exceedingly useful for development, but not of practical use being installed into a production dom0.

---
 tools/python/scripts/verify-stream-v2 |  174 +++++++++++++++++++++++++++++++++
 1 file changed, 174 insertions(+)
 create mode 100755 tools/python/scripts/verify-stream-v2
tools/python/scripts/verify-stream-v2 new file +174 -0
new file mode 100755
index 0000000..3daf257
@@ -0,0 +1,174 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+""" Verify a v2 format migration stream """
+
+import sys
+import struct
+import os, os.path
+import syslog
+import traceback
+
+from xen.migration.verify import StreamError, RecordError
+from xen.migration.libxc import VerifyLibxc
+from xen.migration.libxl import VerifyLibxl
+
+fin = None             # Input file/fd
+log_to_syslog = False  # Boolean - Log to syslog instead of stdout/err?
+verbose = False        # Boolean - Summarise stream contents
+quiet = False          # Boolean - Suppress error printing
+
+def info(msg):
+    """Info message, routed to appropriate destination"""
+    if not quiet and verbose:
+        if log_to_syslog:
+            for line in msg.split("\n"):
+                syslog.syslog(syslog.LOG_INFO, line)
+        else:
+            print msg
+
+def err(msg):
+    """Error message, routed to appropriate destination"""
+    if not quiet:
+        if log_to_syslog:
+            for line in msg.split("\n"):
+                syslog.syslog(syslog.LOG_ERR, line)
+        print >> sys.stderr, msg
+
+def stream_read(_ = None):
+    """Read from input"""
+    return fin.read(_)
+
+def rdexact(nr_bytes):
+    """Read exactly nr_bytes from fin"""
+    _ = stream_read(nr_bytes)
+    if len(_) != nr_bytes:
+        raise IOError("Stream truncated")
+    return _
+
+def unpack_exact(fmt):
+    """Unpack a format from fin"""
+    sz = struct.calcsize(fmt)
+    return struct.unpack(fmt, rdexact(sz))
+
+
+def skip_xl_header():
+    """Skip over an xl header in the stream"""
+
+    hdr = rdexact(32)
+    if hdr != "Xen saved domain, xl format\n \0 \r":
+        raise StreamError("No xl header")
+
+    _, mflags, _, optlen = unpack_exact("=IIII")
+    _ = rdexact(optlen)
+
+    info("Processed xl header")
+
+    if mflags & 2: # XL_MANDATORY_FLAG_STREAMv2
+        return "libxl"
+    else:
+        return "libxc"
+
+def read_stream(fmt):
+    """ Read an entire stream """
+
+    try:
+        if fmt == "xl":
+            fmt = skip_xl_header()
+
+        if fmt == "libxc":
+            VerifyLibxc(info, stream_read).verify()
+        else:
+            VerifyLibxl(info, stream_read).verify()
+
+    except (IOError, StreamError, RecordError):
+        err("Stream Error:")
+        err(traceback.format_exc())
+        return 1
+
+    except StandardError:
+        err("Script Error:")
+        err(traceback.format_exc())
+        err("Please fix me")
+        return 2
+
+    return 0
+
+def open_file_or_fd(val, mode, buffering):
+    """
+    If 'val' looks like a decimal integer, open it as an fd.  If not, try to
+    open it as a regular file.
+    """
+
+    fd = -1
+    try:
+        # Does it look like an integer?
+        try:
+            fd = int(val, 10)
+        except ValueError:
+            pass
+
+        # Try to open it...
+        if fd != -1:
+            return os.fdopen(fd, mode, buffering)
+        else:
+            return open(val, mode, buffering)
+
+    except StandardError, e:
+        if fd != -1:
+            err("Unable to open fd %d: %s: %s" %
+                (fd, e.__class__.__name__, e))
+        else:
+            err("Unable to open file '%s': %s: %s" %
+                (val, e.__class__.__name__, e))
+
+    raise SystemExit(2)
+
+def main():
+    """ main """
+    from optparse import OptionParser
+    global fin, quiet, verbose
+
+    # Change stdout to be line-buffered.
+    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)
+
+    parser = OptionParser(usage = "%prog [options]",
+                          description =
+                          "Verify a stream according to the v2 spec")
+
+    # Optional options
+    parser.add_option("-i", "--in", dest = "fin", metavar = "<FD or FILE>",
+                      default = "0",
+                      help = "Stream to verify (defaults to stdin)")
+    parser.add_option("-v", "--verbose", action = "store_true", default = False,
+                      help = "Summarise stream contents")
+    parser.add_option("-q", "--quiet", action = "store_true", default = False,
+                      help = "Suppress all logging/errors")
+    parser.add_option("-f", "--format", dest = "format",
+                      metavar = "<libxc|libxl|xl>", default = "libxc",
+                      choices = ["libxc", "libxl", "xl"],
+                      help = "Format of the incoming stream (defaults to libxc)")
+    parser.add_option("--syslog", action = "store_true", default = False,
+                      help = "Log to syslog instead of stdout")
+
+    opts, _ = parser.parse_args()
+
+    if opts.syslog:
+        global log_to_syslog
+
+        syslog.openlog("verify-stream-v2", syslog.LOG_PID)
+        log_to_syslog = True
+
+    verbose = opts.verbose
+    quiet = opts.quiet
+    fin = open_file_or_fd(opts.fin, "rb", 0)
+
+    return read_stream(opts.format)
+
+if __name__ == "__main__":
+    try:
+        sys.exit(main())
+    except SystemExit, e:
+        sys.exit(e.code)
+    except KeyboardInterrupt:
+        sys.exit(2)
Signature · 1 line
1.7.10.4
#18 lore raw

PATCH v3 15/28 tools/python: Conversion utility for legacy migration streams

In reply to Andrew Cooper

This utility will take a legacy stream as in input, and produce a v2 stream as an output. It is exec()'d by libxl to provide backwards compatibility.

---
 tools/python/Makefile                      |    4 +
 tools/python/scripts/convert-legacy-stream |  678 ++++++++++++++++++++++++++++
 2 files changed, 682 insertions(+)
 create mode 100755 tools/python/scripts/convert-legacy-stream
tools/python/Makefile +4 -0
index e933be8..df942a7 100644
@@ -17,9 +17,13 @@ build: genwrap.py $(XEN_ROOT)/tools/libxl/libxl_types.idl \
 
 .PHONY: install
 install:
+	$(INSTALL_DIR) $(DESTDIR)$(PRIVATE_BINDIR)
+
 	CC="$(CC)" CFLAGS="$(PY_CFLAGS)" $(PYTHON) setup.py install \
 		$(PYTHON_PREFIX_ARG) --root="$(DESTDIR)" --force
 
+	$(INSTALL_PROG) scripts/convert-legacy-stream $(DESTDIR)$(PRIVATE_BINDIR)
+
 .PHONY: test
 test:
 	export LD_LIBRARY_PATH=$$(readlink -f ../libxc):$$(readlink -f ../xenstore); $(PYTHON) test.py -b -u
tools/python/scripts/convert-legacy-stream new file +678 -0

678 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#19 lore raw

PATCH v3 16/28 tools/libxl: Migration v2 stream format

In reply to Andrew Cooper

From: Ross Lagerwall <[email protected]>

C structures describing the Libxl migration v2 stream format

---
v2: Move into libxl__ namespace

---
 tools/libxl/libxl_sr_stream_format.h |   57 ++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
 create mode 100644 tools/libxl/libxl_sr_stream_format.h
tools/libxl/libxl_sr_stream_format.h new file +57 -0
new file mode 100644
index 0000000..f4f790b
@@ -0,0 +1,57 @@
+#ifndef LIBXL__SR_STREAM_FORMAT_H
+#define LIBXL__SR_STREAM_FORMAT_H
+
+/*
+ * C structures for the Migration v2 stream format.
+ * See docs/specs/libxl-migration-stream.pandoc
+ */
+
+#include <stdint.h>
+
+typedef struct libxl__sr_hdr
+{
+    uint64_t ident;
+    uint32_t version;
+    uint32_t options;
+} libxl__sr_hdr;
+
+#define RESTORE_STREAM_IDENT         0x4c6962786c466d74UL
+#define RESTORE_STREAM_VERSION       0x00000002U
+
+#define RESTORE_OPT_BIG_ENDIAN       (1u << 0)
+#define RESTORE_OPT_LEGACY           (1u << 1)
+
+
+typedef struct libxl__sr_rec_hdr
+{
+    uint32_t type;
+    uint32_t length;
+} libxl__sr_rec_hdr;
+
+/* All records must be aligned up to an 8 octet boundary */
+#define REC_ALIGN_ORDER              3U
+
+#define REC_TYPE_END                 0x00000000U
+#define REC_TYPE_LIBXC_CONTEXT       0x00000001U
+#define REC_TYPE_XENSTORE_DATA       0x00000002U
+#define REC_TYPE_EMULATOR_CONTEXT    0x00000003U
+
+typedef struct libxl__sr_emulator_hdr
+{
+    uint32_t id;
+    uint32_t index;
+} libxl__sr_emulator_hdr;
+
+#define EMULATOR_UNKNOWN             0x00000000U
+#define EMULATOR_QEMU_TRADITIONAL    0x00000001U
+#define EMULATOR_QEMU_UPSTREAM       0x00000002U
+
+#endif /* LIBXL__SR_STREAM_FORMAT_H */
+
+/*
+ * Local variables:
+ * mode: C
+ * c-basic-offset: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
Signature · 1 line
1.7.10.4
#20 lore raw

PATCH v3 17/28 tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Andrew Cooper

From: Ross Lagerwall <[email protected]>

This contains the event machinery and state machines to read an act on a non-checkpointed migration v2 stream (with the exception of the xc_domain_restore() handling which is spliced later in a bisectable way).

It also contains some boilerplate to help support checkpointed streams, which shall be introduced in a later patch.

---
v3: More descriptions of the internal state, shuffle function order, add
an _init() call, condense error handling

---
 tools/libxl/Makefile            |    1 +
 tools/libxl/libxl_internal.h    |   53 ++++
 tools/libxl/libxl_stream_read.c |  541 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 595 insertions(+)
 create mode 100644 tools/libxl/libxl_stream_read.c
tools/libxl/Makefile +1 -0
index cc9c152..c71c5fe 100644
@@ -94,6 +94,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_numa.o libxl_vnuma.o \
+			libxl_stream_read.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_genid.o
tools/libxl/libxl_internal.h +53 -0

65 lines not on this page · raw message

tools/libxl/libxl_stream_read.c new file +541 -0

541 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#31 lore raw

PATCH v3 18/28 tools/libxl: Infrastructure to convert a legacy stream

In reply to Andrew Cooper

Provide a thin wrapper around exec()ing the python conversion utility, and a stub implementation for cases where conversion is not wanted (i.e. not x86).

One complication is that the caller of this interface needs to assume ownership of the output fd, to prevent it being closed while still in use in a datacopier.

CC Ian Campbell <[email protected]>
CC Ian Jackson <[email protected]>
CC Wei Liu <[email protected]>

---
v3: Trimmed down massively from v2, provide libxl_no_convert_callout.c

---
 tools/libxl/Makefile                   |    6 ++
 tools/libxl/libxl_convert_callout.c    |  158 ++++++++++++++++++++++++++++++++
 tools/libxl/libxl_internal.h           |   32 +++++++
 tools/libxl/libxl_no_convert_callout.c |   35 +++++++
 4 files changed, 231 insertions(+)
 create mode 100644 tools/libxl/libxl_convert_callout.c
 create mode 100644 tools/libxl/libxl_no_convert_callout.c
tools/libxl/Makefile +6 -0
index c71c5fe..68fe1c1 100644
@@ -56,6 +56,12 @@ else
 LIBXL_OBJS-y += libxl_nonetbuffer.o
 endif
 
+ifeq ($(CONFIG_X86),y)
+LIBXL_OBJS-y += libxl_convert_callout.o
+else
+LIBXL_OBJS-y += libxl_no_convert_callout.o
+endif
+
 LIBXL_OBJS-y += libxl_remus_device.o libxl_remus_disk_drbd.o
 
 LIBXL_OBJS-$(CONFIG_X86) += libxl_cpuid.o libxl_x86.o libxl_psr.o
tools/libxl/libxl_convert_callout.c new file +158 -0

158 lines not on this page · raw message

tools/libxl/libxl_internal.h +32 -0
index c0e7720..4de7349 100644
@@ -2917,6 +2917,38 @@ _hidden void libxl__remus_devices_commit(libxl__egc *egc,
                                          libxl__remus_devices_state *rds);
 _hidden int libxl__netbuffer_enabled(libxl__gc *gc);
 
+/*----- Legacy conversion helper -----*/
+typedef struct libxl__conversion_helper_state libxl__conversion_helper_state;
+
+struct libxl__conversion_helper_state {
+    /* public */
+    libxl__ao *ao;
+    int legacy_fd;
+    bool hvm;                  /* pv or hvm domain? */
+    libxl__carefd *v2_carefd;  /* Filled by successful call to
+                                * libxl__convert_legacy_stream().  Caller
+                                * assumes ownership of the fd. */
+    void (*completion_callback)(
+        libxl__egc *egc, libxl__conversion_helper_state *chs, int rc);
+    /* private */
+    int rc;
+    libxl__ao_abortable abrt;
+    libxl__ev_child child;
+};
+
+_hidden void libxl__conversion_helper_init(libxl__conversion_helper_state *chs);
+_hidden int libxl__convert_legacy_stream(libxl__egc *egc,
+                                         libxl__conversion_helper_state *chs);
+_hidden void libxl__conversion_helper_abort(libxl__egc *egc,
+                                            libxl__conversion_helper_state *chs,
+                                            int rc);
+static inline bool
+libxl__conversion_helper_inuse(const libxl__conversion_helper_state *chs)
+{
+    return libxl__ev_child_inuse(&chs->child);
+}
+
+
 /*----- Domain suspend (save) state structure -----*/
 
 typedef struct libxl__domain_suspend_state libxl__domain_suspend_state;
tools/libxl/libxl_no_convert_callout.c new file +35 -0
new file mode 100644
index 0000000..6ba4d92
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2015      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__conversion_helper_init(libxl__conversion_helper_state *chs)
+{
+    libxl__ev_child_init(&chs->child);
+}
+
+int libxl__convert_legacy_stream(libxl__egc *egc,
+                                 libxl__conversion_helper_state *chs)
+{
+    return ERROR_FAIL;
+}
+
+void libxl__conversion_helper_abort(libxl__egc *egc,
+                                    libxl__conversion_helper_state *chs,
+                                    int rc)
+{
+    /* no op */
+}
Signature · 1 line
1.7.10.4
#38 lore raw

PATCH v3 19/28 tools/libxl: Convert a legacy stream if needed

In reply to Andrew Cooper

For backwards compatibility, a legacy stream needs converting before it can be read by the v2 stream logic.

This causes the v2 stream logic to need to juggle two parallel tasks. check_all_finished() is introduced for the purpose of joining the tasks in both success and error cases.

CC Ian Campbell <[email protected]>
CC Ian Jackson <[email protected]>
CC Wei Liu <[email protected]>

---
v3: Simplified greatly from v2. No practical change.

---
 tools/libxl/libxl_internal.h    |    2 ++
 tools/libxl/libxl_stream_read.c |   66 ++++++++++++++++++++++++++++++++++++++-
 2 files changed, 67 insertions(+), 1 deletion(-)
tools/libxl/libxl_internal.h +2 -0
index 4de7349..8afff06 100644
@@ -3260,12 +3260,14 @@ struct libxl__stream_read_state {
     libxl__ao *ao;
     libxl__domain_create_state *dcs;
     int fd;
+    bool legacy;
     void (*completion_callback)(libxl__egc *egc,
                                 libxl__stream_read_state *srs,
                                 int rc);
     /* Private */
     int rc;
     bool running;
+    libxl__conversion_helper_state chs;
 
     /* Main stream-reading data. */
     libxl__datacopier_state dc;
tools/libxl/libxl_stream_read.c +65 -1

107 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#42 lore raw

PATCH v3 20/28 tools/libxc+libxl+xl: Restore v2 streams

In reply to Andrew Cooper

This is a complicated set of changes which must be done together for bisectability.

* libxl-save-helper is updated to unconditionally use libxc migration v2.
* libxl compatibility workarounds in libxc are disabled for restore operations.
* libxl__stream_read_start() is logically spliced into the event location where libxl__xc_domain_restore() used to reside.
* Ownership of the save_helper_state moves to stream_read_state.

The parameters 'hvm', 'pae', and 'superpages' were previously superfluous, and are completely unused in migration
v2. callbacks->toolstack_restore is handled via a migration v2 record now, rather than via a callback from libxc.

NB: this change breaks Remus. Further untangling needs to happen before Remus will function.

CC Ian Campbell <[email protected]>
CC Ian Jackson <[email protected]>
CC Wei Liu <[email protected]>

---
v3:
* Simplify from v2.
* Alter the ownership of save_helper_state

v2:
* Drop "legacy_width" from the IDL
* Gain a LIBXL_HAVE_ to signify support of migration v2 streams

---
 tools/libxc/Makefile            |    4 +--
 tools/libxl/libxl.h             |   17 +++++++++++++
 tools/libxl/libxl_create.c      |   52 ++++++++++++++-------------------------
 tools/libxl/libxl_internal.h    |    3 ++-
 tools/libxl/libxl_save_helper.c |    2 +-
 tools/libxl/libxl_stream_read.c |   35 +++++++++++++++++++++++++-
 tools/libxl/libxl_types.idl     |    1 +
 tools/libxl/xl_cmdimpl.c        |    7 +++++-
 8 files changed, 81 insertions(+), 40 deletions(-)
tools/libxc/Makefile +2 -2
index b659df4..2cd0b1a 100644
@@ -64,8 +64,8 @@ GUEST_SRCS-$(CONFIG_X86) += xc_sr_save_x86_hvm.c
 GUEST_SRCS-y += xc_sr_restore.c
 GUEST_SRCS-y += xc_sr_save.c
 GUEST_SRCS-y += xc_offline_page.c xc_compression.c
-$(patsubst %.c,%.o,$(GUEST_SRCS-y)): CFLAGS += -DXG_LIBXL_HVM_COMPAT
-$(patsubst %.c,%.opic,$(GUEST_SRCS-y)): CFLAGS += -DXG_LIBXL_HVM_COMPAT
+xc_sr_save_x86_hvm.o: CFLAGS += -DXG_LIBXL_HVM_COMPAT
+xc_sr_save_x86_hvm.opic: CFLAGS += -DXG_LIBXL_HVM_COMPAT
 else
 GUEST_SRCS-y += xc_nomigrate.c
 endif
tools/libxl/libxl.h +17 -0
index e9d63c9..74b0829 100644
@@ -807,6 +807,23 @@
  */
 #define LIBXL_HAVE_SOCKET_BITMAP_ALLOC 1
 
+/*
+ * LIBXL_HAVE_SRM_V2
+ *
+ * If this is defined, then the libxl_domain_create_restore() interface takes
+ * a "stream_version" parameter and supports a value of 2.
+ */
+#define LIBXL_HAVE_SRM_V2 1
+
+/*
+ * LIBXL_HAVE_SRM_V1
+ *
+ * In the case that LIBXL_HAVE_SRM_V2 is set, LIBXL_HAVE_SRM_V1
+ * indicates that libxl_domain_create_restore() can handle a "stream_version"
+ * parameter of 1, and convert the stream format automatically.
+ */
+#define LIBXL_HAVE_SRM_V1 1
+
 typedef char **libxl_string_list;
 void libxl_string_list_dispose(libxl_string_list *sl);
 int libxl_string_list_length(const libxl_string_list *sl);
tools/libxl/libxl_create.c +18 -34

88 lines not on this page · raw message

tools/libxl/libxl_internal.h +2 -1
index 8afff06..72d544a 100644
@@ -3267,6 +3267,7 @@ struct libxl__stream_read_state {
     /* Private */
     int rc;
     bool running;
+    libxl__save_helper_state shs;
     libxl__conversion_helper_state chs;
 
     /* Main stream-reading data. */
@@ -3314,7 +3315,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. */
-    libxl__save_helper_state shs;
+    libxl__stream_read_state srs;
     /* necessary if the domain creation failed and we have to destroy it */
     libxl__domain_destroy_state dds;
     libxl__multidev multidev;
tools/libxl/libxl_save_helper.c +1 -1
index 14675ae..efbe2eb 100644
@@ -313,7 +313,7 @@ int main(int argc, char **argv)
         startup("restore");
         setup_signals(SIG_DFL);
 
-        r = xc_domain_restore(xch, io_fd, dom, store_evtchn, &store_mfn,
+        r = xc_domain_restore2(xch, io_fd, dom, store_evtchn, &store_mfn,
                               store_domid, console_evtchn, &console_mfn,
                               console_domid, hvm, pae, superpages,
                               checkpointed,
tools/libxl/libxl_stream_read.c +34 -1
index 93aa479..229108b 100644
@@ -146,6 +146,7 @@ void libxl__stream_read_init(libxl__stream_read_state *stream)
 {
     FILLZERO(*stream);
     LIBXL_STAILQ_INIT(&stream->record_queue);
+    libxl__save_helper_init(&stream->shs);
     libxl__conversion_helper_init(&stream->chs);
 }
 
@@ -419,9 +420,13 @@ static bool process_record(libxl__egc *egc,
         stream_complete(egc, stream, 0);
         break;
 
+    case REC_TYPE_LIBXC_CONTEXT:
+        libxl__xc_domain_restore(egc, dcs, &stream->shs, 0, 0, 0);
+        break;
+
     case REC_TYPE_XENSTORE_DATA:
         rc = libxl__toolstack_restore(dcs->guest_domid, rec->body,
-                                      rec->hdr.length, &dcs->shs);
+                                      rec->hdr.length, &stream->shs);
         if (rc)
             goto err;
 
@@ -569,6 +574,32 @@ static void stream_done(libxl__egc *egc,
     check_all_finished(egc, stream, stream->rc);
 }
 
+void libxl__xc_domain_restore_done(libxl__egc *egc, void *dcs_void,
+                                   int rc, int retval, int errnoval)
+{
+    libxl__domain_create_state *dcs = dcs_void;
+    libxl__stream_read_state *stream = &dcs->srs;
+    STATE_AO_GC(dcs->ao);
+
+    if (rc)
+        goto err;
+
+    if (retval) {
+        LOGEV(ERROR, errnoval, "restoring domain");
+        rc = ERROR_FAIL;
+        goto err;
+    }
+
+    /*
+     * Libxc has indicated that it is done with the stream.  Resume reading
+     * libxl records from it.
+     */
+    stream_continue(egc, stream);
+
+ err:
+    check_all_finished(egc, stream, rc);
+}
+
 static void conversion_done(libxl__egc *egc,
                             libxl__conversion_helper_state *chs, int rc)
 {
@@ -587,11 +618,13 @@ static void check_all_finished(libxl__egc *egc,
         stream->rc = rc;
 
         libxl__stream_read_abort(egc, stream, rc);
+        libxl__save_helper_abort(egc, &stream->shs);
         libxl__conversion_helper_abort(egc, &stream->chs, rc);
     }
 
     /* Don't fire the callback until all our parallel tasks have stopped. */
     if (!libxl__stream_read_inuse(stream) &&
+        !libxl__save_helper_inuse(&stream->shs) &&
         !libxl__conversion_helper_inuse(&stream->chs))
         stream->completion_callback(egc, stream, stream->rc);
 }
tools/libxl/libxl_types.idl +1 -0
index 8dacf8d..bc0c4ef 100644
@@ -355,6 +355,7 @@ libxl_domain_create_info = Struct("domain_create_info",[
 
 libxl_domain_restore_params = Struct("domain_restore_params", [
     ("checkpointed_stream", integer),
+    ("stream_version", uint32, {'init_val': '1'}),
     ])
 
 libxl_domain_sched_params = Struct("domain_sched_params",[
tools/libxl/xl_cmdimpl.c +6 -1
index 26b1e7d..71a22b8 100644
@@ -110,7 +110,9 @@
 
 #define XL_MANDATORY_FLAG_JSON (1U << 0) /* config data is in JSON format */
 #define XL_MANDATORY_FLAG_STREAMv2 (1U << 1) /* stream is v2 */
-#define XL_MANDATORY_FLAG_ALL  (XL_MANDATORY_FLAG_JSON)
+#define XL_MANDATORY_FLAG_ALL  (XL_MANDATORY_FLAG_JSON |        \
+                                XL_MANDATORY_FLAG_STREAMv2)
+
 struct save_file_header {
     char magic[32]; /* savefileheader_magic */
     /* All uint32_ts are in domain's byte order. */
@@ -2757,6 +2759,9 @@ static uint32_t create_domain(struct domain_create *dom_info)
         libxl_domain_restore_params_init(&params);
 
         params.checkpointed_stream = dom_info->checkpointed_stream;
+        params.stream_version =
+            (hdr.mandatory_flags & XL_MANDATORY_FLAG_STREAMv2) ? 2 : 1;
+
         ret = libxl_domain_create_restore(ctx, &d_config,
                                           &domid, restore_fd,
                                           &params,
Signature · 1 line
1.7.10.4
#44 lore raw

PATCH v3 21/28 tools/libxl: Infrastructure for writing a v2 stream

In reply to Andrew Cooper

From: Ross Lagerwall <[email protected]>

This contains the event machinery and state machines to write non-checkpointed migration v2 stream (with the exception of the xc_domain_save() handling which is spliced later in a bisectable way).

---
v3: Similar changes to the read side, following the read side review.

---
 tools/libxl/Makefile             |    2 +-
 tools/libxl/libxl_internal.h     |   39 ++++
 tools/libxl/libxl_stream_write.c |  425 ++++++++++++++++++++++++++++++++++++++
 3 files changed, 465 insertions(+), 1 deletion(-)
 create mode 100644 tools/libxl/libxl_stream_write.c
tools/libxl/Makefile +1 -1
index 68fe1c1..0150ec7 100644
@@ -100,7 +100,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_numa.o libxl_vnuma.o \
-			libxl_stream_read.o \
+			libxl_stream_read.o libxl_stream_write.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_genid.o
tools/libxl/libxl_internal.h +39 -0
index 72d544a..c93f4a6 100644
@@ -2958,6 +2958,45 @@ typedef void libxl__domain_suspend_cb(libxl__egc*,
 typedef void libxl__save_device_model_cb(libxl__egc*,
                                          libxl__domain_suspend_state*, int rc);
 
+/* State for writing a libxl migration v2 stream */
+typedef struct libxl__stream_write_state libxl__stream_write_state;
+typedef void (*sws_record_done_cb)(libxl__egc *egc,
+                                   libxl__stream_write_state *sws);
+struct libxl__stream_write_state {
+    /* filled by the user */
+    libxl__ao *ao;
+    libxl__domain_suspend_state *dss;
+    int fd;
+    void (*completion_callback)(libxl__egc *egc,
+                                libxl__stream_write_state *sws,
+                                int rc);
+    /* Private */
+    int rc;
+    bool running;
+
+    /* Main stream-writing data. */
+    libxl__datacopier_state dc;
+    sws_record_done_cb record_done_callback;
+
+    /* Only used when constructing an EMULATOR record. */
+    libxl__datacopier_state emu_dc;
+    libxl__carefd *emu_carefd;
+    libxl__sr_rec_hdr emu_rec_hdr;
+    void *emu_body;
+};
+
+_hidden void libxl__stream_write_init(libxl__stream_write_state *stream);
+_hidden void libxl__stream_write_start(libxl__egc *egc,
+                                       libxl__stream_write_state *stream);
+_hidden void libxl__stream_write_abort(libxl__egc *egc,
+                                       libxl__stream_write_state *stream,
+                                       int rc);
+static inline bool
+libxl__stream_write_inuse(const libxl__stream_write_state *stream)
+{
+    return stream->running;
+}
+
 typedef struct libxl__logdirty_switch {
     const char *cmd;
     const char *cmd_path;
tools/libxl/libxl_stream_write.c new file +425 -0

425 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#50 lore raw

PATCH v3 22/28 tools/libxc+libxl+xl: Save v2 streams

In reply to Andrew Cooper

This is a complicated set of changes which must be done together for bisectability.

* libxl-save-helper is updated to unconditionally use libxc migration v2.
* libxl compatibility workarounds in libxc are disabled for save operations.
* libxl__stream_write_start() is logically spliced into the event location where libxl__xc_domain_save() used to reside.
* Ownership of the helper state moves into stream_write_state.
* xl is updated to indicate that the stream is now v2

CC Ian Campbell <[email protected]>
CC Ian Jackson <[email protected]>
CC Wei Liu <[email protected]>

---
v3: Many small changes, follwing similar review to the restore side

---
 tools/libxc/Makefile             |    2 --
 tools/libxl/libxl.h              |    2 ++
 tools/libxl/libxl_dom.c          |   73 ++++++++++++--------------------------
 tools/libxl/libxl_internal.h     |    3 +-
 tools/libxl/libxl_save_helper.c  |    2 +-
 tools/libxl/libxl_stream_write.c |   39 +++++++++++++++++---
 tools/libxl/xl_cmdimpl.c         |    1 +
 7 files changed, 63 insertions(+), 59 deletions(-)
tools/libxc/Makefile +0 -2
index 2cd0b1a..1aec848 100644
@@ -64,8 +64,6 @@ GUEST_SRCS-$(CONFIG_X86) += xc_sr_save_x86_hvm.c
 GUEST_SRCS-y += xc_sr_restore.c
 GUEST_SRCS-y += xc_sr_save.c
 GUEST_SRCS-y += xc_offline_page.c xc_compression.c
-xc_sr_save_x86_hvm.o: CFLAGS += -DXG_LIBXL_HVM_COMPAT
-xc_sr_save_x86_hvm.opic: CFLAGS += -DXG_LIBXL_HVM_COMPAT
 else
 GUEST_SRCS-y += xc_nomigrate.c
 endif
tools/libxl/libxl.h +2 -0
index 74b0829..5a7308d 100644
@@ -812,6 +812,8 @@
  *
  * If this is defined, then the libxl_domain_create_restore() interface takes
  * a "stream_version" parameter and supports a value of 2.
+ *
+ * libxl_domain_suspend() will produce a v2 stream.
  */
 #define LIBXL_HAVE_SRM_V2 1
 
tools/libxl/libxl_dom.c +23 -50

153 lines not on this page · raw message

tools/libxl/libxl_internal.h +2 -1
index c93f4a6..6827e9c 100644
@@ -2973,6 +2973,7 @@ struct libxl__stream_write_state {
     /* Private */
     int rc;
     bool running;
+    libxl__save_helper_state shs;
 
     /* Main stream-writing data. */
     libxl__datacopier_state dc;
@@ -3030,7 +3031,7 @@ struct libxl__domain_suspend_state {
     libxl__remus_devices_state rds;
     libxl__ev_time checkpoint_timeout; /* used for Remus checkpoint */
     int interval; /* checkpoint interval (for Remus) */
-    libxl__save_helper_state shs;
+    libxl__stream_write_state sws;
     libxl__logdirty_switch logdirty;
     void (*callback_common_done)(libxl__egc*,
                                  struct libxl__domain_suspend_state*, int ok);
tools/libxl/libxl_save_helper.c +1 -1
index efbe2eb..f196786 100644
@@ -286,7 +286,7 @@ int main(int argc, char **argv)
         startup("save");
         setup_signals(save_signal_handler);
 
-        r = xc_domain_save(xch, io_fd, dom, max_iters, max_factor, flags,
+        r = xc_domain_save2(xch, io_fd, dom, max_iters, max_factor, flags,
                            &helper_save_callbacks, hvm);
         complete(r);
 
tools/libxl/libxl_stream_write.c +34 -5
index 2e40978..1847ec9 100644
@@ -203,11 +203,40 @@ static void stream_header_done(libxl__egc *egc,
 static void libxc_header_done(libxl__egc *egc,
                               libxl__stream_write_state *stream)
 {
-    libxl__xc_domain_save(egc, stream->dss, &stream->dss->shs);
+    libxl__xc_domain_save(egc, stream->dss, &stream->shs);
 }
 
-static void __attribute__((unused))
-write_toolstack_record(libxl__egc *egc,
+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;
+    libxl__stream_write_state *stream = &dss->sws;
+    STATE_AO_GC(dss->ao);
+
+    if (rc)
+        goto err;
+
+    if (retval) {
+        LOGEV(ERROR, errnoval, "saving domain: %s",
+              dss->guest_responded ?
+              "domain responded to suspend request" :
+              "domain did not respond to suspend request");
+        if (!dss->guest_responded)
+            rc = ERROR_GUEST_TIMEDOUT;
+        else if (dss->rc)
+            rc = dss->rc;
+        else
+            rc = ERROR_FAIL;
+        goto err;
+    }
+
+    write_toolstack_record(egc, stream);
+
+ err:
+    check_all_finished(egc, stream, rc);
+}
+
+static void write_toolstack_record(libxl__egc *egc,
                                    libxl__stream_write_state *stream)
 {
     libxl__domain_suspend_state *dss = stream->dss;
@@ -407,12 +436,12 @@ static void check_all_finished(libxl__egc *egc,
         stream->rc = rc;
 
         libxl__stream_write_abort(egc, stream, rc);
-        libxl__save_helper_abort(egc, &dss->shs);
+        libxl__save_helper_abort(egc, &stream->shs);
     }
 
     /* Don't fire the callback until all our parallel tasks have stopped. */
     if (!libxl__stream_write_inuse(stream) &&
-        !libxl__save_helper_inuse(&dss->shs))
+        !libxl__save_helper_inuse(&stream->shs))
         stream->completion_callback(egc, stream, stream->rc);
 }
 
tools/libxl/xl_cmdimpl.c +1 -0
index 71a22b8..13e154d 100644
@@ -3922,6 +3922,7 @@ static void save_domain_core_writeconfig(int fd, const char *source,
     memset(&hdr, 0, sizeof(hdr));
     memcpy(hdr.magic, savefileheader_magic, sizeof(hdr.magic));
     hdr.byteorder = SAVEFILE_BYTEORDER_VALUE;
+    hdr.mandatory_flags = XL_MANDATORY_FLAG_STREAMv2;
 
     optdata_begin= 0;
 
Signature · 1 line
1.7.10.4
#52 lore raw

PATCH v3 23/28 docs/libxl: Introduce CHECKPOINT_END to support migration v2 remus streams

In reply to Andrew Cooper

In a remus scenario, libxc will write a CHECKPOINT record, then hand ownership of the fd to libxl. Libxl then writes any records required and finishes with a CHECKPOINT_END record, then hands ownership of the fd back to libxc.

---
 docs/specs/libxl-migration-stream.pandoc |   14 +++++++++++++-
 tools/libxl/libxl_sr_stream_format.h     |    1 +
 tools/python/xen/migration/libxl.py      |   11 +++++++++++
 3 files changed, 25 insertions(+), 1 deletion(-)
docs/specs/libxl-migration-stream.pandoc +13 -1
index 4192950..c24a434 100644
@@ -119,7 +119,9 @@ type         0x00000000: END
 
              0x00000003: EMULATOR_CONTEXT
 
-             0x00000004 - 0x7FFFFFFF: Reserved for future _mandatory_
+             0x00000004: CHECKPOINT_END
+
+             0x00000005 - 0x7FFFFFFF: Reserved for future _mandatory_
              records.
 
              0x80000000 - 0xFFFFFFFF: Reserved for future _optional_
@@ -203,3 +205,13 @@ index            Index of this emulator for the domain, if multiple
 
 emulator_ctx     Emulator context blob.
 --------------------------------------------------------------------
+
+CHECKPOINT\_END
+---------------
+
+A checkpoint end record marks the end of a checkpoint in the image.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+
+The end record contains no fields; its body_length is 0.
tools/libxl/libxl_sr_stream_format.h +1 -0
index f4f790b..3f3c497 100644
@@ -35,6 +35,7 @@
 #define REC_TYPE_LIBXC_CONTEXT       0x00000001U
 #define REC_TYPE_XENSTORE_DATA       0x00000002U
 #define REC_TYPE_EMULATOR_CONTEXT    0x00000003U
+#define REC_TYPE_CHECKPOINT_END      0x00000004U
 
 typedef struct libxl__sr_emulator_hdr
 {
tools/python/xen/migration/libxl.py +11 -0
index 4e1f4f8..415502e 100644
@@ -36,12 +36,14 @@ REC_TYPE_end              = 0x00000000
 REC_TYPE_libxc_context    = 0x00000001
 REC_TYPE_xenstore_data    = 0x00000002
 REC_TYPE_emulator_context = 0x00000003
+REC_TYPE_checkpoint_end   = 0x00000004
 
 rec_type_to_str = {
     REC_TYPE_end              : "End",
     REC_TYPE_libxc_context    : "Libxc context",
     REC_TYPE_xenstore_data    : "Xenstore data",
     REC_TYPE_emulator_context : "Emulator context",
+    REC_TYPE_checkpoint_end   : "Checkpoint end",
 }
 
 # emulator_context
@@ -176,6 +178,13 @@ class VerifyLibxl(VerifyBase):
         self.info("  Index %d, type %s" % (emu_idx, emulator_id_to_str[emu_id]))
 
 
+    def verify_record_checkpoint_end(self, content):
+        """ Checkpoint end record """
+
+        if len(content) != 0:
+            raise RecordError("Checkpoint end record with non-zero length")
+
+
 record_verifiers = {
     REC_TYPE_end:
         VerifyLibxl.verify_record_end,
@@ -185,4 +194,6 @@ record_verifiers = {
         VerifyLibxl.verify_record_xenstore_data,
     REC_TYPE_emulator_context:
         VerifyLibxl.verify_record_emulator_context,
+    REC_TYPE_checkpoint_end:
+        VerifyLibxl.verify_record_checkpoint_end,
 }
Signature · 1 line
1.7.10.4
#53 lore raw

PATCH v3 24/28 tools/libxl: Write checkpoint records into the stream

In reply to Andrew Cooper

when signalled to do so by libxl__remus_domain_checkpoint_callback()

---
v3: Corrections to comments

This patch has changed substantially in v2 as a result of changes earlier in the series. No behavioural difference from v1.

---
 tools/libxl/libxl_dom.c          |   18 ++++-----
 tools/libxl/libxl_internal.h     |    7 ++++
 tools/libxl/libxl_stream_write.c |   77 ++++++++++++++++++++++++++++++++++++--
 3 files changed, 89 insertions(+), 13 deletions(-)
tools/libxl/libxl_dom.c +8 -10
index 0794b30..98eb824 100644
@@ -1937,8 +1937,8 @@ static void remus_devices_preresume_cb(libxl__egc *egc,
 
 /*----- remus asynchronous checkpoint callback -----*/
 
-static void remus_checkpoint_dm_saved(libxl__egc *egc,
-                                      libxl__domain_suspend_state *dss, int rc);
+static void remus_checkpoint_stream_written(
+    libxl__egc *egc, libxl__stream_write_state *sws, int rc);
 static void remus_devices_commit_cb(libxl__egc *egc,
                                     libxl__remus_devices_state *rds,
                                     int rc);
@@ -1953,17 +1953,14 @@ static void libxl__remus_domain_checkpoint_callback(void *data)
     libxl__egc *egc = shs->egc;
     STATE_AO_GC(dss->ao);
 
-    /* This would go into tailbuf. */
-    if (dss->hvm) {
-        libxl__domain_save_device_model(egc, dss, remus_checkpoint_dm_saved);
-    } else {
-        remus_checkpoint_dm_saved(egc, dss, 0);
-    }
+    libxl__stream_write_start_checkpoint(egc, &dss->sws);
 }
 
-static void remus_checkpoint_dm_saved(libxl__egc *egc,
-                                      libxl__domain_suspend_state *dss, int rc)
+static void remus_checkpoint_stream_written(
+    libxl__egc *egc, libxl__stream_write_state *sws, int rc)
 {
+    libxl__domain_suspend_state *dss = CONTAINER_OF(sws, *dss, sws);
+
     /* Convenience aliases */
     libxl__remus_devices_state *const rds = &dss->rds;
 
@@ -2114,6 +2111,7 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
         callbacks->suspend = libxl__remus_domain_suspend_callback;
         callbacks->postcopy = libxl__remus_domain_resume_callback;
         callbacks->checkpoint = libxl__remus_domain_checkpoint_callback;
+        dss->sws.checkpoint_callback = remus_checkpoint_stream_written;
     } else
         callbacks->suspend = libxl__domain_suspend_callback;
 
tools/libxl/libxl_internal.h +7 -0
index 6827e9c..7540ab3 100644
@@ -2970,9 +2970,13 @@ struct libxl__stream_write_state {
     void (*completion_callback)(libxl__egc *egc,
                                 libxl__stream_write_state *sws,
                                 int rc);
+    void (*checkpoint_callback)(libxl__egc *egc,
+                                libxl__stream_write_state *sws,
+                                int rc);
     /* Private */
     int rc;
     bool running;
+    bool in_checkpoint;
     libxl__save_helper_state shs;
 
     /* Main stream-writing data. */
@@ -2989,6 +2993,9 @@ struct libxl__stream_write_state {
 _hidden void libxl__stream_write_init(libxl__stream_write_state *stream);
 _hidden void libxl__stream_write_start(libxl__egc *egc,
                                        libxl__stream_write_state *stream);
+_hidden void
+libxl__stream_write_start_checkpoint(libxl__egc *egc,
+                                     libxl__stream_write_state *stream);
 _hidden void libxl__stream_write_abort(libxl__egc *egc,
                                        libxl__stream_write_state *stream,
                                        int rc);
tools/libxl/libxl_stream_write.c +74 -3

137 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#54 lore raw

PATCH v3 25/28 tools/libx{c, l}: Introduce restore_callbacks.checkpoint()

In reply to Andrew Cooper

And call it when a checkpoint record is found in the libxc stream.

Some parts of this patch have been based on patches from the COLO series.

---
v3: Named constants for the API
v2: Borrow sufficient fragments from several COLO patches to get
BROKEN_CHANNEL and checkpoint failover to function.

---
 tools/libxc/include/xenguest.h     |    7 +++++
 tools/libxc/xc_sr_common.h         |    7 +++--
 tools/libxc/xc_sr_restore.c        |   53 ++++++++++++++++++++++++++----------
 tools/libxl/libxl_save_msgs_gen.pl |    2 +-
 4 files changed, 51 insertions(+), 18 deletions(-)
tools/libxc/include/xenguest.h +7 -0
index 7581263..e95af54 100644
@@ -102,6 +102,13 @@ struct restore_callbacks {
     int (*toolstack_restore)(uint32_t domid, const uint8_t *buf,
             uint32_t size, void* data);
 
+    /* A checkpoint record has been found in the stream.
+     * returns: */
+#define XGR_CHECKPOINT_ERROR    0 /* Terminate processing */
+#define XGR_CHECKPOINT_SUCCESS  1 /* Continue reading more data from the stream */
+#define XGR_CHECKPOINT_FAILOVER 2 /* Failover and resume VM */
+    int (*checkpoint)(void* data);
+
     /* to be provided as the last argument to each callback function */
     void* data;
 };
tools/libxc/xc_sr_common.h +5 -2
index 08c66db..1f4d4e4 100644
@@ -130,10 +130,13 @@ struct xc_sr_restore_ops
      * Process an individual record from the stream.  The caller shall take
      * care of processing common records (e.g. END, PAGE_DATA).
      *
-     * @return 0 for success, -1 for failure, or the sentinel value
-     * RECORD_NOT_PROCESSED.
+     * @return 0 for success, -1 for failure, or the following sentinels:
+     *  - RECORD_NOT_PROCESSED
+     *  - BROKEN_CHANNEL: under Remus/COLO, this means master may be dead, and
+     *    a failover is needed.
      */
 #define RECORD_NOT_PROCESSED 1
+#define BROKEN_CHANNEL 2
     int (*process_record)(struct xc_sr_context *ctx, struct xc_sr_record *rec);
 
     /**
tools/libxc/xc_sr_restore.c +38 -15

88 lines not on this page · raw message

tools/libxl/libxl_save_msgs_gen.pl +1 -1
index 6b4b65e..825d5cc 100755
@@ -25,7 +25,7 @@ our @msgs = (
                                                 'unsigned long', 'total'] ],
     [  3, 'scxA',   "suspend", [] ],
     [  4, 'scxA',   "postcopy", [] ],
-    [  5, 'scxA',   "checkpoint", [] ],
+    [  5, 'srcxA',  "checkpoint", [] ],
     [  6, 'scxA',   "switch_qemu_logdirty",  [qw(int domid
                                               unsigned enable)] ],
     #                toolstack_save          done entirely `by hand'
Signature · 1 line
1.7.10.4
#55 lore raw

PATCH v3 26/28 tools/libxl: Handle checkpoint records in a libxl migration v2 stream

In reply to Andrew Cooper

This is the final bit of untangling for Remus.

When libxc issues a checkpoint callback, start reading and buffering all libxl records from the stream. Once a CHECKPOINT_END record is encountered, start processing all records.

CC Ian Campbell <[email protected]>
CC Ian Jackson <[email protected]>
CC Wei Liu <[email protected]>

---
v3: Simplify, use named constants for API

---
 tools/libxl/libxl_create.c      |   25 ++++++++
 tools/libxl/libxl_internal.h    |    8 +++
 tools/libxl/libxl_stream_read.c |  130 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 163 insertions(+)
tools/libxl/libxl_create.c +25 -0
index f2b5ffb..e42de47 100644
@@ -672,6 +672,27 @@ static int store_libxl_entry(libxl__gc *gc, uint32_t domid,
         libxl_device_model_version_to_string(b_info->device_model_version));
 }
 
+/*----- remus asynchronous checkpoint callback -----*/
+
+static void remus_checkpoint_stream_done(
+    libxl__egc *egc, libxl__stream_read_state *srs, int rc);
+
+static void libxl__remus_domain_checkpoint_callback(void *data)
+{
+    libxl__save_helper_state *shs = data;
+    libxl__domain_create_state *dcs = shs->caller_state;
+    libxl__egc *egc = shs->egc;
+    STATE_AO_GC(dcs->ao);
+
+    libxl__stream_read_start_checkpoint(egc, &dcs->srs);
+}
+
+static void remus_checkpoint_stream_done(
+    libxl__egc *egc, libxl__stream_read_state *stream, int rc)
+{
+    libxl__xc_domain_saverestore_async_callback_done(egc, &stream->shs, rc);
+}
+
 /*----- main domain creation -----*/
 
 /* We have a linear control flow; only one event callback is
@@ -939,6 +960,8 @@ static void domcreate_bootloader_done(libxl__egc *egc,
     libxl_domain_config *const d_config = dcs->guest_config;
     const int restore_fd = dcs->restore_fd;
     libxl__domain_build_state *const state = &dcs->build_state;
+    libxl__srm_restore_autogen_callbacks *const callbacks =
+        &dcs->srs.shs.callbacks.restore.a;
 
     if (rc) {
         domcreate_rebuild_done(egc, dcs, rc);
@@ -966,6 +989,7 @@ static void domcreate_bootloader_done(libxl__egc *egc,
     }
 
     /* Restore */
+    callbacks->checkpoint = libxl__remus_domain_checkpoint_callback;
 
     rc = libxl__build_pre(gc, domid, d_config, state);
     if (rc)
@@ -978,6 +1002,7 @@ static void domcreate_bootloader_done(libxl__egc *egc,
     dcs->srs.fd = restore_fd;
     dcs->srs.legacy = (dcs->restore_params.stream_version == 1);
     dcs->srs.completion_callback = domcreate_stream_done;
+    dcs->srs.checkpoint_callback = remus_checkpoint_stream_done;
 
     libxl__stream_read_start(egc, &dcs->srs);
     return;
tools/libxl/libxl_internal.h +8 -0
index 7540ab3..176c360 100644
@@ -3311,9 +3311,13 @@ struct libxl__stream_read_state {
     void (*completion_callback)(libxl__egc *egc,
                                 libxl__stream_read_state *srs,
                                 int rc);
+    void (*checkpoint_callback)(libxl__egc *egc,
+                                libxl__stream_read_state *srs,
+                                int rc);
     /* Private */
     int rc;
     bool running;
+    bool in_checkpoint;
     libxl__save_helper_state shs;
     libxl__conversion_helper_state chs;
 
@@ -3323,6 +3327,8 @@ struct libxl__stream_read_state {
     LIBXL_STAILQ_HEAD(, libxl__sr_record_buf) record_queue;
     enum {
         SRS_PHASE_NORMAL,
+        SRS_PHASE_BUFFERING,
+        SRS_PHASE_UNBUFFERING,
     } phase;
     bool recursion_guard;
 
@@ -3337,6 +3343,8 @@ struct libxl__stream_read_state {
 _hidden void libxl__stream_read_init(libxl__stream_read_state *stream);
 _hidden void libxl__stream_read_start(libxl__egc *egc,
                                       libxl__stream_read_state *stream);
+_hidden void libxl__stream_read_start_checkpoint(libxl__egc *egc,
+                                                 libxl__stream_read_state *stream);
 _hidden void libxl__stream_read_abort(libxl__egc *egc,
                                       libxl__stream_read_state *stream, int rc);
 static inline bool
tools/libxl/libxl_stream_read.c +130 -0

188 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#59 lore raw

PATCH v3 27/28 tools/libxc: Drop all XG_LIBXL_HVM_COMPAT code from libxc

In reply to Andrew Cooper

Libxl has now been fully adjusted not to need it.

---
 tools/libxc/xc_sr_common.h          |    5 --
 tools/libxc/xc_sr_restore.c         |   18 -----
 tools/libxc/xc_sr_restore_x86_hvm.c |  124 -----------------------------------
 tools/libxc/xc_sr_save_x86_hvm.c    |   36 ----------
 4 files changed, 183 deletions(-)
tools/libxc/xc_sr_common.h +0 -5
index 1f4d4e4..64f6082 100644
@@ -309,11 +309,6 @@ struct xc_sr_context
                     /* HVM context blob. */
                     void *context;
                     size_t contextsz;
-
-/* #ifdef XG_LIBXL_HVM_COMPAT */
-                    uint32_t qlen;
-                    void *qbuf;
-/* #endif */
                 } restore;
             };
         } x86_hvm;
tools/libxc/xc_sr_restore.c +0 -18
index 18ba411..bf1ee15 100644
@@ -627,9 +627,6 @@ static void cleanup(struct xc_sr_context *ctx)
         PERROR("Failed to clean up");
 }
 
-#ifdef XG_LIBXL_HVM_COMPAT
-extern int read_qemu(struct xc_sr_context *ctx);
-#endif
 /*
  * Restore a domain.
  */
@@ -656,21 +653,6 @@ static int restore(struct xc_sr_context *ctx)
                 goto err;
         }
 
-#ifdef XG_LIBXL_HVM_COMPAT
-        if ( ctx->dominfo.hvm &&
-             (rec.type == REC_TYPE_END || rec.type == REC_TYPE_CHECKPOINT) )
-        {
-            rc = read_qemu(ctx);
-            if ( rc )
-            {
-                if ( ctx->restore.buffer_all_records )
-                    goto remus_failover;
-                else
-                    goto err;
-            }
-        }
-#endif
-
         if ( ctx->restore.buffer_all_records &&
              rec.type != REC_TYPE_END &&
              rec.type != REC_TYPE_CHECKPOINT )
tools/libxc/xc_sr_restore_x86_hvm.c +0 -124

148 lines not on this page · raw message

tools/libxc/xc_sr_save_x86_hvm.c +0 -36
index f4604db..cdee774 100644
@@ -118,36 +118,6 @@ static int write_hvm_params(struct xc_sr_context *ctx)
     return rc;
 }
 
-#ifdef XG_LIBXL_HVM_COMPAT
-static int write_toolstack(struct xc_sr_context *ctx)
-{
-    xc_interface *xch = ctx->xch;
-    struct xc_sr_record rec = {
-        .type = REC_TYPE_TOOLSTACK,
-        .length = 0,
-    };
-    uint8_t *buf;
-    uint32_t len;
-    int rc;
-
-    if ( !ctx->save.callbacks || !ctx->save.callbacks->toolstack_save )
-        return 0;
-
-    if ( ctx->save.callbacks->toolstack_save(
-             ctx->domid, &buf, &len, ctx->save.callbacks->data) < 0 )
-    {
-        PERROR("Error calling toolstack_save");
-        return -1;
-    }
-
-    rc = write_split_record(ctx, &rec, buf, len);
-    if ( rc < 0 )
-        PERROR("Error writing TOOLSTACK record");
-    free(buf);
-    return rc;
-}
-#endif
-
 static xen_pfn_t x86_hvm_pfn_to_gfn(const struct xc_sr_context *ctx,
                                     xen_pfn_t pfn)
 {
@@ -199,12 +169,6 @@ static int x86_hvm_end_of_checkpoint(struct xc_sr_context *ctx)
     if ( rc )
         return rc;
 
-#ifdef XG_LIBXL_HVM_COMPAT
-    rc = write_toolstack(ctx);
-    if ( rc )
-        return rc;
-#endif
-
     /* Write the HVM_CONTEXT record. */
     rc = write_hvm_context(ctx);
     if ( rc )
Signature · 1 line
1.7.10.4
#60 lore raw

PATCH v3 28/28 tools/libxl: Drop all knowledge of toolstack callbacks

In reply to Andrew Cooper

Libxl has now been fully adjusted not to need them.

---
 tools/libxl/libxl_dom.c            |    1 -
 tools/libxl/libxl_internal.h       |    2 --
 tools/libxl/libxl_save_callout.c   |   39 +-----------------------------------
 tools/libxl/libxl_save_helper.c    |   29 ---------------------------
 tools/libxl/libxl_save_msgs_gen.pl |    7 ++-----
 5 files changed, 3 insertions(+), 75 deletions(-)
tools/libxl/libxl_dom.c +0 -1
index 98eb824..cbbb6ba 100644
@@ -2116,7 +2116,6 @@ void libxl__domain_suspend(libxl__egc *egc, libxl__domain_suspend_state *dss)
         callbacks->suspend = libxl__domain_suspend_callback;
 
     callbacks->switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
-    dss->sws.shs.callbacks.save.toolstack_save = libxl__toolstack_save;
 
     dss->sws.ao  = dss->ao;
     dss->sws.dss = dss;
tools/libxl/libxl_internal.h +0 -2
index 176c360..5cacbd4 100644
@@ -2699,8 +2699,6 @@ _hidden void libxl__datacopier_prefixdata(libxl__egc*, libxl__datacopier_state*,
 
 typedef struct libxl__srm_save_callbacks {
     libxl__srm_save_autogen_callbacks a;
-    int (*toolstack_save)(uint32_t domid, uint8_t **buf,
-                          uint32_t *len, void *data);
 } libxl__srm_save_callbacks;
 
 typedef struct libxl__srm_restore_callbacks {
tools/libxl/libxl_save_callout.c +1 -38
index b8feb9f..03d1278 100644
@@ -80,41 +80,12 @@ void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_suspend_state *dss,
                            libxl__save_helper_state *shs)
 {
     STATE_AO_GC(dss->ao);
-    int r, rc, toolstack_data_fd = -1;
-    uint32_t toolstack_data_len = 0;
-
-    /* Resources we need to free */
-    uint8_t *toolstack_data_buf = 0;
 
     unsigned cbflags =
         libxl__srm_callout_enumcallbacks_save(&shs->callbacks.save.a);
 
-    if (shs->callbacks.save.toolstack_save) {
-        r = shs->callbacks.save.toolstack_save
-            (dss->domid, &toolstack_data_buf, &toolstack_data_len, dss);
-        if (r) { rc = ERROR_FAIL; goto out; }
-
-        shs->toolstack_data_file = tmpfile();
-        if (!shs->toolstack_data_file) {
-            LOGE(ERROR, "cannot create toolstack data tmpfile");
-            rc = ERROR_FAIL;
-            goto out;
-        }
-        toolstack_data_fd = fileno(shs->toolstack_data_file);
-
-        r = libxl_write_exactly(CTX, toolstack_data_fd,
-                                toolstack_data_buf, toolstack_data_len,
-                                "toolstack data tmpfile", 0);
-        if (r) { rc = ERROR_FAIL; goto out; }
-
-        /* file position must be reset before passing to libxl-save-helper. */
-        r = lseek(toolstack_data_fd, 0, SEEK_SET);
-        if (r) { rc = ERROR_FAIL; goto out; }
-    }
-
     const unsigned long argnums[] = {
         dss->domid, 0, 0, dss->xcflags, dss->hvm,
-        toolstack_data_fd, toolstack_data_len,
         cbflags,
     };
 
@@ -125,18 +96,10 @@ void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_suspend_state *dss,
     shs->caller_state = dss;
     shs->need_results = 0;
 
-    free(toolstack_data_buf);
-
     run_helper(egc, shs, "--save-domain", dss->fd,
-               &toolstack_data_fd, 1,
+               NULL, 0,
                argnums, ARRAY_SIZE(argnums));
     return;
-
- out:
-    free(toolstack_data_buf);
-    if (shs->toolstack_data_file) fclose(shs->toolstack_data_file);
-
-    libxl__xc_domain_save_done(egc, dss, rc, 0, 0);
 }
 
 
tools/libxl/libxl_save_helper.c +0 -29
index f196786..1622bb7 100644
@@ -213,32 +213,8 @@ int helper_getreply(void *user)
 
 /*----- other callbacks -----*/
 
-static int toolstack_save_fd;
-static uint32_t toolstack_save_len;
 static struct save_callbacks helper_save_callbacks;
 
-static int toolstack_save_cb(uint32_t domid, uint8_t **buf,
-                             uint32_t *len, void *data)
-{
-    int r;
-
-    assert(toolstack_save_fd > 0);
-
-    /* This is a hack for remus */
-    if (helper_save_callbacks.checkpoint) {
-        r = lseek(toolstack_save_fd, 0, SEEK_SET);
-        if (r) fail(errno,"rewind toolstack data tmpfile");
-    }
-
-    *buf = xmalloc(toolstack_save_len);
-    r = read_exactly(toolstack_save_fd, *buf, toolstack_save_len);
-    if (r<0) fail(errno,"read toolstack data");
-    if (r==0) fail(0,"read toolstack data eof");
-
-    *len = toolstack_save_len;
-    return 0;
-}
-
 static void startup(const char *op) {
     xtl_log(&logger,XTL_DEBUG,0,program,"starting %s",op);
 
@@ -273,14 +249,9 @@ int main(int argc, char **argv)
         uint32_t max_factor =      strtoul(NEXTARG,0,10);
         uint32_t flags =           strtoul(NEXTARG,0,10);
         int hvm =                  atoi(NEXTARG);
-        toolstack_save_fd  =       atoi(NEXTARG);
-        toolstack_save_len =       strtoul(NEXTARG,0,10);
         unsigned cbflags =         strtoul(NEXTARG,0,10);
         assert(!*++argv);
 
-        if (toolstack_save_fd >= 0)
-            helper_save_callbacks.toolstack_save = toolstack_save_cb;
-
         helper_setcallbacks_save(&helper_save_callbacks, cbflags);
 
         startup("save");
tools/libxl/libxl_save_msgs_gen.pl +2 -5
index 825d5cc..d6d2967 100755
@@ -28,12 +28,9 @@ our @msgs = (
     [  5, 'srcxA',  "checkpoint", [] ],
     [  6, 'scxA',   "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',
+    [  7, 'r',      "restore_results",       ['unsigned long', 'store_mfn',
                                               'unsigned long', 'console_mfn'] ],
-    [  9, 'srW',    "complete",              [qw(int retval
+    [  8, 'srW',    "complete",              [qw(int retval
                                                  int errnoval)] ],
 );
 
Signature · 1 line
1.7.10.4
Acked-by on v3 7/28
#8 lore raw

Re: [PATCH v3 07/28] tools/libxl: Extra management APIs for the save helper

In reply to Andrew Cooper
Quoted 6 lines · Andrew Cooper

With migration v2, there are several moving parts needing to be juggled at once. This requires the error handling logic to be able to query the state of each moving part, possibly before they have been started, and be able to cancel them.

Acked-by on v3 8/28
#11 lore raw

Re: [PATCH v3 08/28] tools/libxl: Add save_helper_state pointers to libxl__xc_domain_{save, restore}()

In reply to Andrew Cooper
Quoted 11 lines · Andrew Cooper

Currently, libxl__xc_domain_{save,restore}() have specific knowledge of where the libxl__save_helper_state lives inside a libxl__domain_{create,save}_state object.

In later changes, the logical ownership of the libxl__save_helper_state will change and will no longer be d{c,s}s->shs.

No functional change.

#21 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Andrew Cooper

tools/libxl/libxl_stream_read.c line 149

Quoted 7 lines · Andrew Cooper
tools/libxl/libxl_stream_read.c new file +7 -0
+void libxl__stream_read_start(libxl__egc *egc,
+                              libxl__stream_read_state *stream)
+{
+    libxl__datacopier_state *dc = &stream->dc;
+    int rc = 0;
+
+    stream->running = true;

Did you drop the assert prior to this on purpose?

tools/libxl/libxl_stream_read.c line 191

Quoted 11 lines
tools/libxl/libxl_stream_read.c new file +11 -0
+
+static void stream_header_done(libxl__egc *egc,
+                               libxl__datacopier_state *dc,
+                               int rc, int onwrite, int errnoval)
+{
+    libxl__stream_read_state *stream = CONTAINER_OF(dc, *stream, dc);
+    libxl__sr_hdr *hdr = &stream->hdr;
+    STATE_AO_GC(dc->ao);
+
+    if (rc || onwrite || errnoval) {
+        rc = ERROR_FAIL;

Sorry for not noticing this before but if we come here because of rc then this clobbers the existing value, which I think is undesirable.

So I think the "if (rc) goto err" should be pulled out of this check. (the one line form is acceptable in this case).

This no doubt applies to most of these functions.

Quoted 4 lines
tools/libxl/libxl_stream_read.c new file +4 -0
+static void stream_continue(libxl__egc *egc,
+                            libxl__stream_read_state *stream)
+{
+    STATE_AO_GC(stream->ao);

tools/libxl/libxl_stream_read.c

Quoted 10 lines
tools/libxl/libxl_stream_read.c new file +10 -0
+
+    /*
+     * Must not mutually recurse with process_record().
+     *
+     * For records whose processing function is synchronous
+     * (e.g. TOOLSTACK), process_record() does not start another async
+     * operation, and a further operation should be started.
+     *
+     * A naive solution, which would function in general, would be for
+     * process_record() to call stream_continue().

Wouldn't the more obvious naive thing to do be to call setup_read_record? That's also potentially recursing I think since the chain of callbacks may also end in a stream_continue.

tools/libxl/libxl_stream_read.c line 247

Quoted 6 lines

However, this

tools/libxl/libxl_stream_read.c new file +5 -0
+     * would allow the content of the stream to cause mutual
+     * recursion, and possibly for us to fall off our stack.
+     *
+     * Instead, process_record() indicates with its return value
+     * whether it a further operation needs to start, and the

"whether it"?

Ian.

Acked-by on v3 26/28
#56 lore raw

Re: [PATCH v3 26/28] tools/libxl: Handle checkpoint records in a libxl migration v2 stream

In reply to Andrew Cooper
Quoted 7 lines · Andrew Cooper

This is the final bit of untangling for Remus.

When libxc issues a checkpoint callback, start reading and buffering all libxl records from the stream. Once a CHECKPOINT_END record is encountered, start processing all records.

#22 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Ian Campbell
Quoted 10 lines · Ian Campbell

tools/libxl/libxl_stream_read.c line 149

Quoted 7 lines · Andrew Cooper
tools/libxl/libxl_stream_read.c new file +7 -0
+void libxl__stream_read_start(libxl__egc *egc,
+                              libxl__stream_read_state *stream)
+{
+    libxl__datacopier_state *dc = &stream->dc;
+    int rc = 0;
+
+    stream->running = true;

Did you drop the assert prior to this on purpose?

I think it got lost while splitting the _init() out. I shall re-introduce.

Quoted 15 lines

tools/libxl/libxl_stream_read.c line 191

Quoted 12 lines
tools/libxl/libxl_stream_read.c new file +11 -0
+
+static void stream_header_done(libxl__egc *egc,
+                               libxl__datacopier_state *dc,
+                               int rc, int onwrite, int errnoval)
+{
+    libxl__stream_read_state *stream = CONTAINER_OF(dc, *stream, dc);
+    libxl__sr_hdr *hdr = &stream->hdr;
+    STATE_AO_GC(dc->ao);
+
+    if (rc || onwrite || errnoval) {
+        rc = ERROR_FAIL;

Sorry for not noticing this before but if we come here because of rc then this clobbers the existing value, which I think is undesirable.

Quoted 4 lines

So I think the "if (rc) goto err" should be pulled out of this check. (the one line form is acceptable in this case).

This no doubt applies to most of these functions.

Urgh yes - I fixed this in some places (mostly in the write side infrastructure) but forgot to check for other occurrences.

Quoted 17 lines
Quoted 5 lines
tools/libxl/libxl_stream_read.c new file +4 -0
+static void stream_continue(libxl__egc *egc,
+                            libxl__stream_read_state *stream)
+{
+    STATE_AO_GC(stream->ao);

tools/libxl/libxl_stream_read.c

Quoted 10 lines
tools/libxl/libxl_stream_read.c new file +10 -0
+
+    /*
+     * Must not mutually recurse with process_record().
+     *
+     * For records whose processing function is synchronous
+     * (e.g. TOOLSTACK), process_record() does not start another async
+     * operation, and a further operation should be started.
+     *
+     * A naive solution, which would function in general, would be for
+     * process_record() to call stream_continue().

Wouldn't the more obvious naive thing to do be to call setup_read_record?

That would also be a naive thing to do. During a remus checkpoint, by the time we are processing TOOLSTACK records, the next thing in the pipe is a libxc record.

This is why everything must come back around to stream_continue() rather than attempting to be clever.

Quoted 2 lines

That's also potentially recursing I think since the chain of callbacks may also end in a stream_continue.

I am fairly sure the reentrancy guarantees prevent that.

Quoted 8 lines

tools/libxl/libxl_stream_read.c line 247

Quoted 7 lines

However, this

tools/libxl/libxl_stream_read.c new file +5 -0
+     * would allow the content of the stream to cause mutual
+     * recursion, and possibly for us to fall off our stack.
+     *
+     * Instead, process_record() indicates with its return value
+     * whether it a further operation needs to start, and the

"whether it"?

s/ it//

~Andrew

#24 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Ian Campbell

Ian Campbell writes ("Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream"):

Quoted 11 lines · Andrew Cooper

tools/libxl/libxl_stream_read.c line 149

Quoted 8 lines
tools/libxl/libxl_stream_read.c new file +7 -0
+void libxl__stream_read_start(libxl__egc *egc,
+                              libxl__stream_read_state *stream)
+{
+    libxl__datacopier_state *dc = &stream->dc;
+    int rc = 0;
+
+    stream->running = true;

Did you drop the assert prior to this on purpose?

This was at my provocation, I think.

Ian.

#23 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Andrew Cooper

Andrew Cooper writes ("Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream"):

Quoted 5 lines · Ian Campbell
Quoted 2 lines · Andrew Cooper

Did you drop the assert prior to this on purpose?

I think it got lost while splitting the _init() out. I shall re-introduce.

Please don't. Or, if you do, please put in some comments in libxl_internal.h about the public states of a libxl__stream_read_state.

Earlier i wrote:

I don't mind this at all but I think if you do this you should:
* provide an _init method
* document that _init must be called before start

and

As far as I can tell, from the outside, this machinery has the usual Undefined/Idle/Active states. [...]

It is usual for functions of this kind to take an Undefined struct and make it Active.

See:
- the comment in libxl_internal.h about `Event generation functions'
- the following examples
libxl__spawn_spawn (accepts Undefined, this is documented)
libxl__bootloader_run (accepts Undefined, not documented)
libxl__datacopier_start (accepts Undefined, not documented)
libxl__openpty (accepts Undefined; no init method)

Thanks,
Ian.

#25 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Andrew Cooper

Andrew Cooper writes ("[PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream"):
...

Quoted 4 lines

+ * PHASE_NORMAL:

+ *   This phase is used for regular migration or resume from file.
+ *   Records are read one at time and immediately processed.  (The
+ *   record queue will not contain more than a single record.)

I see that you added better comments about the record state later in the series, thanks.

I'm not entirely sure that it was right for that to be added later, but I'm not going to quibble about its location in the series. I am however going to comment on the content:

* Internal states:
* running in_checkpoint phase

 * Undefined          -        -              -
 * Idle               false    false          -
 * Active             true     false          normal
 * Checkpoint(buf)    true     true           buffering
 * Checkpoint(unbuf)  true     true           unbuffering
 * Active             true     false          normal
 * Finished           false    false          -

The `Active' line here appears twice. Surely some mistake.

What is the difference between Finished and Idle ? I think none ? So Finished doesn't belong here.

Also you should probably explictly say that Checkpoint is a variant of Active, from the outside. (You don't explicitly list the outside states, but as I say I think they are the usual Undefined / Idle / Active.)

The use of -' for undefined value' is not proper, I think. You probably cribbed this from the -' in one cell in the spawn implementation' comment in libxl_exec.c (near line 242). But that -' means no such object is allocated but the pointer has an undefined value', which is rather special.

Maybe you want this instead:

* Internal states:

 *             phase        running  in_checkpoint
 * Undefined   undef        undef    undef
 * Idle        undef        false    false
 * Active      NORMAL       true     false
 * Active      BUFFERING    true     true
 * Active      UNBUFFERING  true     true

I also asked for you to write down which state variables may take which values in which state. running and in_checkpoint are only part of this.

For example, there is also incoming_record, and record_queue (which may be undefined, empty, one entry, >=2 entries), and the datacopier.

Is the datacopier always active ? I think it is except
- when we are processing one of our own callbacks, or
- in BUFFERING/UNBUFFERING, when process_record is setting up its own callbacks

Maybe you want to say in a comment that there is always _either_ a datacopier callback to come, _or_ a callback set up by process_record.

Quoted 3 lines
tools/libxl/libxl_stream_read.c new file +3 -0
+static void stream_continue(libxl__egc *egc,
+                            libxl__stream_read_state *stream)
+{

...

Quoted 7 lines
tools/libxl/libxl_stream_read.c new file +7 -0
+    switch (stream->phase) {
+    case SRS_PHASE_NORMAL:
+        /*
+         * Normal phase (regular migration or restore from file):
+         *
+         * logically:
+         *   do { read_record(); process_record(); } while ( not END );

tools/libxl/libxl_stream_read.c line 270

Quoted 10 lines
tools/libxl/libxl_stream_read.c new file +10 -0
+         *
+         * Alternate between reading a record from the stream, and
+         * processing the record.  There should never be two records
+         * in the queue.
+         */
+        if (LIBXL_STAILQ_EMPTY(&stream->record_queue))
+            setup_read_record(egc, stream);
+        else {
+            if (process_record(egc, stream))
+                setup_read_record(egc, stream);

Weren't you going to add an assert here, that the queue is empty ?

Review

Quoted 2 lines · Last time I
(quoted diff) +2 -0
+    libxl__sr_record_buf *incoming_record;
+    LIBXL_STAILQ_HEAD(, libxl__sr_record_buf) record_queue;

This comes from malloc, not from the gc. That needs a comment. (Is the same true of incoming_record ? I think it is.)

I don't see that comment. You have moved incoming_record away record_queue so now it needs two comments.

Thanks,
Ian.

#32 lore raw

Re: [PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream

In reply to Andrew Cooper

Andrew Cooper writes ("[PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream"):

Quoted 7 lines

Provide a thin wrapper around exec()ing the python conversion utility, and a stub implementation for cases where conversion is not wanted (i.e. not x86).

One complication is that the caller of this interface needs to assume ownership of the output fd, to prevent it being closed while still in use in a datacopier.

...

Thanks.

I have just very minor comments:

Quoted 3 lines
tools/libxl/libxl_convert_callout.c new file +3 -0
+int libxl__convert_legacy_stream(libxl__egc *egc,
+                                 libxl__conversion_helper_state *chs)
+{

...

tools/libxl/libxl_convert_callout.c line 77

Quoted 6 lines
tools/libxl/libxl_convert_callout.c new file +6 -0
+            "--width",
+#ifdef __i386__
+            "32",
+#else
+            "64",
+#endif

Firstly, and sorry to not spot this the last time: can we get rid of this ifdeffery ?

I'm afraid I don't understand why this script needs to be told the toolstack build bit width. (If indeed the toolstack build bit width is the right thing, can't the script tell what bitness it is running on, some other way?)

If we do need to pass in the bitness then there must be some other way to find it other than an adhoc #ifdef.

I appreciate that this seems very pernickety for compatibility code which will only be executed on i386 or amd64, but #ifdefs like this make the code hard to read IMO.

And some style complaints:

Quoted 1 line

+struct libxl__conversion_helper_state {

...

tools/libxl/libxl_internal.h _hidden void libxl__remus_devices_commit(libxl__egc *egc, · line 2932

Quoted 2 lines
tools/libxl/libxl_internal.h +2 -0
+    void (*completion_callback)(
+        libxl__egc *egc, libxl__conversion_helper_state *chs, int rc);

Please format this like this:

Quoted 1 line

+_hidden void libxl__conversion_helper_init(libxl__conversion_helper_state\

*chs);

Review

Quoted 2 lines
(quoted diff) +2 -0
+_hidden int libxl__convert_legacy_stream(libxl__egc *egc,
+                                         libxl__conversion_helper_state *\

chs);

Review

Quoted 2 lines
(quoted diff) +2 -0
+_hidden void libxl__conversion_helper_abort(libxl__egc *egc,
+                                            libxl__conversion_helper_state\

*chs,

Quoted 1 line

+ int rc);

Please rewrap these like this:

+_hidden void libxl__conversion_helper_init
+ (libxl__conversion_helper_state *chs);
+_hidden int libxl__convert_legacy_stream(libxl__egc *egc,
+ libxl__conversion_helper_state *chs);
+_hidden void libxl__conversion_helper_abort(libxl__egc *egc,
+ libxl__conversion_helper_state *chs, int rc);

or something similar.

Thanks,
Ian.

#39 lore raw

Re: [PATCH v3 19/28] tools/libxl: Convert a legacy stream if needed

In reply to Andrew Cooper

Andrew Cooper writes ("[PATCH v3 19/28] tools/libxl: Convert a legacy stream if needed"):

Quoted 6 lines

For backwards compatibility, a legacy stream needs converting before it can be read by the v2 stream logic.

This causes the v2 stream logic to need to juggle two parallel tasks. check_all_finished() is introduced for the purpose of joining the tasks in both success and error cases.

...

tools/libxl/libxl_stream_read.c static void stream_done(libxl__egc *egc, · line 560

Quoted 3 lines
tools/libxl/libxl_stream_read.c +3 -0
+    /* If we started a conversion helper, we took ownership of its carefd. */
+    if (stream->chs.v2_carefd)
+        libxl__carefd_close(stream->chs.v2_carefd);

This would be more obviously correct (or at least more obviously never leak a carefd) if you set v2_carefd to NULL here, and asserted its NULLness at the end of check_all_finished just before making the callback.

(I looked to see if you initialised it to NULL as well; you don't, but the existing code is not consistent about whether it works on systems where all-bits-0 is not NULL, and I think it unlikely that Xen would ever be made to work on such a system.)

tools/libxl/libxl_stream_read.c static void stream_done(libxl__egc *egc, · line 596

Quoted 4 lines
tools/libxl/libxl_stream_read.c +4 -0
+    /* Don't fire the callback until all our parallel tasks have stopped. */
+    if (!libxl__stream_read_inuse(stream) &&
+        !libxl__conversion_helper_inuse(&stream->chs))
+        stream->completion_callback(egc, stream, stream->rc);

I think this would be clearer if the sense of the if was reversed, so:

+ /* Don't fire the callback until all our parallel tasks have stopped. */
+ if (libxl__stream_read_inuse(stream) ||
+ libxl__conversion_helper_inuse(&stream->chs))
+ return;
+
+ /* At last! */
+ stream->completion_callback(egc, stream, stream->rc);

But this is a matter of taste, so feel free to leave it as it is.

Ian.

#26 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Ian Jackson
Quoted 49 lines · Ian Jackson

Andrew Cooper writes ("[PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream"):
...

Quoted 4 lines

+ * PHASE_NORMAL:

+ *   This phase is used for regular migration or resume from file.
+ *   Records are read one at time and immediately processed.  (The
+ *   record queue will not contain more than a single record.)

I see that you added better comments about the record state later in the series, thanks.

I'm not entirely sure that it was right for that to be added later, but I'm not going to quibble about its location in the series. I am however going to comment on the content:

* Internal states:
* running in_checkpoint phase

 * Undefined          -        -              -
 * Idle               false    false          -
 * Active             true     false          normal
 * Checkpoint(buf)    true     true           buffering
 * Checkpoint(unbuf)  true     true           unbuffering
 * Active             true     false          normal
 * Finished           false    false          -

The `Active' line here appears twice. Surely some mistake.

What is the difference between Finished and Idle ? I think none ? So Finished doesn't belong here.

Also you should probably explictly say that Checkpoint is a variant of Active, from the outside. (You don't explicitly list the outside states, but as I say I think they are the usual Undefined / Idle / Active.)

The use of -' for undefined value' is not proper, I think. You probably cribbed this from the -' in one cell in the spawn implementation' comment in libxl_exec.c (near line 242). But that -' means no such object is allocated but the pointer has an undefined value', which is rather special.

Maybe you want this instead:

* Internal states:

 *             phase        running  in_checkpoint
 * Undefined   undef        undef    undef
 * Idle        undef        false    false
 * Active      NORMAL       true     false
 * Active      BUFFERING    true     true
 * Active      UNBUFFERING  true     true
Quoted 6 lines

I also asked for you to write down which state variables may take which values in which state. running and in_checkpoint are only part of this.

For example, there is also incoming_record, and record_queue (which may be undefined, empty, one entry, >=2 entries), and the datacopier.

These cannot be expressed in the above terms.

incoming_record (as already noted in libxl_internal.h) is only used while reading a record, which happens in both Active/NORMAL and Active/BUFFERING

record_queue is strictly 0 or 1 entries during NORMAL, grows from 0 to

Quoted 1 line

=1 during BUFFERING, and shrinks back to 0 during UNBUFFERING.

How would you go about expressing this without a state transition diagram? (I really don't think an ascii art state transition diagram will help make this any clearer)

Quoted 5 lines

Is the datacopier always active ? I think it is except
- when we are processing one of our own callbacks, or
- in BUFFERING/UNBUFFERING, when process_record is setting up its own callbacks

The datacopier is only active while reading a record from the stream, but that is only (logically) half of the work to do. It will never be active when processing records.

There is a second datacopier for qemu use which is only active while processing an EMULATOR record.

Quoted 3 lines

Maybe you want to say in a comment that there is always _either_ a datacopier callback to come, _or_ a callback set up by process_record.

ok.

Quoted 28 lines
Quoted 5 lines
tools/libxl/libxl_stream_read.c new file +3 -0
+static void stream_continue(libxl__egc *egc,
+                            libxl__stream_read_state *stream)
+{

...

Quoted 7 lines
tools/libxl/libxl_stream_read.c new file +7 -0
+    switch (stream->phase) {
+    case SRS_PHASE_NORMAL:
+        /*
+         * Normal phase (regular migration or restore from file):
+         *
+         * logically:
+         *   do { read_record(); process_record(); } while ( not END );

tools/libxl/libxl_stream_read.c line 270

Quoted 10 lines
tools/libxl/libxl_stream_read.c new file +10 -0
+         *
+         * Alternate between reading a record from the stream, and
+         * processing the record.  There should never be two records
+         * in the queue.
+         */
+        if (LIBXL_STAILQ_EMPTY(&stream->record_queue))
+            setup_read_record(egc, stream);
+        else {
+            if (process_record(egc, stream))
+                setup_read_record(egc, stream);

Weren't you going to add an assert here, that the queue is empty ?

Last time I wrote:

Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    libxl__sr_record_buf *incoming_record;
+    LIBXL_STAILQ_HEAD(, libxl__sr_record_buf) record_queue;

This comes from malloc, not from the gc. That needs a comment. (Is the same true of incoming_record ? I think it is.)

I don't see that comment. You have moved incoming_record away record_queue so now it needs two comments.

It is in the paragraph below PHASE_NORMAL, which you have snipped.

~Andrew

#9 lore raw

Re: [PATCH v3 07/28] tools/libxl: Extra management APIs for the save helper

In reply to Andrew Cooper

Andrew Cooper writes ("[PATCH v3 07/28] tools/libxl: Extra management APIs for the save helper"):

Quoted 4 lines

With migration v2, there are several moving parts needing to be juggled at once. This requires the error handling logic to be able to query the state of each moving part, possibly before they have been started, and be able to cancel them.

I have no objection to the introduction of libxl__save_helper_init and _inuse.

But:

Contrary to usual practice, the two entrypoints libxl__xc_domain_restore and _save require _init to be called first.

This needs to be left the way it was, or documented.

Thanks,
Ian.

Acked-by on v3 20/28
#43 lore raw

Re: [PATCH v3 20/28] tools/libxc+libxl+xl: Restore v2 streams

In reply to Andrew Cooper

Andrew Cooper writes ("[PATCH v3 20/28] tools/libxc+libxl+xl: Restore v2 streams"):

Quoted 16 lines

This is a complicated set of changes which must be done together for bisectability.

* libxl-save-helper is updated to unconditionally use libxc migration v2.
* libxl compatibility workarounds in libxc are disabled for restore operations.
* libxl__stream_read_start() is logically spliced into the event location where libxl__xc_domain_restore() used to reside.
* Ownership of the save_helper_state moves to stream_read_state.

The parameters 'hvm', 'pae', and 'superpages' were previously superfluous, and are completely unused in migration
v2. callbacks->toolstack_restore is handled via a migration v2 record now, rather than via a callback from libxc.

Quoted 7 lines

NB: this change breaks Remus. Further untangling needs to happen before Remus will function.

CC Ian Campbell <[email protected]>
CC Ian Jackson <[email protected]>
CC Wei Liu <[email protected]>
#28 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Andrew Cooper

Andrew Cooper writes ("[PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream"):
...

Quoted 3 lines
tools/libxl/libxl_stream_read.c new file +3 -0
+static void write_emulator_blob(libxl__egc *egc,
+                                libxl__stream_read_state *stream,
+                                libxl__sr_record_buf *rec)

...

tools/libxl/libxl_stream_read.c line 450

Quoted 8 lines
tools/libxl/libxl_stream_read.c new file +8 -0
+    libxl__carefd_begin();
+    writefd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
+    if (writefd == -1) {
+        rc = ERROR_FAIL;
+        LOGE(ERROR, "unable to open %s", path);
+        libxl__carefd_unlock();
+        goto err;
+    }

I have just spotted something else which I think both of us missed from my review of v2:

I wrote:

If [you keep using carefd for this], then please use libxl__carefd_opened. (Best would be to libxl__carefd_opened to save and restore errno and then you can call it unconditionally after the open.)

I meant `best would be to _change_ libxl__carefd_opened save and restore errno'.

tools/libxl/libxl_stream_read.c line 453

Quoted 2 lines
tools/libxl/libxl_stream_read.c new file +2 -0
+    assert(stream->emu_carefd == NULL);
+    stream->emu_carefd = libxl__carefd_opened(CTX, writefd);

And then call it _unconditionally_, _immediately after_ the open.

This means that the carefd functions bracketing open are easy to see and there is no entanglement with error-handling flow control.

Ian.

#33 lore raw

Re: [PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream

In reply to Ian Jackson
Quoted 18 lines · Ian Jackson

Andrew Cooper writes ("[PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream"):

Quoted 7 lines

Provide a thin wrapper around exec()ing the python conversion utility, and a stub implementation for cases where conversion is not wanted (i.e. not x86).

One complication is that the caller of this interface needs to assume ownership of the output fd, to prevent it being closed while still in use in a datacopier.

...

Thanks.

I have just very minor comments:

Quoted 3 lines
tools/libxl/libxl_convert_callout.c new file +3 -0
+int libxl__convert_legacy_stream(libxl__egc *egc,
+                                 libxl__conversion_helper_state *chs)
+{

...

Quoted 8 lines

tools/libxl/libxl_convert_callout.c line 77

Quoted 6 lines
tools/libxl/libxl_convert_callout.c new file +6 -0
+            "--width",
+#ifdef __i386__
+            "32",
+#else
+            "64",
+#endif

Firstly, and sorry to not spot this the last time: can we get rid of this ifdeffery ?

Not without some way of passing equivalent information.

Quoted 5 lines

I'm afraid I don't understand why this script needs to be told the toolstack build bit width. (If indeed the toolstack build bit width is the right thing, can't the script tell what bitness it is running on, some other way?)

The script needs to know the bitness of the toolstack which saved the legacy stream, not the bitness of the one which is currently running.

This is because the legacy stream has insufficient information in its head to determine this with certainty. The conversion script puts the onus on the caller to get this correct, rather than possibly mis-converting a VM without finding a hard error (which is sadly possible).

The ifdefary above is an assumption for the common case. By observation, noone outside of XenServer has tried migrating a VM from a 32bit toolstack to a 64bit, or they have and not reported a bug. Therefore, the common case is that the bitness of toolstack is the same.

If in the future someone genuinely needs to convert legacy -> v2 and 32 -> 64bit at the same time, they can use the conversion script manually to achieve this (even in a migration), which will bypass the conversion logic in libxl, as the incoming stream is already v2.

Quoted 7 lines

If we do need to pass in the bitness then there must be some other way to find it other than an adhoc #ifdef.

I appreciate that this seems very pernickety for compatibility code which will only be executed on i386 or amd64, but #ifdefs like this make the code hard to read IMO.

Would it be acceptable to format the above description into a comment?

~Andrew

#45 lore raw

Re: [PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream

In reply to Andrew Cooper

Andrew Cooper writes ("[PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream"):
...

tools/libxl/libxl_stream_write.c line 276

Quoted 9 lines
tools/libxl/libxl_stream_write.c new file +9 -0
+    libxl__carefd_begin();
+    int readfd = open(filename, O_RDONLY);
+    if (readfd == -1) {
+        rc = ERROR_FAIL;
+        LOGE(ERROR, "unable to open %s", filename);
+        libxl__carefd_unlock();
+        goto err;
+    }
+    stream->emu_carefd = libxl__carefd_opened(CTX, readfd);

A similar comment about libxl__carefd_opened applies here.

Ian.

#29 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Ian Jackson
Quoted 27 lines · Ian Jackson

Andrew Cooper writes ("[PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream"):
...

Quoted 3 lines
tools/libxl/libxl_stream_read.c new file +3 -0
+static void write_emulator_blob(libxl__egc *egc,
+                                libxl__stream_read_state *stream,
+                                libxl__sr_record_buf *rec)

...

tools/libxl/libxl_stream_read.c line 450

Quoted 8 lines
tools/libxl/libxl_stream_read.c new file +8 -0
+    libxl__carefd_begin();
+    writefd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
+    if (writefd == -1) {
+        rc = ERROR_FAIL;
+        LOGE(ERROR, "unable to open %s", path);
+        libxl__carefd_unlock();
+        goto err;
+    }

I have just spotted something else which I think both of us missed from my review of v2:

I wrote:

If [you keep using carefd for this], then please use libxl__carefd_opened. (Best would be to libxl__carefd_opened to save and restore errno and then you can call it unconditionally after the open.)

I meant `best would be to _change_ libxl__carefd_opened save and restore errno'.

Quoted 6 lines

tools/libxl/libxl_stream_read.c line 453

Quoted 2 lines
tools/libxl/libxl_stream_read.c new file +2 -0
+    assert(stream->emu_carefd == NULL);
+    stream->emu_carefd = libxl__carefd_opened(CTX, writefd);

And then call it _unconditionally_, _immediately after_ the open.

This means that the carefd functions bracketing open are easy to see and there is no entanglement with error-handling flow control.

libxl__carefd_opened() doesn't tolerate being handed -1. It cannot be used ahead of the error check.

I could see about introducing something like libxl__carefd_open() as a carefd wrapper to open(2)

~Andrew

#40 lore raw

Re: [PATCH v3 19/28] tools/libxl: Convert a legacy stream if needed

In reply to Ian Jackson
Quoted 7 lines · Ian Jackson

Andrew Cooper writes ("[PATCH v3 19/28] tools/libxl: Convert a legacy stream if needed"):

Quoted 6 lines

For backwards compatibility, a legacy stream needs converting before it can be read by the v2 stream logic.

This causes the v2 stream logic to need to juggle two parallel tasks. check_all_finished() is introduced for the purpose of joining the tasks in both success and error cases.

Quoted 8 lines

...

tools/libxl/libxl_stream_read.c static void stream_done(libxl__egc *egc, · line 560

Quoted 3 lines
tools/libxl/libxl_stream_read.c +3 -0
+    /* If we started a conversion helper, we took ownership of its carefd. */
+    if (stream->chs.v2_carefd)
+        libxl__carefd_close(stream->chs.v2_carefd);

This would be more obviously correct (or at least more obviously never leak a carefd) if you set v2_carefd to NULL here, and asserted its NULLness at the end of check_all_finished just before making the callback.

This argument applies to all the cleanup in this function, but we already assert that stream_done() is strictly executed once.

It would seem wrong to me to check just v2_carefd here, given all the other resources in need of cleanup.

Quoted 5 lines

(I looked to see if you initialised it to NULL as well; you don't, but the existing code is not consistent about whether it works on systems where all-bits-0 is not NULL, and I think it unlikely that Xen would ever be made to work on such a system.)

Given how POSIX-dependent libxl is, I don't see this being likely either.

~Andrew

#46 lore raw

Re: [PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream

In reply to Andrew Cooper

Andrew Cooper writes ("[PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream"):
...

Quoted 6 lines
tools/libxl/libxl_stream_write.c new file +6 -0
+void libxl__stream_write_start(libxl__egc *egc,
+                               libxl__stream_write_state *stream)
+{
+    libxl__datacopier_state *dc = &stream->dc;
+    STATE_AO_GC(stream->ao);
+    struct libxl__sr_hdr hdr = { 0 };

...

Quoted 1 line

+ libxl__datacopier_prefixdata(egc, dc, &hdr, sizeof(hdr));

Sadly this pattern is not correct. I don't think this initialisation ensures that the memory in hdr is all-bits-0. So you may leak arbitrary data from the toolstack process stack into the migration or save stream.

I think you need to use FILLZERO.

Quoted 1 line

+ struct libxl__sr_rec_hdr rec = { REC_TYPE_LIBXC_CONTEXT };

...

tools/libxl/libxl_stream_write.c line 200

Quoted 2 lines
tools/libxl/libxl_stream_write.c new file +2 -0
+    setup_write(egc, stream, "libxc header",
+                &rec, NULL, libxc_header_done);

Same again.

(I haven't searched thoroughly for these.)

Quoted 1 line

+/*----- Success/error/cleanup handling. -----*/

As with read, I would prefer these to be unified into one stream_complete function.

tools/libxl/libxl_stream_write.c line 416

Quoted 4 lines
tools/libxl/libxl_stream_write.c new file +4 -0
+    /* Don't fire the callback until all our parallel tasks have stopped. */
+    if (!libxl__stream_write_inuse(stream) &&
+        !libxl__save_helper_inuse(&dss->shs))
+        stream->completion_callback(egc, stream, stream->rc);

My stylistic comment about the sense of the if applies here. But as I say it's a matter of taste.

Ian.

Acked-by on v3 22/28
#51 lore raw

Re: [PATCH v3 22/28] tools/libxc+libxl+xl: Save v2 streams

In reply to Andrew Cooper

Andrew Cooper writes ("[PATCH v3 22/28] tools/libxc+libxl+xl: Save v2 streams"):

Quoted 11 lines

This is a complicated set of changes which must be done together for bisectability.

* libxl-save-helper is updated to unconditionally use libxc migration v2.
* libxl compatibility workarounds in libxc are disabled for save operations.
* libxl__stream_write_start() is logically spliced into the event location where libxl__xc_domain_save() used to reside.
* Ownership of the helper state moves into stream_write_state.
* xl is updated to indicate that the stream is now v2

#47 lore raw

Re: [PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream

In reply to Ian Jackson
Quoted 9 lines · Ian Jackson

Andrew Cooper writes ("[PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream"):
...

Quoted 6 lines
tools/libxl/libxl_stream_write.c new file +6 -0
+void libxl__stream_write_start(libxl__egc *egc,
+                               libxl__stream_write_state *stream)
+{
+    libxl__datacopier_state *dc = &stream->dc;
+    STATE_AO_GC(stream->ao);
+    struct libxl__sr_hdr hdr = { 0 };

...

Quoted 3 lines
Quoted 1 line

+ libxl__datacopier_prefixdata(egc, dc, &hdr, sizeof(hdr));

Sadly this pattern is not correct. I don't think this initialisation ensures that the memory in hdr is all-bits-0.

It guarantees that all object have their default values, which is 0 for PoD integers. (On a POSIX system, it is only floats/doubles/_Complex which have default representations with not all bits 0)

Quoted 1 line

From the standard,

[6.7.8.21] If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

i.e. everything will get the same value it would have done had it been declared static.

Quoted 3 lines

So you may leak
arbitrary data from the toolstack process stack into the migration or save stream.

I am fairly certain that it cannot leak process stack.

Quoted 7 lines

I think you need to use FILLZERO.

Quoted 1 line

+ struct libxl__sr_rec_hdr rec = { REC_TYPE_LIBXC_CONTEXT };

...

tools/libxl/libxl_stream_write.c line 200

Quoted 2 lines
tools/libxl/libxl_stream_write.c new file +2 -0
+    setup_write(egc, stream, "libxc header",
+                &rec, NULL, libxc_header_done);
Quoted 8 lines

Same again.

(I haven't searched thoroughly for these.)

Quoted 1 line

+/*----- Success/error/cleanup handling. -----*/

As with read, I would prefer these to be unified into one stream_complete function.

They can't, because of differing function signatures from callbacks.

~Andrew

#27 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Andrew Cooper

Andrew Cooper writes ("Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream"):

Quoted 10 lines · Ian Jackson
Quoted 2 lines

For example, there is also incoming_record, and record_queue (which may be undefined, empty, one entry, >=2 entries), and the datacopier.

These cannot be expressed in the above terms.

incoming_record (as already noted in libxl_internal.h) is only used while reading a record, which happens in both Active/NORMAL and Active/BUFFERING

Quoted 6 lines

record_queue is strictly 0 or 1 entries during NORMAL, grows from 0 to

Quoted 1 line

=1 during BUFFERING, and shrinks back to 0 during UNBUFFERING.

How would you go about expressing this without a state transition diagram? (I really don't think an ascii art state transition diagram will help make this any clearer)

  *          phase     running   in_         record   incoming
  *                              checkpoint  _queue   _record
  *
  * Undefined undef       undef    undef       undef    undef
  * Idle      undef       false    false       0        0
  * Active    NORMAL      true     false       0/1      0/partial
  * Active    BUFFERING   true     true        any      0/partial
  * Active    UNBUFFERING true     true        any      0

Adjust to taste and to correspond to facts.

Quoted 11 lines
Quoted 4 lines

Is the datacopier always active ? I think it is except
- when we are processing one of our own callbacks, or
- in BUFFERING/UNBUFFERING, when process_record is setting up its own callbacks

The datacopier is only active while reading a record from the stream, but that is only (logically) half of the work to do. It will never be active when processing records.

There is a second datacopier for qemu use which is only active while processing an EMULATOR record.

Maybe this wants to be in the table, or maybe it wants a comment next to the variable name in the struct.

Quoted 4 lines
Quoted 2 lines

Maybe you want to say in a comment that there is always _either_ a datacopier callback to come, _or_ a callback set up by process_record.

ok.

I'm glad that I divined correctly that this is true :-).

Quoted 23 lines
Quoted 23 lines
Quoted 3 lines
tools/libxl/libxl_stream_read.c new file +3 -0
+static void stream_continue(libxl__egc *egc,
+                            libxl__stream_read_state *stream)
+{

...

Quoted 7 lines
tools/libxl/libxl_stream_read.c new file +7 -0
+    switch (stream->phase) {
+    case SRS_PHASE_NORMAL:
+        /*
+         * Normal phase (regular migration or restore from file):
+         *
+         * logically:
+         *   do { read_record(); process_record(); } while ( not END );

tools/libxl/libxl_stream_read.c line 270

Quoted 10 lines
tools/libxl/libxl_stream_read.c new file +10 -0
+         *
+         * Alternate between reading a record from the stream, and
+         * processing the record.  There should never be two records
+         * in the queue.
+         */
+        if (LIBXL_STAILQ_EMPTY(&stream->record_queue))
+            setup_read_record(egc, stream);
+        else {
+            if (process_record(egc, stream))
+                setup_read_record(egc, stream);

Weren't you going to add an assert here, that the queue is empty ?

...

Quoted 1 line

It is in the paragraph below PHASE_NORMAL, which you have snipped.

I have grepped the whole of `stream_continue' in the tip of v3 of your series (b8bf4572) and these are the results:

    assert(stream->recursion_guard == false);
        assert(stream->in_checkpoint);
        assert(stream->in_checkpoint);
    assert(stream->recursion_guard == true);

I meant a call to assert() which ensures that after process_record in PHASE_NORMAL, the queue is empty.

Ian.

#30 lore raw

Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream

In reply to Andrew Cooper

Andrew Cooper writes ("Re: [PATCH v3 17/28] tools/libxl: Infrastructure for reading a libxl migration v2 stream"):

Quoted 6 lines · Ian Jackson
Quoted 2 lines

This means that the carefd functions bracketing open are easy to see and there is no entanglement with error-handling flow control.

libxl__carefd_opened() doesn't tolerate being handed -1. It cannot be used ahead of the error check.

Wait, what ?

(reads)

The doc comment says:

/* Combines _record and _unlock in a single call. If fd==-1,
* still does the unlock, but returns 0. Cannot fail. */
_hidden libxl__carefd *libxl__carefd_opened(libxl_ctx *ctx, int fd);

but the implementation agrees with you.

Under the circumstances I am going to drop this request from this review and treat this as a cleanup activity.

Sorry.

Ian.

#34 lore raw

Re: [PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream

In reply to Andrew Cooper

Andrew Cooper writes ("Re: [PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream"):

Quoted 1 line · Ian Jackson

...

Quoted 7 lines
Quoted 4 lines

I'm afraid I don't understand why this script needs to be told the toolstack build bit width. (If indeed the toolstack build bit width is the right thing, can't the script tell what bitness it is running on, some other way?)

The script needs to know the bitness of the toolstack which saved the legacy stream, not the bitness of the one which is currently running.

But an ifdef tells you the bitness of the toolstack which is currently running.

Quoted 4 lines

The ifdefary above is an assumption for the common case. By observation, noone outside of XenServer has tried migrating a VM from a 32bit toolstack to a 64bit, or they have and not reported a bug. Therefore, the common case is that the bitness of toolstack is the same.

I see.

Quoted 4 lines

If in the future someone genuinely needs to convert legacy -> v2 and 32 -> 64bit at the same time, they can use the conversion script manually to achieve this (even in a migration), which will bypass the conversion logic in libxl, as the incoming stream is already v2.

How ... exciting.

Quoted 5 lines
Quoted 3 lines

I appreciate that this seems very pernickety for compatibility code which will only be executed on i386 or amd64, but #ifdefs like this make the code hard to read IMO.

Would it be acceptable to format the above description into a comment?

That would help.

But also I want rid of the #ifdef for stylistic reasons.

How about you make the --width option optional, and default it to native bitness in the conversion script ?

Ian.

#41 lore raw

Re: [PATCH v3 19/28] tools/libxl: Convert a legacy stream if needed

In reply to Andrew Cooper

Andrew Cooper writes ("Re: [PATCH v3 19/28] tools/libxl: Convert a legacy stream if needed"):

Quoted 11 lines · Ian Jackson
Quoted 4 lines

This would be more obviously correct (or at least more obviously never leak a carefd) if you set v2_carefd to NULL here, and asserted its NULLness at the end of check_all_finished just before making the callback.

This argument applies to all the cleanup in this function, but we already assert that stream_done() is strictly executed once.

It would seem wrong to me to check just v2_carefd here, given all the other resources in need of cleanup.

Fair enought.

thanks,
Ian.

#48 lore raw

Re: [PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream

In reply to Andrew Cooper

Andrew Cooper writes ("Re: [PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream"):

Quoted 7 lines · Ian Jackson
Quoted 2 lines

Sadly this pattern is not correct. I don't think this initialisation ensures that the memory in hdr is all-bits-0.

It guarantees that all object have their default values, which is 0 for PoD integers. (On a POSIX system, it is only floats/doubles/_Complex which have default representations with not all bits 0)

Yes.

Quoted 11 lines

From the standard,

[6.7.8.21] If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

i.e. everything will get the same value it would have done had it been declared static.

But it does not guarantee that the padding is initialised to all-bits-0.

Quoted 5 lines
Quoted 3 lines
Quoted 1 line

+/*----- Success/error/cleanup handling. -----*/

As with read, I would prefer these to be unified into one stream_complete function.

They can't, because of differing function signatures from callbacks.

You are right about stream_success but not AFAICT about stream_complete.

Ie, stream_success could be simply

stream_complete(egc, stream, 0)

But maybe you prefer not to, so I won't insist.

Ian.

#35 lore raw

Re: [PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream

In reply to Ian Jackson
Quoted 27 lines · Ian Jackson

Andrew Cooper writes ("Re: [PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream"):

Quoted 1 line · Ian Jackson

...

Quoted 6 lines
Quoted 4 lines

I'm afraid I don't understand why this script needs to be told the toolstack build bit width. (If indeed the toolstack build bit width is the right thing, can't the script tell what bitness it is running on, some other way?)

The script needs to know the bitness of the toolstack which saved the legacy stream, not the bitness of the one which is currently running.

But an ifdef tells you the bitness of the toolstack which is currently running.

Quoted 4 lines

The ifdefary above is an assumption for the common case. By observation, noone outside of XenServer has tried migrating a VM from a 32bit toolstack to a 64bit, or they have and not reported a bug. Therefore, the common case is that the bitness of toolstack is the same.

I see.

Quoted 4 lines

If in the future someone genuinely needs to convert legacy -> v2 and 32 -> 64bit at the same time, they can use the conversion script manually to achieve this (even in a migration), which will bypass the conversion logic in libxl, as the incoming stream is already v2.

How ... exciting.

Quoted 3 lines
Quoted 3 lines

I appreciate that this seems very pernickety for compatibility code which will only be executed on i386 or amd64, but #ifdefs like this make the code hard to read IMO.

Quoted 7 lines
Quoted 1 line

Would it be acceptable to format the above description into a comment?

That would help.

But also I want rid of the #ifdef for stylistic reasons.

How about you make the --width option optional, and default it to native bitness in the conversion script ?

I could do, but that would make the further assumption that the width of libxl is the same as the width of python, which is by no means guaranteed to be the case.

I could see about doing something based on BITS_PER_LONG which doesn't have a visible ifdef, but is still ifdefary.

~Andrew

#36 lore raw

Re: [PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream

In reply to Andrew Cooper

Andrew Cooper writes ("Re: [PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream"):

Quoted 2 lines

I could see about doing something based on BITS_PER_LONG which doesn't have a visible ifdef, but is still ifdefary.

I would much prefer that. Sorry to be awkward.

Thanks,
Ian.

#49 lore raw

Re: [PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream

In reply to Ian Jackson
Quoted 28 lines · Ian Jackson

Andrew Cooper writes ("Re: [PATCH v3 21/28] tools/libxl: Infrastructure for writing a v2 stream"):

Quoted 6 lines · Ian Jackson
Quoted 2 lines

Sadly this pattern is not correct. I don't think this initialisation ensures that the memory in hdr is all-bits-0.

It guarantees that all object have their default values, which is 0 for PoD integers. (On a POSIX system, it is only floats/doubles/_Complex which have default representations with not all bits 0)

Yes.

Quoted 11 lines

From the standard,

[6.7.8.21] If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

i.e. everything will get the same value it would have done had it been declared static.

But it does not guarantee that the padding is initialised to all-bits-0.

Quoted 4 lines
Quoted 3 lines
Quoted 1 line

+/*----- Success/error/cleanup handling. -----*/

As with read, I would prefer these to be unified into one stream_complete function.

They can't, because of differing function signatures from callbacks.

Quoted 8 lines

You are right about stream_success but not AFAICT about stream_complete.

Ie, stream_success could be simply

stream_complete(egc, stream, 0)

But maybe you prefer not to, so I won't insist.

stream_success is used as a callback, but I see your point. I had intended to refactor stream_success() in terms of stream_complete().

~Andrew

#37 lore raw

Re: [PATCH v3 18/28] tools/libxl: Infrastructure to convert a legacy stream

In reply to Andrew Cooper
Quoted 2 lines · Andrew Cooper

I could see about doing something based on BITS_PER_LONG which doesn't have a visible ifdef, but is still ifdefary.

Given that it is the reason for the width differences in the old stream using sizeof(unsigned long) wouldn't seem massively inappropriate, indeed.

I'm not sure it's especially necessary to launder that through bits_per_long though.

Ian.

#57 lore raw

Re: [PATCH v3 26/28] tools/libxl: Handle checkpoint records in a libxl migration v2 stream

In reply to Andrew Cooper

On 07/13/2015 08:01 PM, Andrew Cooper wrote:
[...]

Review static void domcreate_bootloader_done(libxl__egc *egc, · line 992

Quoted 6 lines
          domcreate_rebuild_done(egc, dcs, rc);
(quoted diff) +1 -0
@@ -966,6 +989,7 @@ static void domcreate_bootloader_done(libxl__egc *egc,
      }
 
      /* Restore */
+    callbacks->checkpoint = libxl__remus_domain_checkpoint_callback;

This should be moved after read_stream_init()

tools/libxl/libxl_create.c +1 -2
index e42de47..86f7f13 100644
@@ -989,8 +989,6 @@ static void domcreate_bootloader_done(libxl__egc *egc,
     }
 
     /* Restore */
-    callbacks->checkpoint = libxl__remus_domain_checkpoint_callback;
-
     rc = libxl__build_pre(gc, domid, d_config, state);
     if (rc)
         goto out;
@@ -1003,6 +1001,7 @@ static void domcreate_bootloader_done(libxl__egc *egc,
     dcs->srs.legacy = (dcs->restore_params.stream_version == 1);
     dcs->srs.completion_callback = domcreate_stream_done;
     dcs->srs.checkpoint_callback = remus_checkpoint_stream_done;
+    callbacks->checkpoint = libxl__remus_domain_checkpoint_callback;
 
     libxl__stream_read_start(egc, &dcs->srs);
     return;
Quoted 11 lines
(quoted diff) +1 -0
      rc = libxl__build_pre(gc, domid, d_config, state);
      if (rc)
@@ -978,6 +1002,7 @@ static void domcreate_bootloader_done(libxl__egc *egc,
      dcs->srs.fd = restore_fd;
      dcs->srs.legacy = (dcs->restore_params.stream_version == 1);
      dcs->srs.completion_callback = domcreate_stream_done;
+    dcs->srs.checkpoint_callback = remus_checkpoint_stream_done;
 
      libxl__stream_read_start(egc, &dcs->srs);
      return;

...

Signature · 2 lines
Thanks,
Yang.
#58 lore raw

Re: [PATCH v3 26/28] tools/libxl: Handle checkpoint records in a libxl migration v2 stream

Quoted 34 lines · Yang Hongyang

On 07/13/2015 08:01 PM, Andrew Cooper wrote:
[...]

tools/libxl/libxl_create.c static void domcreate_bootloader_done(libxl__egc · line 993

Quoted 7 lines
          domcreate_rebuild_done(egc, dcs, rc);
tools/libxl/libxl_create.c +1 -0
@@ -966,6 +989,7 @@ static void domcreate_bootloader_done(libxl__egc
 *egc,
      }
 
      /* Restore */
+    callbacks->checkpoint = libxl__remus_domain_checkpoint_callback;

This should be moved after read_stream_init()

tools/libxl/libxl_create.c +0 -2
index e42de47..86f7f13 100644
@@ -989,8 +989,6 @@ static void domcreate_bootloader_done(libxl__egc
 *egc,
     }
 
     /* Restore */
-    callbacks->checkpoint = libxl__remus_domain_checkpoint_callback;
-
     rc = libxl__build_pre(gc, domid, d_config, state);
     if (rc)
         goto out;
tools/libxl/libxl_create.c +1 -0
@@ -1003,6 +1001,7 @@ static void domcreate_bootloader_done(libxl__egc
 *egc,
     dcs->srs.legacy = (dcs->restore_params.stream_version == 1);
     dcs->srs.completion_callback = domcreate_stream_done;
     dcs->srs.checkpoint_callback = remus_checkpoint_stream_done;
+    callbacks->checkpoint = libxl__remus_domain_checkpoint_callback;
 
     libxl__stream_read_start(egc, &dcs->srs);
Quoted 1 line
     return;

Thanks. I have already fixed this a different way, given IanJ's review of the _init() methods.

The new init methods don't clobber the callbacks.

~Andrew