Skip to contentSkip to conversation

Migration v2 (libxc)

PATCH In review Andrew Cooper 2 participants 22 messages Apr 23, 2015 – May 5, 2015

lore
Share & tools
lore
#0 lore raw

v10 cover Migration v2 (libxc)

Presented here is v10 of the Migration v2 series (libxc subset), which is able to function when transparently inserted under an unmodified xl/libxl.

There are no major changes from v9. A docs subseries has been completed in parallel and removed from this series, and liberal quantities of spell checking has occured. A summary of changes: (M = modified, A = acked)

A tools/libxc: Implement writev_exact() in the same style as write_exact()
M libxc/progress: Extend the progress interface
A tools/libxc: Migration v2 framework
A tools/libxc: C implementation of stream format
A tools/libxc: generic common code
A tools/libxc: x86 common code
A tools/libxc: x86 PV common code
MA tools/libxc: x86 PV save code
M tools/libxc: x86 PV restore code
A tools/libxc: x86 HVM save code
MA tools/libxc: x86 HVM restore code
A tools/libxc: common save code
A tools/libxc: common restore code
A docs: libxc migration stream specification
A tools/libxc: Migration v2 compatibility for unmodified libxl

This series can be found on a 'saverestore2-v10' at
http://xenbits.xen.org/git-http/people/andrewcoop/xen.git

To experiment, simply set XG_MIGRATION_V2 in xl's environment. For migration, the easiest way is to tweak libxl-save-helper to be a shell script

  root@vitruvias:/home# cat /usr/lib/xen/bin/libxl-save-helper
  #!/bin/bash
  export XG_MIGRATION_V2=x
  exec /usr/lib/xen/bin/libxl-save-helper.bin "$@"

which will ensure that XG_MIGRATION_V2 gets set in the environment for both the source and destination of migration.

Please experiment!

~Andrew

#1 lore raw

PATCH v10 1/15 tools/libxc: Implement writev_exact() in the same style as write_exact()

This implementation of writev_exact() will cope with an iovcnt greater than IOV_MAX because glibc will actually let this work anyway, and it is very useful not to have to work about this in the caller of writev_exact(). The caller is still required to ensure that the sum of iov_len's doesn't overflow a ssize_t.

---
v8: Extra comments indicating why we loop when we do

---
 tools/libxc/xc_private.c |   85 ++++++++++++++++++++++++++++++++++++++++++++++
 tools/libxc/xc_private.h |   14 ++++++++
 2 files changed, 99 insertions(+)
tools/libxc/xc_private.c +85 -0
index 2eb44b6..83ead5e 100644
@@ -867,6 +867,91 @@ int write_exact(int fd, const void *data, size_t size)
     return 0;
 }
 
+#if defined(__MINIOS__)
+/*
+ * MiniOS's libc doesn't know about writev(). Implement it as multiple write()s.
+ */
+int writev_exact(int fd, const struct iovec *iov, int iovcnt)
+{
+    int rc, i;
+
+    for ( i = 0; i < iovcnt; ++i )
+    {
+        rc = write_exact(fd, iov[i].iov_base, iov[i].iov_len);
+        if ( rc )
+            return rc;
+    }
+
+    return 0;
+}
+#else
+int writev_exact(int fd, const struct iovec *iov, int iovcnt)
+{
+    struct iovec *local_iov = NULL;
+    int rc = 0, iov_idx = 0, saved_errno = 0;
+    ssize_t len;
+
+    while ( iov_idx < iovcnt )
+    {
+        /*
+         * Skip over iov[] entries with 0 length.
+         *
+         * This is needed to cover the case where we took a partial write and
+         * all remaining vectors are of 0 length.  In such a case, the results
+         * from writev() are indistinguishable from EOF.
+         */
+        while ( iov[iov_idx].iov_len == 0 )
+            if ( ++iov_idx == iovcnt )
+                goto out;
+
+        len = writev(fd, &iov[iov_idx], min(iovcnt - iov_idx, IOV_MAX));
+        saved_errno = errno;
+
+        if ( (len == -1) && (errno == EINTR) )
+            continue;
+        if ( len <= 0 )
+        {
+            rc = -1;
+            goto out;
+        }
+
+        /* Check iov[] to see whether we had a partial or complete write. */
+        while ( (len > 0) && (iov_idx < iovcnt) )
+        {
+            if ( len >= iov[iov_idx].iov_len )
+                len -= iov[iov_idx++].iov_len;
+            else
+            {
+                /* Partial write of iov[iov_idx]. Copy iov so we can adjust
+                 * element iov_idx and resubmit the rest. */
+                if ( !local_iov )
+                {
+                    local_iov = malloc(iovcnt * sizeof(*iov));
+                    if ( !local_iov )
+                    {
+                        saved_errno = ENOMEM;
+                        goto out;
+                    }
+
+                    iov = memcpy(local_iov, iov, iovcnt * sizeof(*iov));
+                }
+
+                local_iov[iov_idx].iov_base += len;
+                local_iov[iov_idx].iov_len  -= len;
+                break;
+            }
+        }
+    }
+
+    saved_errno = 0;
+
+ out:
+    free(local_iov);
+    errno = saved_errno;
+    return rc;
+}
+#endif
+
 int xc_ffs8(uint8_t x)
 {
     int i;
tools/libxc/xc_private.h +14 -0
index 9f55309..b45b079 100644
@@ -42,6 +42,19 @@
 #define VALGRIND_MAKE_MEM_UNDEFINED(addr, len) /* addr, len */
 #endif
 
+#if defined(__MINIOS__)
+/*
+ * MiniOS's libc doesn't know about sys/uio.h or writev().
+ * Declare enough of sys/uio.h to compile.
+ */
+struct iovec {
+    void *iov_base;
+    size_t iov_len;
+};
+#else
+#include <sys/uio.h>
+#endif
+
 #define DECLARE_HYPERCALL privcmd_hypercall_t hypercall
 #define DECLARE_DOMCTL struct xen_domctl domctl
 #define DECLARE_SYSCTL struct xen_sysctl sysctl
@@ -395,6 +408,7 @@ int xc_add_mmu_update(xc_interface *xch, struct xc_mmu *mmu,
 /* Return 0 on success; -1 on error setting errno. */
 int read_exact(int fd, void *data, size_t size); /* EOF => -1, errno=0 */
 int write_exact(int fd, const void *data, size_t size);
+int writev_exact(int fd, const struct iovec *iov, int iovcnt);
 
 int xc_ffs8(uint8_t x);
 int xc_ffs16(uint16_t x);
Signature · 1 line
1.7.10.4
#2 lore raw

PATCH v10 2/15 libxc/progress: Extend the progress interface

In reply to Andrew Cooper

Progress information is logged via a different logger to regular libxc log messages, and currently can only express a range. However, not everything which needs reporting as progress comes with a range. Extend the interface to allow reporting of a single statement.

The programming interface now looks like:
xc_set_progress_prefix()
set the prefix string to be used
xc_report_progress_single()
report a single action
xc_report_progress_step()
report $X of $Y

The new programming interface is implemented in a compatible way with the existing caller interface (by reporting a single action as "0 of 0").

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

---

v10: Expand commit message more, and add some asserts()
v8:  Expand commit message
---
 tools/libxc/xc_domain_restore.c |    3 ++-
 tools/libxc/xc_domain_save.c    |    3 ++-
 tools/libxc/xc_private.c        |   22 +++++++++++++++-------
 tools/libxc/xc_private.h        |    4 ++--
 tools/libxc/xtl_core.c          |    9 +++++----
 5 files changed, 26 insertions(+), 15 deletions(-)
tools/libxc/xc_domain_restore.c +2 -1
index 2ab9f46..e9c036f 100644
@@ -1622,7 +1622,8 @@ int xc_domain_restore(xc_interface *xch, int io_fd, uint32_t dom,
         goto out;
     }
 
-    xc_report_progress_start(xch, "Reloading memory pages", dinfo->p2m_size);
+    xc_set_progress_prefix(xch, "Reloading memory pages");
+    xc_report_progress_step(xch, 0, dinfo->p2m_size);
 
     /*
      * Now simply read each saved frame into its new machine frame.
tools/libxc/xc_domain_save.c +2 -1
index 59323b8..a71442e 100644
@@ -1131,7 +1131,8 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iter
                  "Saving memory: iter %d (last sent %u skipped %u)",
                  iter, sent_this_iter, skip_this_iter);
 
-        xc_report_progress_start(xch, reportbuf, dinfo->p2m_size);
+        xc_set_progress_prefix(xch, reportbuf);
+        xc_report_progress_step(xch, 0, dinfo->p2m_size);
 
         iter++;
         sent_this_iter = 0;
tools/libxc/xc_private.c +15 -7
index 83ead5e..2ffebd9 100644
@@ -388,18 +388,26 @@ void xc_osdep_log(xc_interface *xch, xentoollog_level level, int code, const cha
     va_end(args);
 }
 
-void xc_report_progress_start(xc_interface *xch, const char *doing,
-                              unsigned long total) {
+const char *xc_set_progress_prefix(xc_interface *xch, const char *doing)
+{
+    const char *old = xch->currently_progress_reporting;
+
     xch->currently_progress_reporting = doing;
-    xtl_progress(xch->error_handler, "xc", xch->currently_progress_reporting,
-                 0, total);
+    return old;
+}
+
+void xc_report_progress_single(xc_interface *xch, const char *doing)
+{
+    assert(doing);
+    xtl_progress(xch->error_handler, "xc", doing, 0, 0);
 }
 
 void xc_report_progress_step(xc_interface *xch,
-                             unsigned long done, unsigned long total) {
+                             unsigned long done, unsigned long total)
+{
     assert(xch->currently_progress_reporting);
-    xtl_progress(xch->error_handler, "xc", xch->currently_progress_reporting,
-                 done, total);
+    xtl_progress(xch->error_handler, "xc",
+                 xch->currently_progress_reporting, done, total);
 }
 
 int xc_get_pfn_type_batch(xc_interface *xch, uint32_t dom,
tools/libxc/xc_private.h +2 -2
index b45b079..247a408 100644
@@ -133,8 +133,8 @@ void xc_report(xc_interface *xch, xentoollog_logger *lg, xentoollog_level,
                int code, const char *fmt, ...)
      __attribute__((format(printf,5,6)));
 
-void xc_report_progress_start(xc_interface *xch, const char *doing,
-                              unsigned long total);
+const char *xc_set_progress_prefix(xc_interface *xch, const char *doing);
+void xc_report_progress_single(xc_interface *xch, const char *doing);
 void xc_report_progress_step(xc_interface *xch,
                              unsigned long done, unsigned long total);
 
tools/libxc/xtl_core.c +5 -4
index 326b97e..73add92 100644
@@ -66,13 +66,14 @@ void xtl_log(struct xentoollog_logger *logger,
 void xtl_progress(struct xentoollog_logger *logger,
                   const char *context, const char *doing_what,
                   unsigned long done, unsigned long total) {
-    int percent;
+    int percent = 0;
 
     if (!logger->progress) return;
 
-    percent = (total < LONG_MAX/100)
-        ? (done * 100) / total
-        : done / ((total + 99) / 100);
+    if ( total )
+        percent = (total < LONG_MAX/100)
+            ? (done * 100) / total
+            : done / ((total + 99) / 100);
 
     logger->progress(logger, context, doing_what, percent, done, total);
 }
Signature · 1 line
1.7.10.4
Acked-by on v10 2/15
#3 lore raw

Re: [PATCH v10 02/15] libxc/progress: Extend the progress interface

Quoted 13 lines · Andrew Cooper

Progress information is logged via a different logger to regular libxc log messages, and currently can only express a range. However, not everything which needs reporting as progress comes with a range. Extend the interface to allow reporting of a single statement.

The programming interface now looks like:
xc_set_progress_prefix()
set the prefix string to be used
xc_report_progress_single()
report a single action
xc_report_progress_step()
report $X of $Y

Quoted 4 lines

The new programming interface is implemented in a compatible way with the existing caller interface (by reporting a single action as "0 of 0").

#4 lore raw

PATCH v10 3/15 tools/libxc: Migration v2 framework

In reply to Andrew Cooper

For testing purposes, the environmental variable "XG_MIGRATION_V2" allows the two save/restore codepaths to coexist, and have a runtime switch.

---
v8: Adjust layout to compile with MiniOS

---
 tools/libxc/Makefile            |    2 ++
 tools/libxc/include/xenguest.h  |   13 +++++++++++++
 tools/libxc/xc_domain_restore.c |    8 ++++++++
 tools/libxc/xc_domain_save.c    |    6 ++++++
 tools/libxc/xc_sr_common.h      |   15 +++++++++++++++
 tools/libxc/xc_sr_restore.c     |   23 +++++++++++++++++++++++
 tools/libxc/xc_sr_save.c        |   19 +++++++++++++++++++
 7 files changed, 86 insertions(+)
 create mode 100644 tools/libxc/xc_sr_common.h
 create mode 100644 tools/libxc/xc_sr_restore.c
 create mode 100644 tools/libxc/xc_sr_save.c
tools/libxc/Makefile +2 -0
index 8b609cf..dfd3445 100644
@@ -54,6 +54,8 @@ GUEST_SRCS-y :=
 GUEST_SRCS-y += xg_private.c xc_suspend.c
 ifeq ($(CONFIG_MIGRATE),y)
 GUEST_SRCS-y += xc_domain_restore.c xc_domain_save.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
 else
 GUEST_SRCS-y += xc_nomigrate.c
tools/libxc/include/xenguest.h +13 -0
index 601b108..8e39075 100644
@@ -90,6 +90,10 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iter
                    uint32_t max_factor, uint32_t flags /* XCFLAGS_xxx */,
                    struct save_callbacks* callbacks, int hvm);
 
+/* Domain Save v2 */
+int xc_domain_save2(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
+                    uint32_t max_factor, uint32_t flags,
+                    struct save_callbacks* callbacks, int hvm);
 
 /* callbacks provided by xc_domain_restore */
 struct restore_callbacks {
@@ -126,6 +130,15 @@ int xc_domain_restore(xc_interface *xch, int io_fd, uint32_t dom,
                       unsigned int hvm, unsigned int pae, int superpages,
                       int checkpointed_stream,
                       struct restore_callbacks *callbacks);
+
+/* Domain Restore v2 */
+int xc_domain_restore2(xc_interface *xch, int io_fd, uint32_t dom,
+                       unsigned int store_evtchn, unsigned long *store_mfn,
+                       domid_t store_domid, unsigned int console_evtchn,
+                       unsigned long *console_mfn, domid_t console_domid,
+                       unsigned int hvm, unsigned int pae, int superpages,
+                       int checkpointed_stream,
+                       struct restore_callbacks *callbacks);
 /**
  * xc_domain_restore writes a file to disk that contains the device
  * model saved state.
tools/libxc/xc_domain_restore.c +8 -0
index e9c036f..b8a8ef4 100644
@@ -1502,6 +1502,14 @@ int xc_domain_restore(xc_interface *xch, int io_fd, uint32_t dom,
     struct restore_ctx *ctx = &_ctx;
     struct domain_info_context *dinfo = &ctx->dinfo;
 
+    if ( getenv("XG_MIGRATION_V2") )
+    {
+        return xc_domain_restore2(
+            xch, io_fd, dom, store_evtchn, store_mfn,
+            store_domid, console_evtchn, console_mfn, console_domid,
+            hvm,  pae,  superpages, checkpointed_stream, callbacks);
+    }
+
     DPRINTF("%s: starting restore of new domid %u", __func__, dom);
 
     pagebuf_init(&pagebuf);
tools/libxc/xc_domain_save.c +6 -0
index a71442e..301e770 100644
@@ -894,6 +894,12 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iter
 
     int completed = 0;
 
+    if ( getenv("XG_MIGRATION_V2") )
+    {
+        return xc_domain_save2(xch, io_fd, dom, max_iters,
+                               max_factor, flags, callbacks, hvm);
+    }
+
     DPRINTF("%s: starting save of domid %u", __func__, dom);
 
     if ( hvm && !callbacks->switch_qemu_logdirty )
tools/libxc/xc_sr_common.h new file +15 -0
new file mode 100644
index 0000000..ab7cb46
@@ -0,0 +1,15 @@
+#ifndef __COMMON__H
+#define __COMMON__H
+
+#include "xg_private.h"
+
+#endif
+/*
+ * Local variables:
+ * mode: C
+ * c-file-style: "BSD"
+ * c-basic-offset: 4
+ * tab-width: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
tools/libxc/xc_sr_restore.c new file +23 -0
new file mode 100644
index 0000000..cdebc69
@@ -0,0 +1,23 @@
+#include "xc_sr_common.h"
+
+int xc_domain_restore2(xc_interface *xch, int io_fd, uint32_t dom,
+                       unsigned int store_evtchn, unsigned long *store_mfn,
+                       domid_t store_domid, unsigned int console_evtchn,
+                       unsigned long *console_mfn, domid_t console_domid,
+                       unsigned int hvm, unsigned int pae, int superpages,
+                       int checkpointed_stream,
+                       struct restore_callbacks *callbacks)
+{
+    IPRINTF("In experimental %s", __func__);
+    return -1;
+}
+
+/*
+ * Local variables:
+ * mode: C
+ * c-file-style: "BSD"
+ * c-basic-offset: 4
+ * tab-width: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
tools/libxc/xc_sr_save.c new file +19 -0
new file mode 100644
index 0000000..3c34a6b
@@ -0,0 +1,19 @@
+#include "xc_sr_common.h"
+
+int xc_domain_save2(xc_interface *xch, int io_fd, uint32_t dom,
+                    uint32_t max_iters, uint32_t max_factor, uint32_t flags,
+                    struct save_callbacks* callbacks, int hvm)
+{
+    IPRINTF("In experimental %s", __func__);
+    return -1;
+}
+
+/*
+ * Local variables:
+ * mode: C
+ * c-file-style: "BSD"
+ * c-basic-offset: 4
+ * tab-width: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
Signature · 1 line
1.7.10.4
#5 lore raw

PATCH v10 4/15 tools/libxc: C implementation of stream format

In reply to Andrew Cooper

Provide the C structures matching the binary (wire) format of the new stream format. All header/record fields are naturally aligned and explicit padding fields are used to ensure the correct layout (i.e., there is no need for any non-standard structure packing pragma or attribute).

Provide some helper functions for converting types to string for diagnostic purposes.

---
 tools/libxc/Makefile              |    1 +
 tools/libxc/xc_sr_common.c        |   72 ++++++++++++++++++
 tools/libxc/xc_sr_common.h        |    8 ++
 tools/libxc/xc_sr_stream_format.h |  148 +++++++++++++++++++++++++++++++++++++
 4 files changed, 229 insertions(+)
 create mode 100644 tools/libxc/xc_sr_common.c
 create mode 100644 tools/libxc/xc_sr_stream_format.h
tools/libxc/Makefile +1 -0
index dfd3445..803db59 100644
@@ -54,6 +54,7 @@ GUEST_SRCS-y :=
 GUEST_SRCS-y += xg_private.c xc_suspend.c
 ifeq ($(CONFIG_MIGRATE),y)
 GUEST_SRCS-y += xc_domain_restore.c xc_domain_save.c
+GUEST_SRCS-y += xc_sr_common.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
tools/libxc/xc_sr_common.c new file +72 -0

72 lines not on this page · raw message

tools/libxc/xc_sr_common.h +8 -0
index ab7cb46..b65e52b 100644
@@ -3,6 +3,14 @@
 
 #include "xg_private.h"
 
+#include "xc_sr_stream_format.h"
+
+/* String representation of Domain Header types. */
+const char *dhdr_type_to_str(uint32_t type);
+
+/* String representation of Record types. */
+const char *rec_type_to_str(uint32_t type);
+
 #endif
 /*
  * Local variables:
tools/libxc/xc_sr_stream_format.h new file +148 -0

148 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#6 lore raw

PATCH v10 5/15 tools/libxc: generic common code

In reply to Andrew Cooper

Add the context structure used to keep state during the save/restore process.

Define the set of architecture or domain type specific operations with a set of callbacks (save_ops, and restore_ops).

Add common functions for writing records.

---
 tools/libxc/xc_sr_common.c |   41 ++++++
 tools/libxc/xc_sr_common.h |  309 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 350 insertions(+)
tools/libxc/xc_sr_common.c +41 -0
index 294a626..59e0c5d 100644
@@ -1,3 +1,5 @@
+#include <assert.h>
+
 #include "xc_sr_common.h"
 
 static const char *dhdr_types[] =
@@ -46,6 +48,45 @@ const char *rec_type_to_str(uint32_t type)
     return "Reserved";
 }
 
+int write_split_record(struct xc_sr_context *ctx, struct xc_sr_record *rec,
+                       void *buf, size_t sz)
+{
+    static const char zeroes[(1u << REC_ALIGN_ORDER) - 1] = { 0 };
+
+    xc_interface *xch = ctx->xch;
+    typeof(rec->length) combined_length = rec->length + sz;
+    size_t record_length = ROUNDUP(combined_length, REC_ALIGN_ORDER);
+    struct iovec parts[] =
+    {
+        { &rec->type,       sizeof(rec->type) },
+        { &combined_length, sizeof(combined_length) },
+        { rec->data,        rec->length },
+        { buf,              sz },
+        { (void*)zeroes,    record_length - combined_length },
+    };
+
+    if ( record_length > REC_LENGTH_MAX )
+    {
+        ERROR("Record (0x%08x, %s) length %#x exceeds max (%#x)", rec->type,
+              rec_type_to_str(rec->type), rec->length, REC_LENGTH_MAX);
+        return -1;
+    }
+
+    if ( rec->length )
+        assert(rec->data);
+    if ( sz )
+        assert(buf);
+
+    if ( writev_exact(ctx->fd, parts, ARRAY_SIZE(parts)) )
+        goto err;
+
+    return 0;
+
+ err:
+    PERROR("Unable to write record to stream");
+    return -1;
+}
+
 static void __attribute__((unused)) build_assertions(void)
 {
     XC_BUILD_BUG_ON(sizeof(struct xc_sr_ihdr) != 24);
tools/libxc/xc_sr_common.h +309 -0

322 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#7 lore raw

PATCH v10 6/15 tools/libxc: x86 common code

In reply to Andrew Cooper

Save/restore records common to all x86 domain types (HVM, PV).

This is only the TSC_INFO record.

---
 tools/libxc/Makefile           |    1 +
 tools/libxc/xc_sr_common_x86.c |   54 ++++++++++++++++++++++++++++++++++++++++
 tools/libxc/xc_sr_common_x86.h |   26 +++++++++++++++++++
 3 files changed, 81 insertions(+)
 create mode 100644 tools/libxc/xc_sr_common_x86.c
 create mode 100644 tools/libxc/xc_sr_common_x86.h
tools/libxc/Makefile +1 -0
index 803db59..5e12e9a 100644
@@ -55,6 +55,7 @@ GUEST_SRCS-y += xg_private.c xc_suspend.c
 ifeq ($(CONFIG_MIGRATE),y)
 GUEST_SRCS-y += xc_domain_restore.c xc_domain_save.c
 GUEST_SRCS-y += xc_sr_common.c
+GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86.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
tools/libxc/xc_sr_common_x86.c new file +54 -0

54 lines not on this page · raw message

tools/libxc/xc_sr_common_x86.h new file +26 -0
new file mode 100644
index 0000000..1d42da9
@@ -0,0 +1,26 @@
+#ifndef __COMMON_X86__H
+#define __COMMON_X86__H
+
+#include "xc_sr_common.h"
+
+/*
+ * Obtains a domains TSC information from Xen and writes a TSC_INFO record
+ * into the stream.
+ */
+int write_tsc_info(struct xc_sr_context *ctx);
+
+/*
+ * Parses a TSC_INFO record and applies the result to the domain.
+ */
+int handle_tsc_info(struct xc_sr_context *ctx, struct xc_sr_record *rec);
+
+#endif
+/*
+ * Local variables:
+ * mode: C
+ * c-file-style: "BSD"
+ * c-basic-offset: 4
+ * tab-width: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
Signature · 1 line
1.7.10.4
#8 lore raw

PATCH v10 7/15 tools/libxc: x86 PV common code

In reply to Andrew Cooper

Add functions common to save and restore of x86 PV guests. This includes functions for dealing with the P2M and M2P and the VCPU context.

---
 tools/libxc/Makefile              |    1 +
 tools/libxc/xc_sr_common_x86_pv.c |  210 +++++++++++++++++++++++++++++++++++++
 tools/libxc/xc_sr_common_x86_pv.h |  102 ++++++++++++++++++
 3 files changed, 313 insertions(+)
 create mode 100644 tools/libxc/xc_sr_common_x86_pv.c
 create mode 100644 tools/libxc/xc_sr_common_x86_pv.h
tools/libxc/Makefile +1 -0
index 5e12e9a..c2e62a8 100644
@@ -56,6 +56,7 @@ ifeq ($(CONFIG_MIGRATE),y)
 GUEST_SRCS-y += xc_domain_restore.c xc_domain_save.c
 GUEST_SRCS-y += xc_sr_common.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86.c
+GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86_pv.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
tools/libxc/xc_sr_common_x86_pv.c new file +210 -0

210 lines not on this page · raw message

tools/libxc/xc_sr_common_x86_pv.h new file +102 -0

102 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#9 lore raw

PATCH v10 8/15 tools/libxc: x86 PV save code

In reply to Andrew Cooper

Save the x86 PV specific parts of a domain. This is the X86_PV_INFO record, the P2M_FRAMES, the X86_PV_SHARED_INFO, the three different VCPU context records, and the MSR records.

The normalise_page callback used by the common code when writing the PAGE_DATA records, converts MFNs in page tables to PFNs.

---
v10: Bail with a hard error if pfn truncation would occur

---
 tools/libxc/Makefile            |    1 +
 tools/libxc/xc_sr_common.h      |    1 +
 tools/libxc/xc_sr_save_x86_pv.c |  885 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 887 insertions(+)
 create mode 100644 tools/libxc/xc_sr_save_x86_pv.c
tools/libxc/Makefile +1 -0
index c2e62a8..40ba91c 100644
@@ -57,6 +57,7 @@ GUEST_SRCS-y += xc_domain_restore.c xc_domain_save.c
 GUEST_SRCS-y += xc_sr_common.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86_pv.c
+GUEST_SRCS-$(CONFIG_X86) += xc_sr_save_x86_pv.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
tools/libxc/xc_sr_common.h +1 -0
index b71b532..2f0f00b 100644
@@ -285,6 +285,7 @@ struct xc_sr_context
     };
 };
 
+extern struct xc_sr_save_ops save_ops_x86_pv;
 
 struct xc_sr_record
 {
tools/libxc/xc_sr_save_x86_pv.c new file +885 -0

885 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#10 lore raw

PATCH v10 9/15 tools/libxc: x86 PV restore code

In reply to Andrew Cooper

Restore the x86 PV specific parts. The X86_PV_INFO, the P2M_FRAMES, SHARED_INFO, and VCPU context records.

The localise_page callback is called from the common PAGE_DATA code to convert PFNs in page tables to MFNs.

Page tables are pinned and the guest's P2M is updated when the stream is complete.

CC Ian Campbell <[email protected]>
CC Ian Jackson <[email protected]>
CC Wei Liu <[email protected]>
---
 tools/libxc/Makefile               |    1 +
 tools/libxc/xc_sr_common.h         |   10 +
 tools/libxc/xc_sr_restore.c        |  125 ++++
 tools/libxc/xc_sr_restore_x86_pv.c | 1165 ++++++++++++++++++++++++++++++++++++
 4 files changed, 1301 insertions(+)
 create mode 100644 tools/libxc/xc_sr_restore_x86_pv.c
tools/libxc/Makefile +1 -0
index 40ba91c..b301432 100644
@@ -57,6 +57,7 @@ GUEST_SRCS-y += xc_domain_restore.c xc_domain_save.c
 GUEST_SRCS-y += xc_sr_common.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86_pv.c
+GUEST_SRCS-$(CONFIG_X86) += xc_sr_restore_x86_pv.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_save_x86_pv.c
 GUEST_SRCS-y += xc_sr_restore.c
 GUEST_SRCS-y += xc_sr_save.c
tools/libxc/xc_sr_common.h +10 -0
index 2f0f00b..7d3d54f 100644
@@ -287,6 +287,8 @@ struct xc_sr_context
 
 extern struct xc_sr_save_ops save_ops_x86_pv;
 
+extern struct xc_sr_restore_ops restore_ops_x86_pv;
+
 struct xc_sr_record
 {
     uint32_t type;
@@ -321,6 +323,14 @@ static inline int write_record(struct xc_sr_context *ctx,
     return write_split_record(ctx, rec, NULL, 0);
 }
 
+/*
+ * This would ideally be private in restore.c, but is needed by
+ * x86_pv_localise_page() if we receive pagetables frames ahead of the
+ * contents of the frames they point at.
+ */
+int populate_pfns(struct xc_sr_context *ctx, unsigned count,
+                  const xen_pfn_t *original_pfns, const uint32_t *types);
+
 #endif
 /*
  * Local variables:
tools/libxc/xc_sr_restore.c +125 -0

130 lines not on this page · raw message

tools/libxc/xc_sr_restore_x86_pv.c new file +1165 -0

1,165 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#11 lore raw

Re: [PATCH v10 09/15] tools/libxc: x86 PV restore code

Quoted 2 lines · Andrew Cooper

+ * Set a pfn as populated, expanding the tracking structures if needed. To
+ * avoid realloc()ing too excessivly, the size increased to the nearest power

"excessively".

Otherwise: Acked-by: Ian Campbell <[email protected]>

#12 lore raw

PATCH v10 10/15 tools/libxc: x86 HVM save code

In reply to Andrew Cooper

Save the x86 HVM specific parts of the domain. This is considerably simpler than an x86 PV domain. Only the HVM_CONTEXT and HVM_PARAMS records are needed.

There is no need for any page normalisation.

---
 tools/libxc/Makefile             |    1 +
 tools/libxc/xc_sr_common.h       |    1 +
 tools/libxc/xc_sr_save_x86_hvm.c |  220 ++++++++++++++++++++++++++++++++++++++
 3 files changed, 222 insertions(+)
 create mode 100644 tools/libxc/xc_sr_save_x86_hvm.c
tools/libxc/Makefile +1 -0
index b301432..936512d 100644
@@ -59,6 +59,7 @@ GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86_pv.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_restore_x86_pv.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_save_x86_pv.c
+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
tools/libxc/xc_sr_common.h +1 -0
index 7d3d54f..a8b5568 100644
@@ -286,6 +286,7 @@ struct xc_sr_context
 };
 
 extern struct xc_sr_save_ops save_ops_x86_pv;
+extern struct xc_sr_save_ops save_ops_x86_hvm;
 
 extern struct xc_sr_restore_ops restore_ops_x86_pv;
 
tools/libxc/xc_sr_save_x86_hvm.c new file +220 -0

220 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#13 lore raw

PATCH v10 11/15 tools/libxc: x86 HVM restore code

In reply to Andrew Cooper

Restore the x86 HVM specific parts of a domain. This is the HVM_CONTEXT and HVM_PARAMS records.

There is no need for any page localisation.

This also includes writing the trailing qemu save record to a file because this is what libxc currently does. This is intended to be moved into libxl proper in the future.

---
v10: Set CONSOLE_EVTCHN parameter

---
 tools/libxc/Makefile                |    1 +
 tools/libxc/xc_sr_common.h          |    1 +
 tools/libxc/xc_sr_restore_x86_hvm.c |  233 +++++++++++++++++++++++++++++++++++
 3 files changed, 235 insertions(+)
 create mode 100644 tools/libxc/xc_sr_restore_x86_hvm.c
tools/libxc/Makefile +1 -0
index 936512d..76f63a1 100644
@@ -58,6 +58,7 @@ GUEST_SRCS-y += xc_sr_common.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_common_x86_pv.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_restore_x86_pv.c
+GUEST_SRCS-$(CONFIG_X86) += xc_sr_restore_x86_hvm.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_save_x86_pv.c
 GUEST_SRCS-$(CONFIG_X86) += xc_sr_save_x86_hvm.c
 GUEST_SRCS-y += xc_sr_restore.c
tools/libxc/xc_sr_common.h +1 -0
index a8b5568..ef42412 100644
@@ -289,6 +289,7 @@ struct xc_sr_context
 extern struct xc_sr_save_ops save_ops_x86_hvm;
 
 extern struct xc_sr_restore_ops restore_ops_x86_pv;
+extern struct xc_sr_restore_ops restore_ops_x86_hvm;
 
 struct xc_sr_record
 {
tools/libxc/xc_sr_restore_x86_hvm.c new file +233 -0

233 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#14 lore raw

PATCH v10 12/15 tools/libxc: common save code

In reply to Andrew Cooper

Save a domain, calling domain type specific function at the appropriate points. This implements the xc_domain_save2() API function which is equivalent to the existing xc_domain_save().

This writes the image and domain headers, and writes all the PAGE_DATA records using a "live" process.

---
 tools/libxc/xc_sr_save.c |  777 +++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 776 insertions(+), 1 deletion(-)
tools/libxc/xc_sr_save.c +776 -1
index 3c34a6b..5d9c267 100644
@@ -1,11 +1,786 @@
+#include <assert.h>
+#include <arpa/inet.h>
+
 #include "xc_sr_common.h"
 
+/*
+ * Writes an Image header and Domain header into the stream.
+ */
+static int write_headers(struct xc_sr_context *ctx, uint16_t guest_type)
+{
+    xc_interface *xch = ctx->xch;
+    int32_t xen_version = xc_version(xch, XENVER_version, NULL);
+    struct xc_sr_ihdr ihdr =
+        {
+            .marker  = IHDR_MARKER,
+            .id      = htonl(IHDR_ID),
+            .version = htonl(IHDR_VERSION),
+            .options = htons(IHDR_OPT_LITTLE_ENDIAN),
+        };
+    struct xc_sr_dhdr dhdr =
+        {
+            .type       = guest_type,
+            .page_shift = XC_PAGE_SHIFT,
+            .xen_major  = (xen_version >> 16) & 0xffff,
+            .xen_minor  = (xen_version)       & 0xffff,
+        };
+
+    if ( xen_version < 0 )
+    {
+        PERROR("Unable to obtain Xen Version");
+        return -1;
+    }
+
+    if ( write_exact(ctx->fd, &ihdr, sizeof(ihdr)) )
+    {
+        PERROR("Unable to write Image Header to stream");
+        return -1;
+    }
+
+    if ( write_exact(ctx->fd, &dhdr, sizeof(dhdr)) )
+    {
+        PERROR("Unable to write Domain Header to stream");
+        return -1;
+    }
+
+    return 0;
+}
+
+/*
+ * Writes an END record into the stream.
+ */
+static int write_end_record(struct xc_sr_context *ctx)
+{
+    struct xc_sr_record end = { REC_TYPE_END, 0, NULL };
+
+    return write_record(ctx, &end);
+}
+
+/*
+ * Writes a batch of memory as a PAGE_DATA record into the stream.  The batch
+ * is constructed in ctx->save.batch_pfns.
+ *
+ * This function:
+ * - gets the types for each pfn in the batch.
+ * - for each pfn with real data:
+ *   - maps and attempts to localise the pages.
+ * - construct and writes a PAGE_DATA record into the stream.
+ */
+static int write_batch(struct xc_sr_context *ctx)
+{
+    xc_interface *xch = ctx->xch;
+    xen_pfn_t *mfns = NULL, *types = NULL;
+    void *guest_mapping = NULL;
+    void **guest_data = NULL;
+    void **local_pages = NULL;
+    int *errors = NULL, rc = -1;
+    unsigned i, p, nr_pages = 0;
+    unsigned nr_pfns = ctx->save.nr_batch_pfns;
+    void *page, *orig_page;
+    uint64_t *rec_pfns = NULL;
+    struct iovec *iov = NULL; int iovcnt = 0;
+    struct xc_sr_rec_page_data_header hdr = { 0 };
+    struct xc_sr_record rec =
+    {
+        .type = REC_TYPE_PAGE_DATA,
+    };
+
+    assert(nr_pfns != 0);
+
+    /* Mfns of the batch pfns. */
+    mfns = malloc(nr_pfns * sizeof(*mfns));
+    /* Types of the batch pfns. */
+    types = malloc(nr_pfns * sizeof(*types));
+    /* Errors from attempting to map the gfns. */
+    errors = malloc(nr_pfns * sizeof(*errors));
+    /* Pointers to page data to send.  Mapped gfns or local allocations. */
+    guest_data = calloc(nr_pfns, sizeof(*guest_data));
+    /* Pointers to locally allocated pages.  Need freeing. */
+    local_pages = calloc(nr_pfns, sizeof(*local_pages));
+    /* iovec[] for writev(). */
+    iov = malloc((nr_pfns + 4) * sizeof(*iov));
+
+    if ( !mfns || !types || !errors || !guest_data || !local_pages || !iov )
+    {
+        ERROR("Unable to allocate arrays for a batch of %u pages",
+              nr_pfns);
+        goto err;
+    }
+
+    for ( i = 0; i < nr_pfns; ++i )
+    {
+        types[i] = mfns[i] = ctx->save.ops.pfn_to_gfn(ctx,
+                                                      ctx->save.batch_pfns[i]);
+
+        /* Likely a ballooned page. */
+        if ( mfns[i] == INVALID_MFN )
+        {
+            set_bit(ctx->save.batch_pfns[i], ctx->save.deferred_pages);
+            ++ctx->save.nr_deferred_pages;
+        }
+    }
+
+    rc = xc_get_pfn_type_batch(xch, ctx->domid, nr_pfns, types);
+    if ( rc )
+    {
+        PERROR("Failed to get types for pfn batch");
+        goto err;
+    }
+    rc = -1;
+
+    for ( i = 0; i < nr_pfns; ++i )
+    {
+        switch ( types[i] )
+        {
+        case XEN_DOMCTL_PFINFO_BROKEN:
+        case XEN_DOMCTL_PFINFO_XALLOC:
+        case XEN_DOMCTL_PFINFO_XTAB:
+            continue;
+        }
+
+        mfns[nr_pages++] = mfns[i];
+    }
+
+    if ( nr_pages > 0 )
+    {
+        guest_mapping = xc_map_foreign_bulk(
+            xch, ctx->domid, PROT_READ, mfns, errors, nr_pages);
+        if ( !guest_mapping )
+        {
+            PERROR("Failed to map guest pages");
+            goto err;
+        }
+
+        for ( i = 0, p = 0; i < nr_pfns; ++i )
+        {
+            switch ( types[i] )
+            {
+            case XEN_DOMCTL_PFINFO_BROKEN:
+            case XEN_DOMCTL_PFINFO_XALLOC:
+            case XEN_DOMCTL_PFINFO_XTAB:
+                continue;
+            }
+
+            if ( errors[p] )
+            {
+                ERROR("Mapping of pfn %#lx (mfn %#lx) failed %d",
+                      ctx->save.batch_pfns[i], mfns[p], errors[p]);
+                goto err;
+            }
+
+            orig_page = page = guest_mapping + (p * PAGE_SIZE);
+            rc = ctx->save.ops.normalise_page(ctx, types[i], &page);
+
+            if ( orig_page != page )
+                local_pages[i] = page;
+
+            if ( rc )
+            {
+                if ( rc == -1 && errno == EAGAIN )
+                {
+                    set_bit(ctx->save.batch_pfns[i], ctx->save.deferred_pages);
+                    ++ctx->save.nr_deferred_pages;
+                    types[i] = XEN_DOMCTL_PFINFO_XTAB;
+                    --nr_pages;
+                }
+                else
+                    goto err;
+            }
+            else
+                guest_data[i] = page;
+
+            rc = -1;
+            ++p;
+        }
+    }
+
+    rec_pfns = malloc(nr_pfns * sizeof(*rec_pfns));
+    if ( !rec_pfns )
+    {
+        ERROR("Unable to allocate %zu bytes of memory for page data pfn list",
+              nr_pfns * sizeof(*rec_pfns));
+        goto err;
+    }
+
+    hdr.count = nr_pfns;
+
+    rec.length = sizeof(hdr);
+    rec.length += nr_pfns * sizeof(*rec_pfns);
+    rec.length += nr_pages * PAGE_SIZE;
+
+    for ( i = 0; i < nr_pfns; ++i )
+        rec_pfns[i] = ((uint64_t)(types[i]) << 32) | ctx->save.batch_pfns[i];
+
+    iov[0].iov_base = &rec.type;
+    iov[0].iov_len = sizeof(rec.type);
+
+    iov[1].iov_base = &rec.length;
+    iov[1].iov_len = sizeof(rec.length);
+
+    iov[2].iov_base = &hdr;
+    iov[2].iov_len = sizeof(hdr);
+
+    iov[3].iov_base = rec_pfns;
+    iov[3].iov_len = nr_pfns * sizeof(*rec_pfns);
+
+    iovcnt = 4;
+
+    if ( nr_pages )
+    {
+        for ( i = 0; i < nr_pfns; ++i )
+        {
+            if ( guest_data[i] )
+            {
+                iov[iovcnt].iov_base = guest_data[i];
+                iov[iovcnt].iov_len = PAGE_SIZE;
+                iovcnt++;
+                --nr_pages;
+            }
+        }
+    }
+
+    if ( writev_exact(ctx->fd, iov, iovcnt) )
+    {
+        PERROR("Failed to write page data to stream");
+        goto err;
+    }
+
+    /* Sanity check we have sent all the pages we expected to. */
+    assert(nr_pages == 0);
+    rc = ctx->save.nr_batch_pfns = 0;
+
+ err:
+    free(rec_pfns);
+    if ( guest_mapping )
+        munmap(guest_mapping, nr_pages * PAGE_SIZE);
+    for ( i = 0; local_pages && i < nr_pfns; ++i )
+        free(local_pages[i]);
+    free(iov);
+    free(local_pages);
+    free(guest_data);
+    free(errors);
+    free(types);
+    free(mfns);
+
+    return rc;
+}
+
+/*
+ * Flush a batch of pfns into the stream.
+ */
+static int flush_batch(struct xc_sr_context *ctx)
+{
+    int rc = 0;
+
+    if ( ctx->save.nr_batch_pfns == 0 )
+        return rc;
+
+    rc = write_batch(ctx);
+
+    if ( !rc )
+    {
+        VALGRIND_MAKE_MEM_UNDEFINED(ctx->save.batch_pfns,
+                                    MAX_BATCH_SIZE *
+                                    sizeof(*ctx->save.batch_pfns));
+    }
+
+    return rc;
+}
+
+/*
+ * Add a single pfn to the batch, flushing the batch if full.
+ */
+static int add_to_batch(struct xc_sr_context *ctx, xen_pfn_t pfn)
+{
+    int rc = 0;
+
+    if ( ctx->save.nr_batch_pfns == MAX_BATCH_SIZE )
+        rc = flush_batch(ctx);
+
+    if ( rc == 0 )
+        ctx->save.batch_pfns[ctx->save.nr_batch_pfns++] = pfn;
+
+    return rc;
+}
+
+/*
+ * Pause/suspend the domain, and refresh ctx->dominfo if required.
+ */
+static int suspend_domain(struct xc_sr_context *ctx)
+{
+    xc_interface *xch = ctx->xch;
+
+    /* TODO: Properly specify the return value from this callback.  All
+     * implementations currently appear to return 1 for success, whereas
+     * the legacy code checks for != 0. */
+    int cb_rc = ctx->save.callbacks->suspend(ctx->save.callbacks->data);
+
+    if ( cb_rc == 0 )
+    {
+        ERROR("save callback suspend() failed: %d", cb_rc);
+        return -1;
+    }
+
+    /* Refresh domain information. */
+    if ( (xc_domain_getinfo(xch, ctx->domid, 1, &ctx->dominfo) != 1) ||
+         (ctx->dominfo.domid != ctx->domid) )
+    {
+        PERROR("Unable to refresh domain information");
+        return -1;
+    }
+
+    /* Confirm the domain has actually been paused. */
+    if ( !ctx->dominfo.shutdown ||
+         (ctx->dominfo.shutdown_reason != SHUTDOWN_suspend) )
+    {
+        ERROR("Domain has not been suspended: shutdown %d, reason %d",
+              ctx->dominfo.shutdown, ctx->dominfo.shutdown_reason);
+        return -1;
+    }
+
+    xc_report_progress_single(xch, "Domain now suspended");
+
+    return 0;
+}
+
+/*
+ * Send all pages in the guests p2m.  Used as the first iteration of the live
+ * migration loop, and for a non-live save.
+ */
+static int send_all_pages(struct xc_sr_context *ctx)
+{
+    xc_interface *xch = ctx->xch;
+    xen_pfn_t p;
+    int rc;
+
+    for ( p = 0; p < ctx->save.p2m_size; ++p )
+    {
+        rc = add_to_batch(ctx, p);
+        if ( rc )
+            return rc;
+
+        /* Update progress every 4MB worth of memory sent. */
+        if ( (p & ((1U << (22 - 12)) - 1)) == 0 )
+            xc_report_progress_step(xch, p, ctx->save.p2m_size);
+    }
+
+    rc = flush_batch(ctx);
+    if ( rc )
+        return rc;
+
+    xc_report_progress_step(xch, ctx->save.p2m_size,
+                            ctx->save.p2m_size);
+    return 0;
+}
+
+/*
+ * Send a subset of pages in the guests p2m, according to the provided bitmap.
+ * Used for each subsequent iteration of the live migration loop.
+ *
+ * Bitmap is bounded by p2m_size.
+ */
+static int send_some_pages(struct xc_sr_context *ctx,
+                           unsigned long *bitmap,
+                           unsigned long entries)
+{
+    xc_interface *xch = ctx->xch;
+    xen_pfn_t p;
+    unsigned long written;
+    int rc;
+
+    for ( p = 0, written = 0; p < ctx->save.p2m_size; ++p )
+    {
+        if ( !test_bit(p, bitmap) )
+            continue;
+
+        rc = add_to_batch(ctx, p);
+        if ( rc )
+            return rc;
+
+        /* Update progress every 4MB worth of memory sent. */
+        if ( (written & ((1U << (22 - 12)) - 1)) == 0 )
+            xc_report_progress_step(xch, written, entries);
+
+        ++written;
+    }
+
+    rc = flush_batch(ctx);
+    if ( rc )
+        return rc;
+
+    if ( written > entries )
+        DPRINTF("Bitmap contained more entries than expected...");
+
+    xc_report_progress_step(xch, entries, entries);
+    return 0;
+}
+
+static int enable_logdirty(struct xc_sr_context *ctx)
+{
+    xc_interface *xch = ctx->xch;
+    int on1 = 0, off = 0, on2 = 0;
+    int rc;
+
+    /* This juggling is required if logdirty is enabled for VRAM tracking. */
+    rc = xc_shadow_control(xch, ctx->domid,
+                           XEN_DOMCTL_SHADOW_OP_ENABLE_LOGDIRTY,
+                           NULL, 0, NULL, 0, NULL);
+    if ( rc < 0 )
+    {
+        on1 = errno;
+        rc = xc_shadow_control(xch, ctx->domid, XEN_DOMCTL_SHADOW_OP_OFF,
+                               NULL, 0, NULL, 0, NULL);
+        if ( rc < 0 )
+            off = errno;
+        else {
+            rc = xc_shadow_control(xch, ctx->domid,
+                                   XEN_DOMCTL_SHADOW_OP_ENABLE_LOGDIRTY,
+                                   NULL, 0, NULL, 0, NULL);
+            if ( rc < 0 )
+                on2 = errno;
+        }
+        if ( rc < 0 )
+        {
+            PERROR("Failed to enable logdirty: %d,%d,%d", on1, off, on2);
+            return rc;
+        }
+    }
+
+    return 0;
+}
+
+static int update_progress_string(struct xc_sr_context *ctx,
+                                  char **str, unsigned iter)
+{
+    xc_interface *xch = ctx->xch;
+    char *new_str = NULL;
+
+    if ( asprintf(&new_str, "Memory iteration %u of %u",
+                  iter, ctx->save.max_iterations) == -1 )
+    {
+        PERROR("Unable to allocate new progress string");
+        return -1;
+    }
+
+    free(*str);
+    *str = new_str;
+
+    xc_set_progress_prefix(xch, *str);
+    return 0;
+}
+
+/*
+ * Send all domain memory.  This is the heart of the live migration loop.
+ */
+static int send_domain_memory_live(struct xc_sr_context *ctx)
+{
+    xc_interface *xch = ctx->xch;
+    DECLARE_HYPERCALL_BUFFER(unsigned long, to_send);
+    xc_shadow_op_stats_t stats = { 0, ctx->save.p2m_size };
+    char *progress_str = NULL;
+    unsigned x;
+    int rc = -1;
+
+    to_send = xc_hypercall_buffer_alloc_pages(
+        xch, to_send, NRPAGES(bitmap_size(ctx->save.p2m_size)));
+
+    ctx->save.batch_pfns = malloc(MAX_BATCH_SIZE *
+                                  sizeof(*ctx->save.batch_pfns));
+    ctx->save.deferred_pages = calloc(1, bitmap_size(ctx->save.p2m_size));
+
+    if ( !ctx->save.batch_pfns || !to_send || !ctx->save.deferred_pages )
+    {
+        ERROR("Unable to allocate memory for to_{send,fix}/batch bitmaps");
+        goto out;
+    }
+
+    rc = enable_logdirty(ctx);
+    if ( rc )
+        goto out;
+
+    rc = update_progress_string(ctx, &progress_str, 0);
+    if ( rc )
+        goto out;
+
+    rc = send_all_pages(ctx);
+    if ( rc )
+        goto out;
+
+    for ( x = 1;
+          ((x < ctx->save.max_iterations) &&
+           (stats.dirty_count > ctx->save.dirty_threshold)); ++x )
+    {
+        if ( xc_shadow_control(
+                 xch, ctx->domid, XEN_DOMCTL_SHADOW_OP_CLEAN,
+                 HYPERCALL_BUFFER(to_send), ctx->save.p2m_size,
+                 NULL, 0, &stats) != ctx->save.p2m_size )
+        {
+            PERROR("Failed to retrieve logdirty bitmap");
+            rc = -1;
+            goto out;
+        }
+
+        if ( stats.dirty_count == 0 )
+            break;
+
+        rc = update_progress_string(ctx, &progress_str, x);
+        if ( rc )
+            goto out;
+
+        rc = send_some_pages(ctx, to_send, stats.dirty_count);
+        if ( rc )
+            goto out;
+    }
+
+    rc = suspend_domain(ctx);
+    if ( rc )
+        goto out;
+
+    if ( xc_shadow_control(
+             xch, ctx->domid, XEN_DOMCTL_SHADOW_OP_CLEAN,
+             HYPERCALL_BUFFER(to_send), ctx->save.p2m_size,
+             NULL, 0, &stats) != ctx->save.p2m_size )
+    {
+        PERROR("Failed to retrieve logdirty bitmap");
+        rc = -1;
+        goto out;
+    }
+
+    rc = update_progress_string(ctx, &progress_str, ctx->save.max_iterations);
+    if ( rc )
+        goto out;
+
+    bitmap_or(to_send, ctx->save.deferred_pages, ctx->save.p2m_size);
+
+    rc = send_some_pages(ctx, to_send,
+                         stats.dirty_count + ctx->save.nr_deferred_pages);
+    if ( rc )
+        goto out;
+
+    if ( ctx->save.debug )
+    {
+        struct xc_sr_record rec =
+        {
+            .type = REC_TYPE_VERIFY,
+            .length = 0,
+        };
+
+        DPRINTF("Enabling verify mode");
+
+        rc = write_record(ctx, &rec);
+        if ( rc )
+            goto out;
+
+        xc_set_progress_prefix(xch, "Memory verify");
+        rc = send_all_pages(ctx);
+        if ( rc )
+            goto out;
+
+        if ( xc_shadow_control(
+                 xch, ctx->domid, XEN_DOMCTL_SHADOW_OP_PEEK,
+                 HYPERCALL_BUFFER(to_send), ctx->save.p2m_size,
+                 NULL, 0, &stats) != ctx->save.p2m_size )
+        {
+            PERROR("Failed to retrieve logdirty bitmap");
+            rc = -1;
+            goto out;
+        }
+
+        DPRINTF("  Further stats: faults %u, dirty %u",
+                stats.fault_count, stats.dirty_count);
+    }
+
+  out:
+    xc_set_progress_prefix(xch, NULL);
+    free(progress_str);
+    xc_hypercall_buffer_free_pages(xch, to_send,
+                                   NRPAGES(bitmap_size(ctx->save.p2m_size)));
+    free(ctx->save.deferred_pages);
+    free(ctx->save.batch_pfns);
+    return rc;
+}
+
+/*
+ * Send all domain memory, pausing the domain first.  Generally used for
+ * suspend-to-file.
+ */
+static int send_domain_memory_nonlive(struct xc_sr_context *ctx)
+{
+    xc_interface *xch = ctx->xch;
+    int rc = -1;
+
+    ctx->save.batch_pfns = malloc(MAX_BATCH_SIZE *
+                                  sizeof(*ctx->save.batch_pfns));
+    ctx->save.deferred_pages = calloc(1, bitmap_size(ctx->save.p2m_size));
+
+    if ( !ctx->save.batch_pfns || !ctx->save.deferred_pages )
+    {
+        PERROR("Failed to allocate memory for nonlive tracking structures");
+        errno = ENOMEM;
+        goto err;
+    }
+
+    rc = suspend_domain(ctx);
+    if ( rc )
+        goto err;
+
+    xc_set_progress_prefix(xch, "Memory");
+
+    rc = send_all_pages(ctx);
+    if ( rc )
+        goto err;
+
+ err:
+    free(ctx->save.deferred_pages);
+    free(ctx->save.batch_pfns);
+
+    return rc;
+}
+
+/*
+ * Save a domain.
+ */
+static int save(struct xc_sr_context *ctx, uint16_t guest_type)
+{
+    xc_interface *xch = ctx->xch;
+    int rc, saved_rc = 0, saved_errno = 0;
+
+    IPRINTF("Saving domain %d, type %s",
+            ctx->domid, dhdr_type_to_str(guest_type));
+
+    rc = ctx->save.ops.setup(ctx);
+    if ( rc )
+        goto err;
+
+    xc_report_progress_single(xch, "Start of stream");
+
+    rc = write_headers(ctx, guest_type);
+    if ( rc )
+        goto err;
+
+    rc = ctx->save.ops.start_of_stream(ctx);
+    if ( rc )
+        goto err;
+
+    if ( ctx->save.live )
+        rc = send_domain_memory_live(ctx);
+    else
+        rc = send_domain_memory_nonlive(ctx);
+
+    if ( rc )
+        goto err;
+
+    if ( !ctx->dominfo.shutdown ||
+         (ctx->dominfo.shutdown_reason != SHUTDOWN_suspend) )
+    {
+        ERROR("Domain has not been suspended");
+        rc = -1;
+        goto err;
+    }
+
+    xc_report_progress_single(xch, "End of stream");
+
+    rc = ctx->save.ops.end_of_stream(ctx);
+    if ( rc )
+        goto err;
+
+    rc = write_end_record(ctx);
+    if ( rc )
+        goto err;
+
+    xc_report_progress_single(xch, "Complete");
+    goto done;
+
+ err:
+    saved_errno = errno;
+    saved_rc = rc;
+    PERROR("Save failed");
+
+ done:
+    xc_shadow_control(xch, ctx->domid, XEN_DOMCTL_SHADOW_OP_OFF,
+                      NULL, 0, NULL, 0, NULL);
+
+    rc = ctx->save.ops.cleanup(ctx);
+    if ( rc )
+        PERROR("Failed to clean up");
+
+    if ( saved_rc )
+    {
+        rc = saved_rc;
+        errno = saved_errno;
+    }
+
+    return rc;
+};
+
 int xc_domain_save2(xc_interface *xch, int io_fd, uint32_t dom,
                     uint32_t max_iters, uint32_t max_factor, uint32_t flags,
                     struct save_callbacks* callbacks, int hvm)
 {
+    xen_pfn_t nr_pfns;
+    struct xc_sr_context ctx =
+        {
+            .xch = xch,
+            .fd = io_fd,
+        };
+
+    /* GCC 4.4 (of CentOS 6.x vintage) can' t initialise anonymous unions. */
+    ctx.save.callbacks = callbacks;
+    ctx.save.live  = !!(flags & XCFLAGS_LIVE);
+    ctx.save.debug = !!(flags & XCFLAGS_DEBUG);
+
+    /*
+     * TODO: Find some time to better tweak the live migration algorithm.
+     *
+     * These parameters are better than the legacy algorithm especially for
+     * busy guests.
+     */
+    ctx.save.max_iterations = 5;
+    ctx.save.dirty_threshold = 50;
+
     IPRINTF("In experimental %s", __func__);
-    return -1;
+    DPRINTF("fd %d, dom %u, max_iters %u, max_factor %u, flags %u, hvm %d",
+            io_fd, dom, max_iters, max_factor, flags, hvm);
+
+    if ( xc_domain_getinfo(xch, dom, 1, &ctx.dominfo) != 1 )
+    {
+        PERROR("Failed to get domain info");
+        return -1;
+    }
+
+    if ( ctx.dominfo.domid != dom )
+    {
+        ERROR("Domain %u does not exist", dom);
+        return -1;
+    }
+
+    ctx.domid = dom;
+
+    if ( xc_domain_nr_gpfns(xch, dom, &nr_pfns) < 0 )
+    {
+        PERROR("Unable to obtain the guest p2m size");
+        return -1;
+    }
+
+    ctx.save.p2m_size = nr_pfns;
+
+    if ( ctx.save.p2m_size > ~XEN_DOMCTL_PFINFO_LTAB_MASK )
+    {
+        errno = E2BIG;
+        ERROR("Cannot save this big a guest");
+        return -1;
+    }
+
+    if ( ctx.dominfo.hvm )
+    {
+        ctx.save.ops = save_ops_x86_hvm;
+        return save(&ctx, DHDR_TYPE_X86_HVM);
+    }
+    else
+    {
+        ctx.save.ops = save_ops_x86_pv;
+        return save(&ctx, DHDR_TYPE_X86_PV);
+    }
 }
 
 /*
Signature · 1 line
1.7.10.4
#15 lore raw

PATCH v10 13/15 tools/libxc: common restore code

In reply to Andrew Cooper

Restore a domain from the new format. This reads and validates the domain and image header and loads the guest memory from the PAGE_DATA records, populating the p2m as it does so.

This provides the xc_domain_restore2() function as an alternative to the existing xc_domain_restore().

---
 tools/libxc/xc_sr_restore.c |  507 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 503 insertions(+), 4 deletions(-)
tools/libxc/xc_sr_restore.c +503 -4
index 045f486..0bf4bae 100644
@@ -1,6 +1,133 @@
+#include <arpa/inet.h>
+
 #include "xc_sr_common.h"
 
 /*
+ * Read and validate the Image and Domain headers.
+ */
+static int read_headers(struct xc_sr_context *ctx)
+{
+    xc_interface *xch = ctx->xch;
+    struct xc_sr_ihdr ihdr;
+    struct xc_sr_dhdr dhdr;
+
+    if ( read_exact(ctx->fd, &ihdr, sizeof(ihdr)) )
+    {
+        PERROR("Failed to read Image Header from stream");
+        return -1;
+    }
+
+    ihdr.id      = ntohl(ihdr.id);
+    ihdr.version = ntohl(ihdr.version);
+    ihdr.options = ntohs(ihdr.options);
+
+    if ( ihdr.marker != IHDR_MARKER )
+    {
+        ERROR("Invalid marker: Got 0x%016"PRIx64, ihdr.marker);
+        return -1;
+    }
+    else if ( ihdr.id != IHDR_ID )
+    {
+        ERROR("Invalid ID: Expected 0x%08x, Got 0x%08x", IHDR_ID, ihdr.id);
+        return -1;
+    }
+    else if ( ihdr.version != IHDR_VERSION )
+    {
+        ERROR("Invalid Version: Expected %d, Got %d",
+              ihdr.version, IHDR_VERSION);
+        return -1;
+    }
+    else if ( ihdr.options & IHDR_OPT_BIG_ENDIAN )
+    {
+        ERROR("Unable to handle big endian streams");
+        return -1;
+    }
+
+    ctx->restore.format_version = ihdr.version;
+
+    if ( read_exact(ctx->fd, &dhdr, sizeof(dhdr)) )
+    {
+        PERROR("Failed to read Domain Header from stream");
+        return -1;
+    }
+
+    ctx->restore.guest_type = dhdr.type;
+    ctx->restore.guest_page_size = (1U << dhdr.page_shift);
+
+    if ( dhdr.xen_major == 0 )
+    {
+        IPRINTF("Found %s domain, converted from legacy stream format",
+                dhdr_type_to_str(dhdr.type));
+        DPRINTF("  Legacy conversion script version %u", dhdr.xen_minor);
+    }
+    else
+        IPRINTF("Found %s domain from Xen %u.%u",
+                dhdr_type_to_str(dhdr.type), dhdr.xen_major, dhdr.xen_minor);
+    return 0;
+}
+
+/*
+ * Reads a record from the stream, and fills in the record structure.
+ *
+ * Returns 0 on success and non-0 on failure.
+ *
+ * On success, the records type and size shall be valid.
+ * - If size is 0, data shall be NULL.
+ * - If size is non-0, data shall be a buffer allocated by malloc() which must
+ *   be passed to free() by the caller.
+ *
+ * On failure, the contents of the record structure are undefined.
+ */
+static int read_record(struct xc_sr_context *ctx, struct xc_sr_record *rec)
+{
+    xc_interface *xch = ctx->xch;
+    struct xc_sr_rhdr rhdr;
+    size_t datasz;
+
+    if ( read_exact(ctx->fd, &rhdr, sizeof(rhdr)) )
+    {
+        PERROR("Failed to read Record Header from stream");
+        return -1;
+    }
+    else if ( rhdr.length > REC_LENGTH_MAX )
+    {
+        ERROR("Record (0x%08x, %s) length %#x exceeds max (%#x)", rhdr.type,
+              rec_type_to_str(rhdr.type), rhdr.length, REC_LENGTH_MAX);
+        return -1;
+    }
+
+    datasz = ROUNDUP(rhdr.length, REC_ALIGN_ORDER);
+
+    if ( datasz )
+    {
+        rec->data = malloc(datasz);
+
+        if ( !rec->data )
+        {
+            ERROR("Unable to allocate %zu bytes for record data (0x%08x, %s)",
+                  datasz, rhdr.type, rec_type_to_str(rhdr.type));
+            return -1;
+        }
+
+        if ( read_exact(ctx->fd, rec->data, datasz) )
+        {
+            free(rec->data);
+            rec->data = NULL;
+            PERROR("Failed to read %zu bytes of data for record (0x%08x, %s)",
+                   datasz, rhdr.type, rec_type_to_str(rhdr.type));
+            return -1;
+        }
+    }
+    else
+        rec->data = NULL;
+
+    rec->type   = rhdr.type;
+    rec->length = rhdr.length;
+
+    return 0;
+};
+
+/*
  * Is a pfn populated?
  */
 static bool pfn_is_populated(const struct xc_sr_context *ctx, xen_pfn_t pfn)
@@ -12,7 +139,7 @@ static bool pfn_is_populated(const struct xc_sr_context *ctx, xen_pfn_t pfn)
 
 /*
  * Set a pfn as populated, expanding the tracking structures if needed. To
- * avoid realloc()ing too excessivly, the size increased to the nearest power
+ * avoid realloc()ing too excessively, the size increased to the nearest power
  * of two large enough to contain the required pfn.
  */
 static int pfn_set_populated(struct xc_sr_context *ctx, xen_pfn_t pfn)
@@ -59,7 +186,7 @@ static int pfn_set_populated(struct xc_sr_context *ctx, xen_pfn_t pfn)
 
 /*
  * Given a set of pfns, obtain memory from Xen to fill the physmap for the
- * unpopulated subset.  If types is NULL, no page typechecking is performed
+ * unpopulated subset.  If types is NULL, no page type checking is performed
  * and all unpopulated pfns are populated.
  */
 int populate_pfns(struct xc_sr_context *ctx, unsigned count,
@@ -125,16 +252,388 @@ int populate_pfns(struct xc_sr_context *ctx, unsigned count,
     return rc;
 }
 
+/*
+ * Given a list of pfns, their types, and a block of page data from the
+ * stream, populate and record their types, map the relevant subset and copy
+ * the data into the guest.
+ */
+static int process_page_data(struct xc_sr_context *ctx, unsigned count,
+                             xen_pfn_t *pfns, uint32_t *types, void *page_data)
+{
+    xc_interface *xch = ctx->xch;
+    xen_pfn_t *mfns = malloc(count * sizeof(*mfns));
+    int *map_errs = malloc(count * sizeof(*map_errs));
+    int rc;
+    void *mapping = NULL, *guest_page = NULL;
+    unsigned i,    /* i indexes the pfns from the record. */
+        j,         /* j indexes the subset of pfns we decide to map. */
+        nr_pages = 0;
+
+    if ( !mfns || !map_errs )
+    {
+        rc = -1;
+        ERROR("Failed to allocate %zu bytes to process page data",
+              count * (sizeof(*mfns) + sizeof(*map_errs)));
+        goto err;
+    }
+
+    rc = populate_pfns(ctx, count, pfns, types);
+    if ( rc )
+    {
+        ERROR("Failed to populate pfns for batch of %u pages", count);
+        goto err;
+    }
+
+    for ( i = 0; i < count; ++i )
+    {
+        ctx->restore.ops.set_page_type(ctx, pfns[i], types[i]);
+
+        switch ( types[i] )
+        {
+        case XEN_DOMCTL_PFINFO_NOTAB:
+
+        case XEN_DOMCTL_PFINFO_L1TAB:
+        case XEN_DOMCTL_PFINFO_L1TAB | XEN_DOMCTL_PFINFO_LPINTAB:
+
+        case XEN_DOMCTL_PFINFO_L2TAB:
+        case XEN_DOMCTL_PFINFO_L2TAB | XEN_DOMCTL_PFINFO_LPINTAB:
+
+        case XEN_DOMCTL_PFINFO_L3TAB:
+        case XEN_DOMCTL_PFINFO_L3TAB | XEN_DOMCTL_PFINFO_LPINTAB:
+
+        case XEN_DOMCTL_PFINFO_L4TAB:
+        case XEN_DOMCTL_PFINFO_L4TAB | XEN_DOMCTL_PFINFO_LPINTAB:
+
+            mfns[nr_pages++] = ctx->restore.ops.pfn_to_gfn(ctx, pfns[i]);
+            break;
+        }
+    }
+
+    /* Nothing to do? */
+    if ( nr_pages == 0 )
+        goto done;
+
+    mapping = guest_page = xc_map_foreign_bulk(
+        xch, ctx->domid, PROT_READ | PROT_WRITE,
+        mfns, map_errs, nr_pages);
+    if ( !mapping )
+    {
+        rc = -1;
+        PERROR("Unable to map %u mfns for %u pages of data",
+               nr_pages, count);
+        goto err;
+    }
+
+    for ( i = 0, j = 0; i < count; ++i )
+    {
+        switch ( types[i] )
+        {
+        case XEN_DOMCTL_PFINFO_XTAB:
+        case XEN_DOMCTL_PFINFO_BROKEN:
+        case XEN_DOMCTL_PFINFO_XALLOC:
+            /* No page data to deal with. */
+            continue;
+        }
+
+        if ( map_errs[j] )
+        {
+            rc = -1;
+            ERROR("Mapping pfn %lx (mfn %lx, type %#x)failed with %d",
+                  pfns[i], mfns[j], types[i], map_errs[j]);
+            goto err;
+        }
+
+        /* Undo page normalisation done by the saver. */
+        rc = ctx->restore.ops.localise_page(ctx, types[i], page_data);
+        if ( rc )
+        {
+            ERROR("Failed to localise pfn %lx (type %#x)",
+                  pfns[i], types[i] >> XEN_DOMCTL_PFINFO_LTAB_SHIFT);
+            goto err;
+        }
+
+        if ( ctx->restore.verify )
+        {
+            /* Verify mode - compare incoming data to what we already have. */
+            if ( memcmp(guest_page, page_data, PAGE_SIZE) )
+                ERROR("verify pfn %lx failed (type %#x)",
+                      pfns[i], types[i] >> XEN_DOMCTL_PFINFO_LTAB_SHIFT);
+        }
+        else
+        {
+            /* Regular mode - copy incoming data into place. */
+            memcpy(guest_page, page_data, PAGE_SIZE);
+        }
+
+        ++j;
+        guest_page += PAGE_SIZE;
+        page_data += PAGE_SIZE;
+    }
+
+ done:
+    rc = 0;
+
+ err:
+    if ( mapping )
+        munmap(mapping, nr_pages * PAGE_SIZE);
+
+    free(map_errs);
+    free(mfns);
+
+    return rc;
+}
+
+/*
+ * Validate a PAGE_DATA record from the stream, and pass the results to
+ * process_page_data() to actually perform the legwork.
+ */
+static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec)
+{
+    xc_interface *xch = ctx->xch;
+    struct xc_sr_rec_page_data_header *pages = rec->data;
+    unsigned i, pages_of_data = 0;
+    int rc = -1;
+
+    xen_pfn_t *pfns = NULL, pfn;
+    uint32_t *types = NULL, type;
+
+    if ( rec->length < sizeof(*pages) )
+    {
+        ERROR("PAGE_DATA record truncated: length %u, min %zu",
+              rec->length, sizeof(*pages));
+        goto err;
+    }
+    else if ( pages->count < 1 )
+    {
+        ERROR("Expected at least 1 pfn in PAGE_DATA record");
+        goto err;
+    }
+    else if ( rec->length < sizeof(*pages) + (pages->count * sizeof(uint64_t)) )
+    {
+        ERROR("PAGE_DATA record (length %u) too short to contain %u"
+              " pfns worth of information", rec->length, pages->count);
+        goto err;
+    }
+
+    pfns = malloc(pages->count * sizeof(*pfns));
+    types = malloc(pages->count * sizeof(*types));
+    if ( !pfns || !types )
+    {
+        ERROR("Unable to allocate enough memory for %u pfns",
+              pages->count);
+        goto err;
+    }
+
+    for ( i = 0; i < pages->count; ++i )
+    {
+        pfn = pages->pfn[i] & PAGE_DATA_PFN_MASK;
+        if ( !ctx->restore.ops.pfn_is_valid(ctx, pfn) )
+        {
+            ERROR("pfn %#lx (index %u) outside domain maximum", pfn, i);
+            goto err;
+        }
+
+        type = (pages->pfn[i] & PAGE_DATA_TYPE_MASK) >> 32;
+        if ( ((type >> XEN_DOMCTL_PFINFO_LTAB_SHIFT) >= 5) &&
+             ((type >> XEN_DOMCTL_PFINFO_LTAB_SHIFT) <= 8) )
+        {
+            ERROR("Invalid type %#x for pfn %#lx (index %u)", type, pfn, i);
+            goto err;
+        }
+        else if ( type < XEN_DOMCTL_PFINFO_BROKEN )
+            /* NOTAB and all L1 through L4 tables (including pinned) should
+             * have a page worth of data in the record. */
+            pages_of_data++;
+
+        pfns[i] = pfn;
+        types[i] = type;
+    }
+
+    if ( rec->length != (sizeof(*pages) +
+                         (sizeof(uint64_t) * pages->count) +
+                         (PAGE_SIZE * pages_of_data)) )
+    {
+        ERROR("PAGE_DATA record wrong size: length %u, expected "
+              "%zu + %zu + %lu", rec->length, sizeof(*pages),
+              (sizeof(uint64_t) * pages->count), (PAGE_SIZE * pages_of_data));
+        goto err;
+    }
+
+    rc = process_page_data(ctx, pages->count, pfns, types,
+                           &pages->pfn[pages->count]);
+ err:
+    free(types);
+    free(pfns);
+
+    return rc;
+}
+
+/*
+ * Restore a domain.
+ */
+static int restore(struct xc_sr_context *ctx)
+{
+    xc_interface *xch = ctx->xch;
+    struct xc_sr_record rec;
+    int rc, saved_rc = 0, saved_errno = 0;
+
+    IPRINTF("Restoring domain");
+
+    rc = ctx->restore.ops.setup(ctx);
+    if ( rc )
+        goto err;
+
+    ctx->restore.max_populated_pfn = (32 * 1024 / 4) - 1;
+    ctx->restore.populated_pfns = bitmap_alloc(
+        ctx->restore.max_populated_pfn + 1);
+    if ( !ctx->restore.populated_pfns )
+    {
+        ERROR("Unable to allocate memory for populated_pfns bitmap");
+        goto err;
+    }
+
+    do
+    {
+        rc = read_record(ctx, &rec);
+        if ( rc )
+            goto err;
+
+        switch ( rec.type )
+        {
+        case REC_TYPE_END:
+            break;
+
+        case REC_TYPE_PAGE_DATA:
+            rc = handle_page_data(ctx, &rec);
+            break;
+
+        case REC_TYPE_VERIFY:
+            DPRINTF("Verify mode enabled");
+            ctx->restore.verify = true;
+            break;
+
+        default:
+            rc = ctx->restore.ops.process_record(ctx, &rec);
+            break;
+        }
+
+        free(rec.data);
+
+        if ( rc == RECORD_NOT_PROCESSED )
+        {
+            if ( rec.type & REC_TYPE_OPTIONAL )
+                DPRINTF("Ignoring optional record %#x (%s)",
+                        rec.type, rec_type_to_str(rec.type));
+            else
+            {
+                ERROR("Mandatory record %#x (%s) not handled",
+                      rec.type, rec_type_to_str(rec.type));
+                rc = -1;
+            }
+        }
+
+        if ( rc )
+            goto err;
+
+    } while ( rec.type != REC_TYPE_END );
+
+    rc = ctx->restore.ops.stream_complete(ctx);
+    if ( rc )
+        goto err;
+
+    IPRINTF("Restore successful");
+    goto done;
+
+ err:
+    saved_errno = errno;
+    saved_rc = rc;
+    PERROR("Restore failed");
+
+ done:
+    free(ctx->restore.populated_pfns);
+    rc = ctx->restore.ops.cleanup(ctx);
+    if ( rc )
+        PERROR("Failed to clean up");
+
+    if ( saved_rc )
+    {
+        rc = saved_rc;
+        errno = saved_errno;
+    }
+
+    return rc;
+}
+
 int xc_domain_restore2(xc_interface *xch, int io_fd, uint32_t dom,
                        unsigned int store_evtchn, unsigned long *store_mfn,
                        domid_t store_domid, unsigned int console_evtchn,
-                       unsigned long *console_mfn, domid_t console_domid,
+                       unsigned long *console_gfn, domid_t console_domid,
                        unsigned int hvm, unsigned int pae, int superpages,
                        int checkpointed_stream,
                        struct restore_callbacks *callbacks)
 {
+    struct xc_sr_context ctx =
+        {
+            .xch = xch,
+            .fd = io_fd,
+        };
+
+    /* GCC 4.4 (of CentOS 6.x vintage) can' t initialise anonymous unions. */
+    ctx.restore.console_evtchn = console_evtchn;
+    ctx.restore.console_domid = console_domid;
+    ctx.restore.xenstore_evtchn = store_evtchn;
+    ctx.restore.xenstore_domid = store_domid;
+    ctx.restore.callbacks = callbacks;
+
     IPRINTF("In experimental %s", __func__);
-    return -1;
+    DPRINTF("fd %d, dom %u, hvm %u, pae %u, superpages %d"
+            ", checkpointed_stream %d", io_fd, dom, hvm, pae,
+            superpages, checkpointed_stream);
+
+    if ( xc_domain_getinfo(xch, dom, 1, &ctx.dominfo) != 1 )
+    {
+        PERROR("Failed to get domain info");
+        return -1;
+    }
+
+    if ( ctx.dominfo.domid != dom )
+    {
+        ERROR("Domain %u does not exist", dom);
+        return -1;
+    }
+
+    ctx.domid = dom;
+
+    if ( read_headers(&ctx) )
+        return -1;
+
+    if ( ctx.dominfo.hvm )
+    {
+        ctx.restore.ops = restore_ops_x86_hvm;
+        if ( restore(&ctx) )
+            return -1;
+    }
+    else
+    {
+        ctx.restore.ops = restore_ops_x86_pv;
+        if ( restore(&ctx) )
+            return -1;
+    }
+
+    IPRINTF("XenStore: mfn %#lx, dom %d, evt %u",
+            ctx.restore.xenstore_gfn,
+            ctx.restore.xenstore_domid,
+            ctx.restore.xenstore_evtchn);
+
+    IPRINTF("Console: mfn %#lx, dom %d, evt %u",
+            ctx.restore.console_gfn,
+            ctx.restore.console_domid,
+            ctx.restore.console_evtchn);
+
+    *console_gfn = ctx.restore.console_gfn;
+    *store_mfn = ctx.restore.xenstore_gfn;
+
+    return 0;
 }
 
 /*
Signature · 1 line
1.7.10.4
#16 lore raw

PATCH v10 14/15 docs: libxc migration stream specification

In reply to Andrew Cooper

From: David Vrabel <[email protected]>

Add the specification for a new migration stream format. The document includes all the details but to summarize:

The existing (legacy) format is dependant on the word size of the toolstack. This prevents domains from migrating from hosts running 32-bit toolstacks to hosts running 64-bit toolstacks (and vice-versa).

The legacy format lacks any version information making it difficult to extend in compatible way.

The new format has a header (the image header) with version information, a domain header with basic information of the domain and a stream of records for the image data.

The format will be used for future domain types (such as on ARM).

The specification is pandoc format (an extended markdown format) and the documentation build system is extended to support pandoc format documents.

---

---
 docs/specs/libxc-migration-stream.pandoc |  672 ++++++++++++++++++++++++++++++
 1 file changed, 672 insertions(+)
 create mode 100644 docs/specs/libxc-migration-stream.pandoc
docs/specs/libxc-migration-stream.pandoc new file +672 -0
new file mode 100644
index 0000000..455d1ce
@@ -0,0 +1,672 @@
+% LibXenCtrl Domain Image Format
+% David Vrabel <<[email protected]>>
+  Andrew Cooper <<[email protected]>>
+% Draft G
+
+Introduction
+============
+
+Purpose
+-------
+
+The _domain save image_ 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 format of the domain save
+image used in Xen 4.4 and earlier (the _legacy format_).
+
+* Dependant on toolstack word size.  A number of fields within the
+  image are native types such as `unsigned long` which have different
+  sizes between 32-bit and 64-bit toolstacks.  This prevents domains
+  from being migrated between hosts running 32-bit and 64-bit
+  toolstacks.
+
+* There is no header identifying the image.
+
+* The image has no version information.
+
+A new format that addresses the above is required.
+
+ARM does not yet have have a domain save image format specified and
+the format described in this specification should be suitable.
+
+Not Yet Included
+----------------
+
+The following features are not yet fully specified and will be
+included in a future draft.
+
+* Remus
+
+* Page data compression.
+
+* ARM
+
+
+Overview
+========
+
+The image format consists of two main sections:
+
+* _Headers_
+* _Records_
+
+Headers
+-------
+
+There are two headers: the _image header_, and the _domain header_.
+The image header describes the format of the image (version etc.).
+The _domain header_ contains general information about the domain
+(architecture, type etc.).
+
+Records
+-------
+
+The main part of the format is a sequence of different _records_.
+Each record type contains information about the domain context.  At a
+minimum there is a END record marking the end of the records section.
+
+
+Fields
+------
+
+All the fields within the headers and records have a fixed width.
+
+Fields are always aligned to their size.
+
+Padding and reserved fields are set to zero on save and must be
+ignored during restore.
+
+Integer (numeric) fields in the image header are always in big-endian
+byte order.
+
+Integer fields in the domain header and in the records are in the
+endianess described in the image header (which will typically be the
+native ordering).
+
+\clearpage
+
+Headers
+=======
+
+Image Header
+------------
+
+The image header identifies an image as a Xen domain save image.  It
+includes the version of this specification that the image complies
+with.
+
+Tools supporting version _V_ of the specification shall always save
+images using version _V_.  Tools shall support restoring from version
+_V_.  If the previous Xen release produced version _V_ - 1 images,
+tools shall supported restoring from these.  Tools may additionally
+support restoring from earlier versions.
+
+The marker field can be used to distinguish between legacy images and
+those corresponding to this specification.  Legacy images will have at
+one or more zero bits within the first 8 octets of the image.
+
+Fields within the image header are always in _big-endian_ byte order,
+regardless of the setting of the endianness bit.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+    | marker                                          |
+    +-----------------------+-------------------------+
+    | id                    | version                 |
+    +-----------+-----------+-------------------------+
+    | options   | (reserved)                          |
+    +-----------+-------------------------------------+
+
+
+--------------------------------------------------------------------
+Field       Description
+----------- --------------------------------------------------------
+marker      0xFFFFFFFFFFFFFFFF.
+
+id          0x58454E46 ("XENF" in ASCII).
+
+version     0x00000002.  The version of this specification.
+
+options     bit 0: Endianness.  0 = little-endian, 1 = big-endian.
+
+            bit 1-15: Reserved.
+--------------------------------------------------------------------
+
+The endianness shall be 0 (little-endian) for images generated on an
+i386, x86_64, or arm host.
+
+\clearpage
+
+Domain Header
+-------------
+
+The domain header includes general properties of the domain.
+
+     0      1     2     3     4     5     6     7 octet
+    +-----------------------+-----------+-------------+
+    | type                  | page_shift| (reserved)  |
+    +-----------------------+-----------+-------------+
+    | xen_major             | xen_minor               |
+    +-----------------------+-------------------------+
+
+--------------------------------------------------------------------
+Field       Description
+----------- --------------------------------------------------------
+type        0x0000: Reserved.
+
+            0x0001: x86 PV.
+
+            0x0002: x86 HVM.
+
+            0x0003: x86 PVH.
+
+            0x0004: ARM.
+
+            0x0005 - 0xFFFFFFFF: Reserved.
+
+page_shift  Size of a guest page as a power of two.
+
+            i.e., page size = 2 ^page_shift^.
+
+xen_major   The Xen major version when this image was saved.
+
+xen_minor   The Xen minor version when this image was saved.
+--------------------------------------------------------------------
+
+The legacy stream conversion tool writes a `xen_major` version of 0, and sets
+`xen_minor` to the version of itself.
+
+\clearpage
+
+Records
+=======
+
+A record has a record header, type specific data and a trailing
+footer.  If `body_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: PAGE_DATA
+
+             0x00000002: X86_PV_INFO
+
+             0x00000003: X86_PV_P2M_FRAMES
+
+             0x00000004: X86_PV_VCPU_BASIC
+
+             0x00000005: X86_PV_VCPU_EXTENDED
+
+             0x00000006: X86_PV_VCPU_XSAVE
+
+             0x00000007: SHARED_INFO
+
+             0x00000008: TSC_INFO
+
+             0x00000009: HVM_CONTEXT
+
+             0x0000000A: HVM_PARAMS
+
+             0x0000000B: TOOLSTACK
+
+             0x0000000C: X86_PV_VCPU_MSRS
+
+             0x0000000D: VERIFY
+
+             0x0000000E - 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.
+--------------------------------------------------------------------
+
+Records may be _mandatory_ or _optional_.  Optional records have bit
+31 set in their type.  Restoring an image that has unrecognised or
+unsupported mandatory record must fail.  The contents of optional
+records may be ignored during a restore.
+
+The following sub-sections specify the record body format for each of
+the record types.
+
+\clearpage
+
+END
+----
+
+An 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.
+
+\clearpage
+
+PAGE_DATA
+---------
+
+The bulk of an image consists of many PAGE_DATA records containing the
+memory contents.
+
+     0     1     2     3     4     5     6     7 octet
+    +-----------------------+-------------------------+
+    | count (C)             | (reserved)              |
+    +-----------------------+-------------------------+
+    | pfn[0]                                          |
+    +-------------------------------------------------+
+    ...
+    +-------------------------------------------------+
+    | pfn[C-1]                                        |
+    +-------------------------------------------------+
+    | page_data[0]...                                 |
+    ...
+    +-------------------------------------------------+
+    | page_data[N-1]...                               |
+    ...
+    +-------------------------------------------------+
+
+--------------------------------------------------------------------
+Field       Description
+----------- --------------------------------------------------------
+count       Number of pages described in this record.
+
+pfn         An array of count PFNs and their types.
+
+            Bit 63-60: XEN\_DOMCTL\_PFINFO\_* type (from
+            `public/domctl.h` but shifted by 32 bits)
+
+            Bit 59-52: Reserved.
+
+            Bit 51-0: PFN.
+
+page\_data  page\_size octets of uncompressed page contents for each
+            page set as present in the pfn array.
+--------------------------------------------------------------------
+
+Note: Count is strictly > 0.  N is strictly <= C and it is possible for there
+to be no page_data in the record if all pfns are of invalid types.
+
+--------------------------------------------------------------------
+PFINFO type    Value      Description
+-------------  ---------  ------------------------------------------
+NOTAB          0x0        Normal page.
+
+L1TAB          0x1        L1 page table page.
+
+L2TAB          0x2        L2 page table page.
+
+L3TAB          0x3        L3 page table page.
+
+L4TAB          0x4        L4 page table page.
+
+               0x5-0x8    Reserved.
+
+L1TAB_PIN      0x9        L1 page table page (pinned).
+
+L2TAB_PIN      0xA        L2 page table page (pinned).
+
+L3TAB_PIN      0xB        L3 page table page (pinned).
+
+L4TAB_PIN      0xC        L4 page table page (pinned).
+
+BROKEN         0xD        Broken page.
+
+XALLOC         0xE        Allocate only.
+
+XTAB           0xF        Invalid page.
+--------------------------------------------------------------------
+
+Table: XEN\_DOMCTL\_PFINFO\_* Page Types.
+
+PFNs with type `BROKEN`, `XALLOC`, or `XTAB` do not have any
+corresponding `page_data`.
+
+The saver uses the `XTAB` type for PFNs that become invalid in the
+guest's P2M table during a live migration[^2].
+
+Restoring an image with unrecognised page types shall fail.
+
+[^2]: In the legacy format, this is the list of unmapped PFNs in the
+tail.
+
+\clearpage
+
+X86_PV_INFO
+-----------
+
+     0     1     2     3     4     5     6     7 octet
+    +-----+-----+-----------+-------------------------+
+    | w   | ptl | (reserved)                          |
+    +-----+-----+-----------+-------------------------+
+
+--------------------------------------------------------------------
+Field            Description
+-----------      ---------------------------------------------------
+guest_width (w)  Guest width in octets (either 4 or 8).
+
+pt_levels (ptl)  Number of page table levels (either 3 or 4).
+--------------------------------------------------------------------
+
+\clearpage
+
+X86_PV_P2M_FRAMES
+-----------------
+
+     0     1     2     3     4     5     6     7 octet
+    +-----+-----+-----+-----+-------------------------+
+    | p2m_start_pfn (S)     | p2m_end_pfn (E)         |
+    +-----+-----+-----+-----+-------------------------+
+    | p2m_pfn[p2m frame containing pfn S]             |
+    +-------------------------------------------------+
+    ...
+    +-------------------------------------------------+
+    | p2m_pfn[p2m frame containing pfn E]             |
+    +-------------------------------------------------+
+
+--------------------------------------------------------------------
+Field            Description
+-------------    ---------------------------------------------------
+p2m_start_pfn    First pfn index in the p2m_pfn array.
+
+p2m_end_pfn      Last pfn index in the p2m_pfn array.
+
+p2m_pfn          Array of PFNs containing the guest's P2M table, for
+                 the PFN frames containing the PFN range S to E
+                 (inclusive).
+
+--------------------------------------------------------------------
+
+\clearpage
+
+X86_PV_VCPU_BASIC, EXTENDED, XSAVE, MSRS
+----------------------------------------
+
+The format of these records are identical.  They are all binary blobs
+of data which are accessed using specific pairs of domctl hypercalls.
+
+     0     1     2     3     4     5     6     7 octet
+    +-----------------------+-------------------------+
+    | vcpu_id               | (reserved)              |
+    +-----------------------+-------------------------+
+    | context...                                      |
+    ...
+    +-------------------------------------------------+
+
+---------------------------------------------------------------------
+Field            Description
+-----------      ----------------------------------------------------
+vcpu_id          The VCPU ID.
+
+context          Binary data for this VCPU.
+---------------------------------------------------------------------
+
+---------------------------------------------------------------------
+Record type                  Accessor hypercalls
+-----------------------      ----------------------------------------
+X86\_PV\_VCPU\_BASIC         XEN\_DOMCTL\_{get,set}vcpucontext
+
+X86\_PV\_VCPU\_EXTENDED      XEN\_DOMCTL\_{get,set}\_ext\_vcpucontext
+
+X86\_PV\_VCPU\_XSAVE         XEN\_DOMCTL\_{get,set}vcpuextstate
+
+X86\_PV\_VCPU\_MSRS          XEN\_DOMCTL\_{get,set}\_vcpu\_msrs
+---------------------------------------------------------------------
+
+\clearpage
+
+SHARED_INFO
+-----------
+
+The content of the Shared Info page.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+    | shared_info                                     |
+    ...
+    +-------------------------------------------------+
+
+--------------------------------------------------------------------
+Field            Description
+-----------      ---------------------------------------------------
+shared_info      Contents of the shared info page.  This record
+                 should be exactly 1 page long.
+--------------------------------------------------------------------
+
+\clearpage
+
+TSC_INFO
+--------
+
+Domain TSC information, as accessed by the
+XEN\_DOMCTL\_{get,set}tscinfo hypercall sub-ops.
+
+     0     1     2     3     4     5     6     7 octet
+    +------------------------+------------------------+
+    | mode                   | khz                    |
+    +------------------------+------------------------+
+    | nsec                                            |
+    +------------------------+------------------------+
+    | incarnation            | (reserved)             |
+    +------------------------+------------------------+
+
+--------------------------------------------------------------------
+Field            Description
+-----------      ---------------------------------------------------
+mode             TSC mode, TSC\_MODE\_* constant.
+
+khz              TSC frequency, in kHz.
+
+nsec             Elapsed time, in nanoseconds.
+
+incarnation      Incarnation.
+--------------------------------------------------------------------
+
+\clearpage
+
+HVM_CONTEXT
+-----------
+
+HVM Domain context, as accessed by the
+XEN\_DOMCTL\_{get,set}hvmcontext hypercall sub-ops.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+    | hvm_ctx                                         |
+    ...
+    +-------------------------------------------------+
+
+--------------------------------------------------------------------
+Field            Description
+-----------      ---------------------------------------------------
+hvm_ctx          The HVM Context blob from Xen.
+--------------------------------------------------------------------
+
+\clearpage
+
+HVM_PARAMS
+----------
+
+HVM Domain parameters, as accessed by the
+HVMOP\_{get,set}\_param hypercall sub-ops.
+
+     0     1     2     3     4     5     6     7 octet
+    +------------------------+------------------------+
+    | count (C)              | (reserved)             |
+    +------------------------+------------------------+
+    | param[0].index                                  |
+    +-------------------------------------------------+
+    | param[0].value                                  |
+    +-------------------------------------------------+
+    ...
+    +-------------------------------------------------+
+    | param[C-1].index                                |
+    +-------------------------------------------------+
+    | param[C-1].value                                |
+    +-------------------------------------------------+
+
+--------------------------------------------------------------------
+Field            Description
+-----------      ---------------------------------------------------
+count            The number of parameters contained in this record.
+                 Each parameter in the record contains an index and
+                 value.
+
+param index      Parameter index.
+
+param value      Parameter value.
+--------------------------------------------------------------------
+
+\clearpage
+
+TOOLSTACK
+---------
+
+An opaque blob provided by and supplied to the higher layers of the
+toolstack (e.g., libxl) during save and restore.
+
+> This is only temporary -- the intention is the toolstack takes care
+> of this itself.  This record is only present for early development
+> purposes and will be removed before submissions, along with changes
+> to libxl which cause libxl to handle this data itself.
+
+     0     1     2     3     4     5     6     7 octet
+    +------------------------+------------------------+
+    | data                                            |
+    ...
+    +-------------------------------------------------+
+
+--------------------------------------------------------------------
+Field            Description
+-----------      ---------------------------------------------------
+data             Blob of toolstack-specific data.
+--------------------------------------------------------------------
+
+\clearpage
+
+VERIFY
+------
+
+A verify record indicates that, while all memory has now been sent, the sender
+shall send further memory records for debugging purposes.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+
+The verify record contains no fields; its body_length is 0.
+
+\clearpage
+
+Layout
+======
+
+The set of valid records depends on the guest architecture and type.  No
+assumptions should be made about the ordering or interleaving of
+independent records.  Record dependencies are noted below.
+
+x86 PV Guest
+------------
+
+A typical save record for an x86 PV guest image would look like:
+
+1. Image header
+2. Domain header
+3. X86\_PV\_INFO record
+4. X86\_PV\_P2M\_FRAMES record
+5. Many PAGE\_DATA records
+6. TSC\_INFO
+7. SHARED\_INFO record
+8. VCPU context records for each online VCPU
+    a. X86\_PV\_VCPU\_BASIC record
+    b. X86\_PV\_VCPU\_EXTENDED record
+    c. X86\_PV\_VCPU\_XSAVE record
+    d. X86\_PV\_VCPU\_MSRS record
+9. END record
+
+There are some strict ordering requirements.  The following records must
+be present in the following order as each of them depends on information
+present in the preceding ones.
+
+1. X86\_PV\_INFO record
+2. X86\_PV\_P2M\_FRAMES record
+3. PAGE\_DATA records
+4. VCPU records
+
+x86 HVM Guest
+-------------
+
+A typical save record for an x86 HVM guest image would look like:
+
+1. Image header
+2. Domain header
+3. Many PAGE\_DATA records
+4. TSC\_INFO
+5. HVM\_PARAMS
+6. HVM\_CONTEXT
+
+HVM\_PARAMS must precede HVM\_CONTEXT, as certain parameters can affect
+the validity of architectural state in the context.
+
+
+Legacy Images (x86 only)
+========================
+
+Restoring legacy images from older tools shall be handled by
+translating the legacy format image into this new format.
+
+It shall not be possible to save in the legacy format.
+
+There are two different legacy images depending on whether they were
+generated by a 32-bit or a 64-bit toolstack. These shall be
+distinguished by inspecting octets 4-7 in the image.  If these are
+zero then it is a 64-bit image.
+
+Toolstack  Field                            Value
+---------  -----                            -----
+64-bit     Bit 31-63 of the p2m_size field  0 (since p2m_size < 2^32^)
+32-bit     extended-info chunk ID (PV)      0xFFFFFFFF
+32-bit     Chunk type (HVM)                 < 0
+32-bit     Page count (HVM)                 > 0
+
+Table: Possible values for octet 4-7 in legacy images
+
+This assumes the presence of the extended-info chunk which was
+introduced in Xen 3.0.
+
+
+Future Extensions
+=================
+
+All changes to the image or domain headers require the image version
+to be increased.
+
+The format may be extended by adding additional record types.
+
+Extending an existing record type must be done by adding a new record
+type.  This allows old images with the old record to still be
+restored.
+
+The image header may only be extended by _appending_ additional
+fields.  In particular, the `marker`, `id` and `version` fields must
+never change size or location.
Signature · 1 line
1.7.10.4
Acked-by on v10 14/15
#17 lore raw

Re: [PATCH v10 14/15] docs: libxc migration stream specification

Quoted 16 lines · Andrew Cooper

From: David Vrabel <[email protected]>

Add the specification for a new migration stream format. The document includes all the details but to summarize:

The existing (legacy) format is dependant on the word size of the toolstack. This prevents domains from migrating from hosts running 32-bit toolstacks to hosts running 64-bit toolstacks (and vice-versa).

The legacy format lacks any version information making it difficult to extend in compatible way.

The new format has a header (the image header) with version information, a domain header with basic information of the domain and a stream of records for the image data.

Quoted 7 lines

The format will be used for future domain types (such as on ARM).

The specification is pandoc format (an extended markdown format) and the documentation build system is extended to support pandoc format documents.

Without reading:

With two minor comments:

docs/specs/libxc-migration-stream.pandoc line 4

Quoted 10 lines
docs/specs/libxc-migration-stream.pandoc new file +4 -0
new file mode 100644
index 0000000..455d1ce
@@ -0,0 +1,672 @@
+% LibXenCtrl Domain Image Format
+% David Vrabel <<[email protected]>>
+  Andrew Cooper <<[email protected]>>
+% Draft G

No longer a draft? Perhaps s/Draft/Version/?

docs/specs/libxc-migration-stream.pandoc line 85

Quoted 2 lines
docs/specs/libxc-migration-stream.pandoc new file +2 -0
+Integer fields in the domain header and in the records are in the
+endianess described in the image header (which will typically be the

endianness.

Ian.

#18 lore raw

Re: [PATCH v10 14/15] docs: libxc migration stream specification

Quoted 30 lines · Ian Campbell
Quoted 16 lines · Andrew Cooper

From: David Vrabel <[email protected]>

Add the specification for a new migration stream format. The document includes all the details but to summarize:

The existing (legacy) format is dependant on the word size of the toolstack. This prevents domains from migrating from hosts running 32-bit toolstacks to hosts running 64-bit toolstacks (and vice-versa).

The legacy format lacks any version information making it difficult to extend in compatible way.

The new format has a header (the image header) with version information, a domain header with basic information of the domain and a stream of records for the image data.

Quoted 7 lines

The format will be used for future domain types (such as on ARM).

The specification is pandoc format (an extended markdown format) and the documentation build system is extended to support pandoc format documents.

Without reading:

With two minor comments:

Quoted 11 lines

docs/specs/libxc-migration-stream.pandoc line 4

Quoted 10 lines
docs/specs/libxc-migration-stream.pandoc new file +4 -0
new file mode 100644
index 0000000..455d1ce
@@ -0,0 +1,672 @@
+% LibXenCtrl Domain Image Format
+% David Vrabel <<[email protected]>>
+  Andrew Cooper <<[email protected]>>
+% Draft G

No longer a draft? Perhaps s/Draft/Version/?

Strictly speaking it is still a draft until migration v2 becomes enabled by default. This is one of the areas I was going to cover with my post-libxl cleanup patches.

~Andrew

#19 lore raw

Re: [PATCH v10 14/15] docs: libxc migration stream specification

Quoted 43 lines · Andrew Cooper
Quoted 30 lines · Ian Campbell
Quoted 16 lines · Andrew Cooper

From: David Vrabel <[email protected]>

Add the specification for a new migration stream format. The document includes all the details but to summarize:

The existing (legacy) format is dependant on the word size of the toolstack. This prevents domains from migrating from hosts running 32-bit toolstacks to hosts running 64-bit toolstacks (and vice-versa).

The legacy format lacks any version information making it difficult to extend in compatible way.

The new format has a header (the image header) with version information, a domain header with basic information of the domain and a stream of records for the image data.

Quoted 7 lines

The format will be used for future domain types (such as on ARM).

The specification is pandoc format (an extended markdown format) and the documentation build system is extended to support pandoc format documents.

Without reading:

With two minor comments:

Quoted 11 lines

docs/specs/libxc-migration-stream.pandoc line 4

Quoted 10 lines
docs/specs/libxc-migration-stream.pandoc new file +4 -0
new file mode 100644
index 0000000..455d1ce
@@ -0,0 +1,672 @@
+% LibXenCtrl Domain Image Format
+% David Vrabel <<[email protected]>>
+  Andrew Cooper <<[email protected]>>
+% Draft G

No longer a draft? Perhaps s/Draft/Version/?

Quoted 3 lines

Strictly speaking it is still a draft until migration v2 becomes enabled by default. This is one of the areas I was going to cover with my post-libxl cleanup patches.

Good point & sounds good, thanks.

Ian.

#20 lore raw

PATCH v10 15/15 tools/libxc: Migration v2 compatibility for unmodified libxl

In reply to Andrew Cooper

These changes cause migration v2 to behave similarly enough to legacy migration to function for HVM guests under an unmodified xl/libxl.

The migration v2 work for libxl will fix the layering issues with the toolstack and qemu records, at which point this patch will be unneeded.

It is however included here for people wishing to experiment with migration v2 ahead of the libxl work.

---
v10: s/dump_qemu/handle_qemu/ for consistency

---
 tools/libxc/Makefile                |    2 +
 tools/libxc/xc_sr_restore_x86_hvm.c |  102 +++++++++++++++++++++++++++++++++++
 tools/libxc/xc_sr_save_x86_hvm.c    |   36 +++++++++++++
 3 files changed, 140 insertions(+)
tools/libxc/Makefile +2 -0
index 76f63a1..63878ec 100644
@@ -64,6 +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
 else
 GUEST_SRCS-y += xc_nomigrate.c
 endif
tools/libxc/xc_sr_restore_x86_hvm.c +102 -0

126 lines not on this page · raw message

tools/libxc/xc_sr_save_x86_hvm.c +36 -0
index 0928f19..8baa104 100644
@@ -118,6 +118,36 @@ 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)
 {
@@ -170,6 +200,12 @@ static int x86_hvm_end_of_stream(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
#21 lore raw
In reply to Andrew Cooper
Quoted 2 lines · Andrew Cooper

Presented here is v10 of the Migration v2 series (libxc subset), which is able to function when transparently inserted under an unmodified xl/libxl.

I've applied the v11 branch with my minor comments addressed which you provided privately.

Quoted 8 lines

To experiment, simply set XG_MIGRATION_V2 in xl's environment. For migration, the easiest way is to tweak libxl-save-helper to be a shell script

  root@vitruvias:/home# cat /usr/lib/xen/bin/libxl-save-helper
  #!/bin/bash
  export XG_MIGRATION_V2=x
  exec /usr/lib/xen/bin/libxl-save-helper.bin "$@"
Quoted 4 lines

which will ensure that XG_MIGRATION_V2 gets set in the environment for both the source and destination of migration.

Please experiment!

Seconded!

Cheers,
Ian.