Skip to contentSkip to conversation

Add postcopy live migration support

RFC PATCH In review Joshua Otto 6 participants 53 messages Mar 27, 2017 – Apr 27, 2017

lore
Share & tools
lore
#0 lore raw

cover Add postcopy live migration support

Hi,

We're a team of three fourth-year undergraduate software engineering students at the University of Waterloo in Canada. In late 2015 we posted on the list [1] to ask for a project to undertake for our program's capstone design project, and Andrew Cooper pointed us in the direction of the live migration implementation as an area that could use some attention. We were particularly interested in post-copy live migration (as evaluated by [2] and discussed on the list at [3]), and have been working on an implementation of this on-and-off since then.

We now have a working implementation of this scheme, and are submitting it for comment. The changes are also available as the 'postcopy' branch of the GitHub repository at [4]

As a brief overview of our approach:
- We introduce a mechanism by which libxl can indicate to the libxc stream helper process that the iterative migration precopy loop should be terminated and postcopy should begin.
- At this point, we suspend the domain, collect the final set of dirty pfns and write these pfns (and _not_ their contents) into the stream.
- At the destination, the xc restore logic registers itself as a pager for the migrating domain, 'evicts' all of the pfns indicated by the sender as outstanding, and then resumes the domain at the destination.
- As the domain executes, the migration sender continues to push the remaining oustanding pages to the receiver in the background. The receiver monitors both the stream for incoming page data and the paging ring event channel for page faults triggered by the guest. Page faults are forwarded on the back-channel migration stream to the migration sender, which prioritizes these pages for transmission.

By leveraging the existing paging API, we are able to implement the postcopy scheme without any hypervisor modifications - all of our changes are confined to the userspace toolstack. However, we inherit from the paging API the requirement that the domains be HVM and that the host have HAP/EPT support.

We haven't yet had the opportunity to perform a quantitative evaluation of the performance trade-offs between the traditional pre-copy and our post-copy strategies, but intend to. Informally, we've been testing our implementation by migrating a domain running the x86 memtest program (which is obviously a tremendously write-heavy workload), and have observed a substantial reduction in total time required for migration completion (at the expense of a visually obvious 'slowdown' in the execution of the program). We've also noticed that, when performing a postcopy without any leading precopy iterations, the time required at the destination to 'evict' all of the outstanding pages is substantial - possibly because there is no batching mechanism by which pages can be evicted - so this area in particular might require further attention.

We're really interested in any feedback you might have!

Thanks!

Harley Armstrong, Chester Lin, Joshua Otto

[1] https://lists.gt.net/xen/devel/410255
[2] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.184.2368
[3] https://lists.gt.net/xen/devel/261568
[4] https://github.com/jtotto/xen

Joshua Otto (20):
tools: rename COLO 'postcopy' to 'aftercopy'
libxc/xc_sr: parameterise write_record() on fd libxc/xc_sr_restore.c: use write_record() in
send_checkpoint_dirty_pfn_list()
libxc/xc_sr_save.c: add WRITE_TRIVIAL_RECORD_FN() libxc/xc_sr: factor out filter_pages()
libxc/xc_sr: factor helpers out of handle_page_data()
migration: defer precopy policy to libxl
libxl/migration: add precopy tuning parameters libxc/xc_sr_save: introduce save batch types libxc/xc_sr_save.c: initialise rec.data before free() libxc/migration: correct hvm record ordering specification libxc/migration: specify postcopy live migration libxc/migration: add try_read_record()
libxc/migration: implement the sender side of postcopy live migration libxc/migration: implement the receiver side of postcopy live
migration
libxl/libxl_stream_write.c: track callback chains with an explicit
phase
libxl/libxl_stream_read.c: track callback chains with an explicit
phase
libxl/migration: implement the sender side of postcopy live migration libxl/migration: implement the receiver side of postcopy live
migration
tools: expose postcopy live migration support in libxl and xl

 docs/specs/libxc-migration-stream.pandoc |  184 ++++-
 docs/specs/libxl-migration-stream.pandoc |   19 +-
 tools/libxc/include/xenguest.h           |  170 ++--
 tools/libxc/xc_nomigrate.c               |    3 +-
 tools/libxc/xc_private.c                 |   21 +-
 tools/libxc/xc_private.h                 |    2 +
 tools/libxc/xc_sr_common.c               |  118 ++-
 tools/libxc/xc_sr_common.h               |  152 +++-
 tools/libxc/xc_sr_common_x86.c           |    2 +-
 tools/libxc/xc_sr_restore.c              | 1297 +++++++++++++++++++++++++-----
 tools/libxc/xc_sr_restore_x86_hvm.c      |   38 +-
 tools/libxc/xc_sr_save.c                 |  828 +++++++++++++++----
 tools/libxc/xc_sr_save_x86_hvm.c         |   18 +-
 tools/libxc/xc_sr_save_x86_pv.c          |   17 +-
 tools/libxc/xc_sr_stream_format.h        |   15 +-
 tools/libxc/xg_save_restore.h            |   16 +-
 tools/libxl/libxl.h                      |   44 +-
 tools/libxl/libxl_colo_restore.c         |    2 +-
 tools/libxl/libxl_colo_save.c            |    2 +-
 tools/libxl/libxl_create.c               |  167 +++-
 tools/libxl/libxl_dom_save.c             |   55 +-
 tools/libxl/libxl_domain.c               |   41 +-
 tools/libxl/libxl_internal.h             |   79 +-
 tools/libxl/libxl_remus.c                |    2 +-
 tools/libxl/libxl_save_callout.c         |    3 +-
 tools/libxl/libxl_save_helper.c          |    7 +-
 tools/libxl/libxl_save_msgs_gen.pl       |   10 +-
 tools/libxl/libxl_sr_stream_format.h     |   13 +-
 tools/libxl/libxl_stream_read.c          |  136 +++-
 tools/libxl/libxl_stream_write.c         |  161 ++--
 tools/ocaml/libs/xl/xenlight_stubs.c     |    2 +-
 tools/xl/xl.h                            |    7 +-
 tools/xl/xl_cmdtable.c                   |   25 +-
 tools/xl/xl_migrate.c                    |   85 +-
 tools/xl/xl_vmcontrol.c                  |    8 +-
 35 files changed, 3144 insertions(+), 605 deletions(-)
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#1 lore raw

RFC PATCH 1/20 tools: rename COLO 'postcopy' to 'aftercopy'

The COLO xc domain save and restore procedures both make use of a 'postcopy' callback to defer part of each checkpoint operation to xl. In this context, the name 'postcopy' is meant as "the callback invoked immediately after this checkpoint's memory callback." This is an unfortunate name collision with the other common use of 'postcopy' in the context of live migration, where it is used to mean "a memory migration that permits the guest to execute at the destination before all of its memory is migrated by servicing accesses to unmigrated memory via a network page-fault."

Mechanically rename 'postcopy' -> 'aftercopy' to free up the postcopy namespace while preserving the original intent of the name in the COLO context.

No functional change.

---
 tools/libxc/include/xenguest.h     | 4 ++--
 tools/libxc/xc_sr_restore.c        | 4 ++--
 tools/libxc/xc_sr_save.c           | 4 ++--
 tools/libxl/libxl_colo_restore.c   | 2 +-
 tools/libxl/libxl_colo_save.c      | 2 +-
 tools/libxl/libxl_remus.c          | 2 +-
 tools/libxl/libxl_save_msgs_gen.pl | 2 +-
 7 files changed, 10 insertions(+), 10 deletions(-)
tools/libxc/include/xenguest.h +2 -2
index 40902ee..aa8cc8b 100644
@@ -53,7 +53,7 @@ struct save_callbacks {
      * xc_domain_save then flushes the output buffer, while the
      *  guest continues to run.
      */
-    int (*postcopy)(void* data);
+    int (*aftercopy)(void* data);
 
     /* Called after the memory checkpoint has been flushed
      * out into the network. Typical actions performed in this
@@ -115,7 +115,7 @@ struct restore_callbacks {
      * Callback function resumes the guest & the device model,
      * returns to xc_domain_restore.
      */
-    int (*postcopy)(void* data);
+    int (*aftercopy)(void* data);
 
     /* A checkpoint record has been found in the stream.
      * returns: */
tools/libxc/xc_sr_restore.c +2 -2
index 3549f0a..ee06b3d 100644
@@ -576,7 +576,7 @@ static int handle_checkpoint(struct xc_sr_context *ctx)
                                                 ctx->restore.callbacks->data);
 
         /* Resume secondary vm */
-        ret = ctx->restore.callbacks->postcopy(ctx->restore.callbacks->data);
+        ret = ctx->restore.callbacks->aftercopy(ctx->restore.callbacks->data);
         HANDLE_CALLBACK_RETURN_VALUE(ret);
 
         /* Wait for a new checkpoint */
@@ -855,7 +855,7 @@ int xc_domain_restore(xc_interface *xch, int io_fd, uint32_t dom,
     {
         /* this is COLO restore */
         assert(callbacks->suspend &&
-               callbacks->postcopy &&
+               callbacks->aftercopy &&
                callbacks->wait_checkpoint &&
                callbacks->restore_results);
     }
tools/libxc/xc_sr_save.c +2 -2
index f98c827..fc63a55 100644
@@ -863,7 +863,7 @@ static int save(struct xc_sr_context *ctx, uint16_t guest_type)
                 }
             }
 
-            rc = ctx->save.callbacks->postcopy(ctx->save.callbacks->data);
+            rc = ctx->save.callbacks->aftercopy(ctx->save.callbacks->data);
             if ( rc <= 0 )
                 goto err;
 
@@ -951,7 +951,7 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
     if ( hvm )
         assert(callbacks->switch_qemu_logdirty);
     if ( ctx.save.checkpointed )
-        assert(callbacks->checkpoint && callbacks->postcopy);
+        assert(callbacks->checkpoint && callbacks->aftercopy);
     if ( ctx.save.checkpointed == XC_MIG_STREAM_COLO )
         assert(callbacks->wait_checkpoint);
 
tools/libxl/libxl_colo_restore.c +1 -1
index 0c535bd..7d8f9ff 100644
@@ -246,7 +246,7 @@ void libxl__colo_restore_setup(libxl__egc *egc,
     if (init_dsps(&crcs->dsps))
         goto out;
 
-    callbacks->postcopy = libxl__colo_restore_domain_resume_callback;
+    callbacks->aftercopy = libxl__colo_restore_domain_resume_callback;
     callbacks->wait_checkpoint = libxl__colo_restore_domain_wait_checkpoint_callback;
     callbacks->suspend = libxl__colo_restore_domain_suspend_callback;
     callbacks->checkpoint = libxl__colo_restore_domain_checkpoint_callback;
tools/libxl/libxl_colo_save.c +1 -1
index f687d5a..5921196 100644
@@ -145,7 +145,7 @@ void libxl__colo_save_setup(libxl__egc *egc, libxl__colo_save_state *css)
 
     callbacks->suspend = libxl__colo_save_domain_suspend_callback;
     callbacks->checkpoint = libxl__colo_save_domain_checkpoint_callback;
-    callbacks->postcopy = libxl__colo_save_domain_resume_callback;
+    callbacks->aftercopy = libxl__colo_save_domain_resume_callback;
     callbacks->wait_checkpoint = libxl__colo_save_domain_wait_checkpoint_callback;
 
     libxl__checkpoint_devices_setup(egc, &dss->cds);
tools/libxl/libxl_remus.c +1 -1
index 29a4783..1453365 100644
@@ -110,7 +110,7 @@ void libxl__remus_setup(libxl__egc *egc, libxl__remus_state *rs)
     dss->sws.checkpoint_callback = remus_checkpoint_stream_written;
 
     callbacks->suspend = libxl__remus_domain_suspend_callback;
-    callbacks->postcopy = libxl__remus_domain_resume_callback;
+    callbacks->aftercopy = libxl__remus_domain_resume_callback;
     callbacks->checkpoint = libxl__remus_domain_save_checkpoint_callback;
 
     libxl__checkpoint_devices_setup(egc, cds);
tools/libxl/libxl_save_msgs_gen.pl +1 -1
index 3ae7373..27845bb 100755
@@ -24,7 +24,7 @@ our @msgs = (
                                                 'unsigned long', 'done',
                                                 'unsigned long', 'total'] ],
     [  3, 'srcxA',  "suspend", [] ],
-    [  4, 'srcxA',  "postcopy", [] ],
+    [  4, 'srcxA',  "aftercopy", [] ],
     [  5, 'srcxA',  "checkpoint", [] ],
     [  6, 'srcxA',  "wait_checkpoint", [] ],
     [  7, 'scxA',   "switch_qemu_logdirty",  [qw(int domid
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#2 lore raw

Re: [PATCH RFC 01/20] tools: rename COLO 'postcopy' to 'aftercopy'

Cc Chen

Quoted 146 lines · Joshua Otto

The COLO xc domain save and restore procedures both make use of a 'postcopy' callback to defer part of each checkpoint operation to xl. In this context, the name 'postcopy' is meant as "the callback invoked immediately after this checkpoint's memory callback." This is an unfortunate name collision with the other common use of 'postcopy' in the context of live migration, where it is used to mean "a memory migration that permits the guest to execute at the destination before all of its memory is migrated by servicing accesses to unmigrated memory via a network page-fault."

Mechanically rename 'postcopy' -> 'aftercopy' to free up the postcopy namespace while preserving the original intent of the name in the COLO context.

No functional change.

---
 tools/libxc/include/xenguest.h     | 4 ++--
 tools/libxc/xc_sr_restore.c        | 4 ++--
 tools/libxc/xc_sr_save.c           | 4 ++--
 tools/libxl/libxl_colo_restore.c   | 2 +-
 tools/libxl/libxl_colo_save.c      | 2 +-
 tools/libxl/libxl_remus.c          | 2 +-
 tools/libxl/libxl_save_msgs_gen.pl | 2 +-
 7 files changed, 10 insertions(+), 10 deletions(-)
tools/libxc/include/xenguest.h +2 -2
index 40902ee..aa8cc8b 100644
@@ -53,7 +53,7 @@ struct save_callbacks {
      * xc_domain_save then flushes the output buffer, while the
      *  guest continues to run.
      */
-    int (*postcopy)(void* data);
+    int (*aftercopy)(void* data);
 
     /* Called after the memory checkpoint has been flushed
      * out into the network. Typical actions performed in this
@@ -115,7 +115,7 @@ struct restore_callbacks {
      * Callback function resumes the guest & the device model,
      * returns to xc_domain_restore.
      */
-    int (*postcopy)(void* data);
+    int (*aftercopy)(void* data);
 
     /* A checkpoint record has been found in the stream.
      * returns: */
tools/libxc/xc_sr_restore.c +2 -2
index 3549f0a..ee06b3d 100644
@@ -576,7 +576,7 @@ static int handle_checkpoint(struct xc_sr_context *ctx)
                                                 ctx->restore.callbacks->data);
 
         /* Resume secondary vm */
-        ret = ctx->restore.callbacks->postcopy(ctx->restore.callbacks->data);
+        ret = ctx->restore.callbacks->aftercopy(ctx->restore.callbacks->data);
         HANDLE_CALLBACK_RETURN_VALUE(ret);
 
         /* Wait for a new checkpoint */
@@ -855,7 +855,7 @@ int xc_domain_restore(xc_interface *xch, int io_fd, uint32_t dom,
     {
         /* this is COLO restore */
         assert(callbacks->suspend &&
-               callbacks->postcopy &&
+               callbacks->aftercopy &&
                callbacks->wait_checkpoint &&
                callbacks->restore_results);
     }
tools/libxc/xc_sr_save.c +2 -2
index f98c827..fc63a55 100644
@@ -863,7 +863,7 @@ static int save(struct xc_sr_context *ctx, uint16_t guest_type)
                 }
             }
 
-            rc = ctx->save.callbacks->postcopy(ctx->save.callbacks->data);
+            rc = ctx->save.callbacks->aftercopy(ctx->save.callbacks->data);
             if ( rc <= 0 )
                 goto err;
 
@@ -951,7 +951,7 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
     if ( hvm )
         assert(callbacks->switch_qemu_logdirty);
     if ( ctx.save.checkpointed )
-        assert(callbacks->checkpoint && callbacks->postcopy);
+        assert(callbacks->checkpoint && callbacks->aftercopy);
     if ( ctx.save.checkpointed == XC_MIG_STREAM_COLO )
         assert(callbacks->wait_checkpoint);
 
tools/libxl/libxl_colo_restore.c +1 -1
index 0c535bd..7d8f9ff 100644
@@ -246,7 +246,7 @@ void libxl__colo_restore_setup(libxl__egc *egc,
     if (init_dsps(&crcs->dsps))
         goto out;
 
-    callbacks->postcopy = libxl__colo_restore_domain_resume_callback;
+    callbacks->aftercopy = libxl__colo_restore_domain_resume_callback;
     callbacks->wait_checkpoint = libxl__colo_restore_domain_wait_checkpoint_callback;
     callbacks->suspend = libxl__colo_restore_domain_suspend_callback;
     callbacks->checkpoint = libxl__colo_restore_domain_checkpoint_callback;
tools/libxl/libxl_colo_save.c +1 -1
index f687d5a..5921196 100644
@@ -145,7 +145,7 @@ void libxl__colo_save_setup(libxl__egc *egc, libxl__colo_save_state *css)
 
     callbacks->suspend = libxl__colo_save_domain_suspend_callback;
     callbacks->checkpoint = libxl__colo_save_domain_checkpoint_callback;
-    callbacks->postcopy = libxl__colo_save_domain_resume_callback;
+    callbacks->aftercopy = libxl__colo_save_domain_resume_callback;
     callbacks->wait_checkpoint = libxl__colo_save_domain_wait_checkpoint_callback;
 
     libxl__checkpoint_devices_setup(egc, &dss->cds);
tools/libxl/libxl_remus.c +1 -1
index 29a4783..1453365 100644
@@ -110,7 +110,7 @@ void libxl__remus_setup(libxl__egc *egc, libxl__remus_state *rs)
     dss->sws.checkpoint_callback = remus_checkpoint_stream_written;
 
     callbacks->suspend = libxl__remus_domain_suspend_callback;
-    callbacks->postcopy = libxl__remus_domain_resume_callback;
+    callbacks->aftercopy = libxl__remus_domain_resume_callback;
     callbacks->checkpoint = libxl__remus_domain_save_checkpoint_callback;
 
     libxl__checkpoint_devices_setup(egc, cds);
tools/libxl/libxl_save_msgs_gen.pl +1 -1
index 3ae7373..27845bb 100755
@@ -24,7 +24,7 @@ our @msgs = (
                                                 'unsigned long', 'done',
                                                 'unsigned long', 'total'] ],
     [  3, 'srcxA',  "suspend", [] ],
-    [  4, 'srcxA',  "postcopy", [] ],
+    [  4, 'srcxA',  "aftercopy", [] ],
     [  5, 'srcxA',  "checkpoint", [] ],
     [  6, 'srcxA',  "wait_checkpoint", [] ],
     [  7, 'scxA',   "switch_qemu_logdirty",  [qw(int domid
Signature · 1 line
2.7.4

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

Acked-by
#3 lore raw

Re: [PATCH RFC 01/20] tools: rename COLO 'postcopy' to 'aftercopy'

Quoted 18 lines · Wei Liu

Cc Chen

Quoted 15 lines · Joshua Otto

The COLO xc domain save and restore procedures both make use of a 'postcopy' callback to defer part of each checkpoint operation to xl. In this context, the name 'postcopy' is meant as "the callback invoked immediately after this checkpoint's memory callback." This is an unfortunate name collision with the other common use of 'postcopy' in the context of live migration, where it is used to mean "a memory migration that permits the guest to execute at the destination before all of its memory is migrated by servicing accesses to unmigrated memory via a network page-fault."

Mechanically rename 'postcopy' -> 'aftercopy' to free up the postcopy namespace while preserving the original intent of the name in the COLO context.

No functional change.

Quoted 134 lines
Quoted 131 lines
---
  tools/libxc/include/xenguest.h     | 4 ++--
  tools/libxc/xc_sr_restore.c        | 4 ++--
  tools/libxc/xc_sr_save.c           | 4 ++--
  tools/libxl/libxl_colo_restore.c   | 2 +-
  tools/libxl/libxl_colo_save.c      | 2 +-
  tools/libxl/libxl_remus.c          | 2 +-
  tools/libxl/libxl_save_msgs_gen.pl | 2 +-
  7 files changed, 10 insertions(+), 10 deletions(-)
tools/libxc/include/xenguest.h +2 -2
index 40902ee..aa8cc8b 100644
@@ -53,7 +53,7 @@ struct save_callbacks {
       * xc_domain_save then flushes the output buffer, while the
       *  guest continues to run.
       */
-    int (*postcopy)(void* data);
+    int (*aftercopy)(void* data);
 
      /* Called after the memory checkpoint has been flushed
       * out into the network. Typical actions performed in this
@@ -115,7 +115,7 @@ struct restore_callbacks {
       * Callback function resumes the guest & the device model,
       * returns to xc_domain_restore.
       */
-    int (*postcopy)(void* data);
+    int (*aftercopy)(void* data);
 
      /* A checkpoint record has been found in the stream.
       * returns: */
tools/libxc/xc_sr_restore.c +2 -2
index 3549f0a..ee06b3d 100644
@@ -576,7 +576,7 @@ static int handle_checkpoint(struct xc_sr_context *ctx)
                                                  ctx->restore.callbacks->data);
 
          /* Resume secondary vm */
-        ret = ctx->restore.callbacks->postcopy(ctx->restore.callbacks->data);
+        ret = ctx->restore.callbacks->aftercopy(ctx->restore.callbacks->data);
          HANDLE_CALLBACK_RETURN_VALUE(ret);
 
          /* Wait for a new checkpoint */
@@ -855,7 +855,7 @@ int xc_domain_restore(xc_interface *xch, int io_fd, uint32_t dom,
      {
          /* this is COLO restore */
          assert(callbacks->suspend &&
-               callbacks->postcopy &&
+               callbacks->aftercopy &&
                 callbacks->wait_checkpoint &&
                 callbacks->restore_results);
      }
tools/libxc/xc_sr_save.c +2 -2
index f98c827..fc63a55 100644
@@ -863,7 +863,7 @@ static int save(struct xc_sr_context *ctx, uint16_t guest_type)
                  }
              }
 
-            rc = ctx->save.callbacks->postcopy(ctx->save.callbacks->data);
+            rc = ctx->save.callbacks->aftercopy(ctx->save.callbacks->data);
              if ( rc <= 0 )
                  goto err;
 
@@ -951,7 +951,7 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
      if ( hvm )
          assert(callbacks->switch_qemu_logdirty);
      if ( ctx.save.checkpointed )
-        assert(callbacks->checkpoint && callbacks->postcopy);
+        assert(callbacks->checkpoint && callbacks->aftercopy);
      if ( ctx.save.checkpointed == XC_MIG_STREAM_COLO )
          assert(callbacks->wait_checkpoint);
 
tools/libxl/libxl_colo_restore.c +1 -1
index 0c535bd..7d8f9ff 100644
@@ -246,7 +246,7 @@ void libxl__colo_restore_setup(libxl__egc *egc,
      if (init_dsps(&crcs->dsps))
          goto out;
 
-    callbacks->postcopy = libxl__colo_restore_domain_resume_callback;
+    callbacks->aftercopy = libxl__colo_restore_domain_resume_callback;
      callbacks->wait_checkpoint = libxl__colo_restore_domain_wait_checkpoint_callback;
      callbacks->suspend = libxl__colo_restore_domain_suspend_callback;
      callbacks->checkpoint = libxl__colo_restore_domain_checkpoint_callback;
tools/libxl/libxl_colo_save.c +1 -1
index f687d5a..5921196 100644
@@ -145,7 +145,7 @@ void libxl__colo_save_setup(libxl__egc *egc, libxl__colo_save_state *css)
 
      callbacks->suspend = libxl__colo_save_domain_suspend_callback;
      callbacks->checkpoint = libxl__colo_save_domain_checkpoint_callback;
-    callbacks->postcopy = libxl__colo_save_domain_resume_callback;
+    callbacks->aftercopy = libxl__colo_save_domain_resume_callback;
      callbacks->wait_checkpoint = libxl__colo_save_domain_wait_checkpoint_callback;
 
      libxl__checkpoint_devices_setup(egc, &dss->cds);
tools/libxl/libxl_remus.c +1 -1
index 29a4783..1453365 100644
@@ -110,7 +110,7 @@ void libxl__remus_setup(libxl__egc *egc, libxl__remus_state *rs)
      dss->sws.checkpoint_callback = remus_checkpoint_stream_written;
 
      callbacks->suspend = libxl__remus_domain_suspend_callback;
-    callbacks->postcopy = libxl__remus_domain_resume_callback;
+    callbacks->aftercopy = libxl__remus_domain_resume_callback;
      callbacks->checkpoint = libxl__remus_domain_save_checkpoint_callback;
 
      libxl__checkpoint_devices_setup(egc, cds);
tools/libxl/libxl_save_msgs_gen.pl +1 -1
index 3ae7373..27845bb 100755
@@ -24,7 +24,7 @@ our @msgs = (
                                                  'unsigned long', 'done',
                                                  'unsigned long', 'total'] ],
      [  3, 'srcxA',  "suspend", [] ],
-    [  4, 'srcxA',  "postcopy", [] ],
+    [  4, 'srcxA',  "aftercopy", [] ],
      [  5, 'srcxA',  "checkpoint", [] ],
      [  6, 'srcxA',  "wait_checkpoint", [] ],
      [  7, 'scxA',   "switch_qemu_logdirty",  [qw(int domid
Signature · 1 line
2.7.4

.

Signature · 10 lines
Thanks
Zhang Chen




_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#4 lore raw

RFC PATCH 2/20 libxc/xc_sr: parameterise write_record() on fd

In reply to Joshua Otto

Right now, write_split_record() - which is delegated to by write_record() - implicitly writes to ctx->fd. This means it can't be used with the restore context's send_back_fd, which is unhandy.

Add an 'fd' parameter to both write_record() and write_split_record(), and mechanically update all existing callsites to pass ctx->fd for it.

No functional change.

---
 tools/libxc/xc_sr_common.c       |  6 +++---
 tools/libxc/xc_sr_common.h       |  8 ++++----
 tools/libxc/xc_sr_common_x86.c   |  2 +-
 tools/libxc/xc_sr_save.c         |  6 +++---
 tools/libxc/xc_sr_save_x86_hvm.c |  5 +++--
 tools/libxc/xc_sr_save_x86_pv.c  | 17 +++++++++--------
 6 files changed, 23 insertions(+), 21 deletions(-)
tools/libxc/xc_sr_common.c +3 -3
index 48fa676..c1babf6 100644
@@ -52,8 +52,8 @@ 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)
+int write_split_record(struct xc_sr_context *ctx, int fd,
+                       struct xc_sr_record *rec, void *buf, size_t sz)
 {
     static const char zeroes[(1u << REC_ALIGN_ORDER) - 1] = { 0 };
 
@@ -81,7 +81,7 @@ int write_split_record(struct xc_sr_context *ctx, struct xc_sr_record *rec,
     if ( sz )
         assert(buf);
 
-    if ( writev_exact(ctx->fd, parts, ARRAY_SIZE(parts)) )
+    if ( writev_exact(fd, parts, ARRAY_SIZE(parts)) )
         goto err;
 
     return 0;
tools/libxc/xc_sr_common.h +4 -4
index a83f22a..2f33ccc 100644
@@ -361,8 +361,8 @@ struct xc_sr_record
  *
  * Returns 0 on success and non0 on failure.
  */
-int write_split_record(struct xc_sr_context *ctx, struct xc_sr_record *rec,
-                       void *buf, size_t sz);
+int write_split_record(struct xc_sr_context *ctx, int fd,
+                       struct xc_sr_record *rec, void *buf, size_t sz);
 
 /*
  * Writes a record to the stream, applying correct padding where appropriate.
@@ -371,10 +371,10 @@ int write_split_record(struct xc_sr_context *ctx, struct xc_sr_record *rec,
  *
  * Returns 0 on success and non0 on failure.
  */
-static inline int write_record(struct xc_sr_context *ctx,
+static inline int write_record(struct xc_sr_context *ctx, int fd,
                                struct xc_sr_record *rec)
 {
-    return write_split_record(ctx, rec, NULL, 0);
+    return write_split_record(ctx, fd, rec, NULL, 0);
 }
 
 /*
tools/libxc/xc_sr_common_x86.c +1 -1
index 98f1cef..7b3dd50 100644
@@ -18,7 +18,7 @@ int write_tsc_info(struct xc_sr_context *ctx)
         return -1;
     }
 
-    return write_record(ctx, &rec);
+    return write_record(ctx, ctx->fd, &rec);
 }
 
 int handle_tsc_info(struct xc_sr_context *ctx, struct xc_sr_record *rec)
tools/libxc/xc_sr_save.c +3 -3
index fc63a55..61fc4a4 100644
@@ -53,7 +53,7 @@ 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);
+    return write_record(ctx, ctx->fd, &end);
 }
 
 /*
@@ -63,7 +63,7 @@ static int write_checkpoint_record(struct xc_sr_context *ctx)
 {
     struct xc_sr_record checkpoint = { REC_TYPE_CHECKPOINT, 0, NULL };
 
-    return write_record(ctx, &checkpoint);
+    return write_record(ctx, ctx->fd, &checkpoint);
 }
 
 /*
@@ -646,7 +646,7 @@ static int verify_frames(struct xc_sr_context *ctx)
 
     DPRINTF("Enabling verify mode");
 
-    rc = write_record(ctx, &rec);
+    rc = write_record(ctx, ctx->fd, &rec);
     if ( rc )
         goto out;
 
tools/libxc/xc_sr_save_x86_hvm.c +3 -2
index e485928..ea4b780 100644
@@ -42,7 +42,7 @@ static int write_hvm_context(struct xc_sr_context *ctx)
     }
 
     hvm_rec.length = hvm_buf_size;
-    rc = write_record(ctx, &hvm_rec);
+    rc = write_record(ctx, ctx->fd, &hvm_rec);
     if ( rc < 0 )
     {
         PERROR("error write HVM_CONTEXT record");
@@ -112,7 +112,8 @@ static int write_hvm_params(struct xc_sr_context *ctx)
         }
     }
 
-    rc = write_split_record(ctx, &rec, entries, hdr.count * sizeof(*entries));
+    rc = write_split_record(ctx, ctx->fd, &rec, entries,
+                            hdr.count * sizeof(*entries));
     if ( rc )
         PERROR("Failed to write HVM_PARAMS record");
 
tools/libxc/xc_sr_save_x86_pv.c +9 -8
index f218d17..2b2c050 100644
@@ -571,9 +571,9 @@ static int write_one_vcpu_basic(struct xc_sr_context *ctx, uint32_t id)
     }
 
     if ( ctx->x86_pv.width == 8 )
-        rc = write_split_record(ctx, &rec, &vcpu, sizeof(vcpu.x64));
+        rc = write_split_record(ctx, ctx->fd, &rec, &vcpu, sizeof(vcpu.x64));
     else
-        rc = write_split_record(ctx, &rec, &vcpu, sizeof(vcpu.x32));
+        rc = write_split_record(ctx, ctx->fd, &rec, &vcpu, sizeof(vcpu.x32));
 
  err:
     return rc;
@@ -609,7 +609,7 @@ static int write_one_vcpu_extended(struct xc_sr_context *ctx, uint32_t id)
         return -1;
     }
 
-    return write_split_record(ctx, &rec, &domctl.u.ext_vcpucontext,
+    return write_split_record(ctx, ctx->fd, &rec, &domctl.u.ext_vcpucontext,
                               domctl.u.ext_vcpucontext.size);
 }
 
@@ -664,7 +664,8 @@ static int write_one_vcpu_xsave(struct xc_sr_context *ctx, uint32_t id)
         goto err;
     }
 
-    rc = write_split_record(ctx, &rec, buffer, domctl.u.vcpuextstate.size);
+    rc = write_split_record(ctx, ctx->fd, &rec, buffer,
+                            domctl.u.vcpuextstate.size);
     if ( rc )
         goto err;
 
@@ -730,7 +731,7 @@ static int write_one_vcpu_msrs(struct xc_sr_context *ctx, uint32_t id)
         goto err;
     }
 
-    rc = write_split_record(ctx, &rec, buffer,
+    rc = write_split_record(ctx, ctx->fd, &rec, buffer,
                             domctl.u.vcpu_msrs.msr_count *
                             sizeof(xen_domctl_vcpu_msr_t));
     if ( rc )
@@ -805,7 +806,7 @@ static int write_x86_pv_info(struct xc_sr_context *ctx)
             .data = &info
         };
 
-    return write_record(ctx, &rec);
+    return write_record(ctx, ctx->fd, &rec);
 }
 
 /*
@@ -846,7 +847,7 @@ static int write_x86_pv_p2m_frames(struct xc_sr_context *ctx)
     else
         data = (uint64_t *)ctx->x86_pv.p2m_pfns;
 
-    rc = write_split_record(ctx, &rec, data, datasz);
+    rc = write_split_record(ctx, ctx->fd, &rec, data, datasz);
 
     if ( data != (uint64_t *)ctx->x86_pv.p2m_pfns )
         free(data);
@@ -866,7 +867,7 @@ static int write_shared_info(struct xc_sr_context *ctx)
         .data = ctx->x86_pv.shinfo,
     };
 
-    return write_record(ctx, &rec);
+    return write_record(ctx, ctx->fd, &rec);
 }
 
 /*
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
Reviewed-by on v1 2/20
#5 lore raw

Re: [PATCH RFC 02/20] libxc/xc_sr: parameterise write_record() on fd

Quoted 3 lines · Joshua Otto

Right now, write_split_record() - which is delegated to by write_record() - implicitly writes to ctx->fd. This means it can't be used with the restore context's send_back_fd, which is unhandy.

Unhelpful?

Quoted 7 lines

Add an 'fd' parameter to both write_record() and write_split_record(), and mechanically update all existing callsites to pass ctx->fd for it.

No functional change.

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

Acked-by on v1 2/20
#6 lore raw

Re: [PATCH RFC 02/20] libxc/xc_sr: parameterise write_record() on fd

In reply to Joshua Otto
Quoted 10 lines · Joshua Otto

Right now, write_split_record() - which is delegated to by write_record() - implicitly writes to ctx->fd. This means it can't be used with the restore context's send_back_fd, which is unhandy.

Add an 'fd' parameter to both write_record() and write_split_record(), and mechanically update all existing callsites to pass ctx->fd for it.

No functional change.

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

#7 lore raw

RFC PATCH 3/20 libxc/xc_sr_restore.c: use write_record() in send_checkpoint_dirty_pfn_list()

In reply to Joshua Otto

Teach send_checkpoint_dirty_pfn_list() to use write_record()'s new fd parameter, avoiding the need for a manual writev().

No functional change.

---
 tools/libxc/xc_sr_restore.c | 27 ++++-----------------------
 1 file changed, 4 insertions(+), 23 deletions(-)
tools/libxc/xc_sr_restore.c +4 -23
index ee06b3d..481a904 100644
@@ -420,7 +420,6 @@ static int send_checkpoint_dirty_pfn_list(struct xc_sr_context *ctx)
     int rc = -1;
     unsigned count, written;
     uint64_t i, *pfns = NULL;
-    struct iovec *iov = NULL;
     xc_shadow_op_stats_t stats = { 0, ctx->restore.p2m_size };
     struct xc_sr_record rec =
     {
@@ -467,35 +466,17 @@ static int send_checkpoint_dirty_pfn_list(struct xc_sr_context *ctx)
         pfns[written++] = i;
     }
 
-    /* iovec[] for writev(). */
-    iov = malloc(3 * sizeof(*iov));
-    if ( !iov )
-    {
-        ERROR("Unable to allocate memory for sending dirty bitmap");
-        goto err;
-    }
-
+    rec.data = pfns;
     rec.length = count * sizeof(*pfns);
 
-    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 = pfns;
-    iov[2].iov_len = count * sizeof(*pfns);
-
-    if ( writev_exact(ctx->restore.send_back_fd, iov, 3) )
-    {
-        PERROR("Failed to write dirty bitmap to stream");
+    rc = write_record(ctx, ctx->restore.send_back_fd, &rec);
+    if ( rc )
         goto err;
-    }
 
     rc = 0;
+
  err:
     free(pfns);
-    free(iov);
     return rc;
 }
 
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
Reviewed-by on v1 3/20
#8 lore raw

Re: [PATCH RFC 03/20] libxc/xc_sr_restore.c: use write_record() in send_checkpoint_dirty_pfn_list()

Quoted 6 lines · Joshua Otto

Teach send_checkpoint_dirty_pfn_list() to use write_record()'s new fd parameter, avoiding the need for a manual writev().

No functional change.

Hmm - I could have sworn I objected to the patch which added this code in the first place, for its opencoded use of writev().

Oh well, thanks for fixing it.

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

Acked-by on v1 3/20
#9 lore raw

Re: [PATCH RFC 03/20] libxc/xc_sr_restore.c: use write_record() in send_checkpoint_dirty_pfn_list()

In reply to Joshua Otto
Quoted 6 lines · Joshua Otto

Teach send_checkpoint_dirty_pfn_list() to use write_record()'s new fd parameter, avoiding the need for a manual writev().

No functional change.

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

#10 lore raw

RFC PATCH 4/20 libxc/xc_sr_save.c: add WRITE_TRIVIAL_RECORD_FN()

In reply to Joshua Otto

Writing the libxc save stream requires writing a few 'trivial' records, consisting only of a header with a particular type. As a readability aid, it's nice to have obviously-named functions that write these sorts of records into the stream - for example, the first such function was write_end_record(), which reads much more pleasantly at its call-site than write_generic_record(REC_TYPE_END) would. However, it's tedious and error-prone to copy-paste the generic body of such a function for each new trivial record type.

Add a helper macro that takes a name base and a record type and declares the corresponding trivial record write function. Use this to re-define the two existing trivial record functions, write_end_record() and write_checkpoint_record().

No functional change.

---
 tools/libxc/xc_sr_save.c | 26 ++++++++++----------------
 1 file changed, 10 insertions(+), 16 deletions(-)
tools/libxc/xc_sr_save.c +10 -16
index 61fc4a4..86f6903 100644
@@ -47,24 +47,18 @@ static int write_headers(struct xc_sr_context *ctx, uint16_t guest_type)
 }
 
 /*
- * Writes an END record into the stream.
+ * Declares a helper function to write an empty record of a particular type.
  */
-static int write_end_record(struct xc_sr_context *ctx)
-{
-    struct xc_sr_record end = { REC_TYPE_END, 0, NULL };
-
-    return write_record(ctx, ctx->fd, &end);
-}
-
-/*
- * Writes a CHECKPOINT record into the stream.
- */
-static int write_checkpoint_record(struct xc_sr_context *ctx)
-{
-    struct xc_sr_record checkpoint = { REC_TYPE_CHECKPOINT, 0, NULL };
+#define WRITE_TRIVIAL_RECORD_FN(name, type)                         \
+    static int write_ ## name ## _record(struct xc_sr_context *ctx) \
+    {                                                               \
+        struct xc_sr_record name = { (type), 0, NULL };             \
+                                                                    \
+        return write_record(ctx, ctx->fd, &name);                   \
+    }
 
-    return write_record(ctx, ctx->fd, &checkpoint);
-}
+WRITE_TRIVIAL_RECORD_FN(end,                 REC_TYPE_END);
+WRITE_TRIVIAL_RECORD_FN(checkpoint,          REC_TYPE_CHECKPOINT);
 
 /*
  * Writes a batch of memory as a PAGE_DATA record into the stream.  The batch
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#11 lore raw

Re: [PATCH RFC 04/20] libxc/xc_sr_save.c: add WRITE_TRIVIAL_RECORD_FN()

Quoted 9 lines · Joshua Otto

Writing the libxc save stream requires writing a few 'trivial' records, consisting only of a header with a particular type. As a readability aid, it's nice to have obviously-named functions that write these sorts of records into the stream - for example, the first such function was write_end_record(), which reads much more pleasantly at its call-site than write_generic_record(REC_TYPE_END) would. However, it's tedious and error-prone to copy-paste the generic body of such a function for each new trivial record type.

Quoted 8 lines

Add a helper macro that takes a name base and a record type and declares the corresponding trivial record write function. Use this to re-define the two existing trivial record functions, write_end_record() and write_checkpoint_record().

No functional change.

-1.

This hides the functions from tools like cscope, and makes the code harder to read. I also don't really buy the error prone argument.

If you do want to avoid opencoding different functions, how about

static int write_zerolength_record(uint32_t record_type)

and updating the existing callsites to be

write_zerolength_record(REC_TYPE_END); etc.

~Andrew

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

#12 lore raw

Re: [PATCH RFC 04/20] libxc/xc_sr_save.c: add WRITE_TRIVIAL_RECORD_FN()

Quoted 15 lines · Andrew Cooper
Quoted 14 lines · Joshua Otto

Writing the libxc save stream requires writing a few 'trivial' records, consisting only of a header with a particular type. As a readability aid, it's nice to have obviously-named functions that write these sorts of records into the stream - for example, the first such function was write_end_record(), which reads much more pleasantly at its call-site than write_generic_record(REC_TYPE_END) would. However, it's tedious and error-prone to copy-paste the generic body of such a function for each new trivial record type.

Add a helper macro that takes a name base and a record type and declares the corresponding trivial record write function. Use this to re-define the two existing trivial record functions, write_end_record() and write_checkpoint_record().

Quoted 8 lines
Quoted 3 lines

No functional change.

-1.

This hides the functions from tools like cscope, and makes the code harder to read. I also don't really buy the error prone argument.

Okay, fair enough.

Quoted 8 lines

If you do want to avoid opencoding different functions, how about

static int write_zerolength_record(uint32_t record_type)

and updating the existing callsites to be

write_zerolength_record(REC_TYPE_END); etc.

I really do prefer write_end_record() to write_some_record(REC_TYPE_END), visually. I'll fix up the later patches to add the corresponding functions without the macro.

Josh

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

#13 lore raw

RFC PATCH 5/20 libxc/xc_sr: factor out filter_pages()

In reply to Joshua Otto

When processing a PAGE_DATA record, the restore side needs to set the types of incoming pages using the appropriate restore op and filter the list of pfns in the record to the subset that are 'backed' - ie. accompanied by real backing data in the stream that needs to be filled in.

Both of these steps are also required when processing postcopy records, so factor it out into a common helper.

No functional change.

---
 tools/libxc/xc_sr_restore.c | 100 +++++++++++++++++++++++++++++++++-----------
 1 file changed, 75 insertions(+), 25 deletions(-)
tools/libxc/xc_sr_restore.c +75 -25
index 481a904..8574ee8 100644
@@ -194,6 +194,68 @@ int populate_pfns(struct xc_sr_context *ctx, unsigned count,
     return rc;
 }
 
+static void set_page_types(struct xc_sr_context *ctx, unsigned count,
+                           xen_pfn_t *pfns, uint32_t *types)
+{
+    unsigned i;
+
+    for ( i = 0; i < count; ++i )
+        ctx->restore.ops.set_page_type(ctx, pfns[i], types[i]);
+}
+
+/*
+ * Given count pfns and their types, allocate and fill in buffer bpfns with only
+ * those pfns that are 'backed' by real page data that needs to be migrated.
+ * The caller must later free() *bpfns.
+ *
+ * Returns 0 on success and non-0 on failure.  *bpfns can be free()ed even after
+ * failure.
+ */
+static int filter_pages(struct xc_sr_context *ctx,
+                        unsigned count,
+                        xen_pfn_t *pfns,
+                        uint32_t *types,
+                        /* OUT */ unsigned *nr_pages,
+                        /* OUT */ xen_pfn_t **bpfns)
+{
+    xc_interface *xch = ctx->xch;
+    unsigned i;
+
+    *nr_pages = 0;
+    *bpfns = malloc(count * sizeof(*bpfns));
+    if ( !(*bpfns) )
+    {
+        ERROR("Failed to allocate %zu bytes to process page data",
+              count * (sizeof(*bpfns)));
+        return -1;
+    }
+
+    for ( i = 0; i < count; ++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:
+
+            (*bpfns)[(*nr_pages)++] = pfns[i];
+            break;
+        }
+    }
+
+    return 0;
+}
+
 /*
  * 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
@@ -203,7 +265,7 @@ 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));
+    xen_pfn_t *mfns = NULL;
     int *map_errs = malloc(count * sizeof(*map_errs));
     int rc;
     void *mapping = NULL, *guest_page = NULL;
@@ -211,11 +273,11 @@ static int process_page_data(struct xc_sr_context *ctx, unsigned count,
         j,         /* j indexes the subset of pfns we decide to map. */
         nr_pages = 0;
 
-    if ( !mfns || !map_errs )
+    if ( !map_errs )
     {
         rc = -1;
         ERROR("Failed to allocate %zu bytes to process page data",
-              count * (sizeof(*mfns) + sizeof(*map_errs)));
+              count * sizeof(*map_errs));
         goto err;
     }
 
@@ -226,31 +288,19 @@ static int process_page_data(struct xc_sr_context *ctx, unsigned 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:
+    set_page_types(ctx, count, pfns, types);
 
-        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;
-        }
+    rc = filter_pages(ctx, count, pfns, types, &nr_pages, &mfns);
+    if ( rc )
+    {
+        ERROR("Failed to filter mfns for batch of %u pages", count);
+        goto err;
     }
 
+    /* Map physically-backed pfns ('bpfns') to their gmfns. */
+    for ( i = 0; i < nr_pages; ++i )
+        mfns[i] = ctx->restore.ops.pfn_to_gfn(ctx, mfns[i]);
+
     /* Nothing to do? */
     if ( nr_pages == 0 )
         goto done;
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#14 lore raw

Re: [PATCH RFC 05/20] libxc/xc_sr: factor out filter_pages()

tools/libxc/xc_sr_restore.c int populate_pfns(struct xc_sr_context *ctx, unsigned count, · line 200

Quoted 12 lines · Joshua Otto
tools/libxc/xc_sr_restore.c +4 -0
index 481a904..8574ee8 100644
@@ -194,6 +194,68 @@ int populate_pfns(struct xc_sr_context *ctx, unsigned count,
     return rc;
 }
 
+static void set_page_types(struct xc_sr_context *ctx, unsigned count,
+                           xen_pfn_t *pfns, uint32_t *types)
+{
+    unsigned i;

Please use unsigned int rather than just "unsigned" throughout.

Quoted 11 lines
tools/libxc/xc_sr_restore.c +11 -0
+
+    for ( i = 0; i < count; ++i )
+        ctx->restore.ops.set_page_type(ctx, pfns[i], types[i]);
+}
+
+/*
+ * Given count pfns and their types, allocate and fill in buffer bpfns with only
+ * those pfns that are 'backed' by real page data that needs to be migrated.
+ * The caller must later free() *bpfns.
+ *
+ * Returns 0 on success and non-0 on failure.  *bpfns can be free()ed even after

tools/libxc/xc_sr_restore.c int populate_pfns(struct xc_sr_context *ctx, unsigned count, · line 221

Quoted 10 lines
tools/libxc/xc_sr_restore.c +10 -0
+ * failure.
+ */
+static int filter_pages(struct xc_sr_context *ctx,
+                        unsigned count,
+                        xen_pfn_t *pfns,
+                        uint32_t *types,
+                        /* OUT */ unsigned *nr_pages,
+                        /* OUT */ xen_pfn_t **bpfns)
+{
+    xc_interface *xch = ctx->xch;

Pointers to arrays are very easy to get wrong in C. This code will be less error if you use

xen_pfn_t *_pfns; (variable name subject to improvement)

tools/libxc/xc_sr_restore.c int populate_pfns(struct xc_sr_context *ctx, unsigned count, · line 225

Quoted 4 lines
tools/libxc/xc_sr_restore.c +4 -0
+    unsigned i;
+
+    *nr_pages = 0;
+    *bpfns = malloc(count * sizeof(*bpfns));

_pfns = *bfns = malloc(...).

Then use _pfns in place of (*bpfns) everywhere else.

However, your sizeof has the wrong indirection. It works on x86 because xen_pfn_t is the same size as a pointer, but it will blow up on 32bit ARM, where a pointer is 4 bytes but xen_pfn_t is 8 bytes.

Quoted 37 lines
tools/libxc/xc_sr_restore.c +33 -0
+    if ( !(*bpfns) )
+    {
+        ERROR("Failed to allocate %zu bytes to process page data",
+              count * (sizeof(*bpfns)));
+        return -1;
+    }
+
+    for ( i = 0; i < count; ++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:
+
+            (*bpfns)[(*nr_pages)++] = pfns[i];
+            break;
+        }
+    }
+
+    return 0;
+}
+
 /*
  * 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

tools/libxc/xc_sr_restore.c static int process_page_data(struct xc_sr_context *ctx, unsigned count, · line 268

Quoted 5 lines
tools/libxc/xc_sr_restore.c +1 -1
@@ -203,7 +265,7 @@ 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));
+    xen_pfn_t *mfns = NULL;

This shows a naming bug, which is my fault. This should be named gfns, not mfns. (It inherits its name from the legacy migration code, but that was also wrong.)

Please correct it, either in this patch or another; the memory management terms are hard enough, even when all the code is correct.

~Andrew

Quoted 8 lines
tools/libxc/xc_sr_restore.c +0 -0
     int *map_errs = malloc(count * sizeof(*map_errs));
     int rc;
     void *mapping = NULL, *guest_page = NULL;
@@ -211,11 +273,11 @@ static int process_page_data(struct xc_sr_context *ctx, unsigned count,
         j,         /* j indexes the subset of pfns we decide to map. */
         nr_pages = 0;
 

tools/libxc/xc_sr_restore.c static int process_page_data(struct xc_sr_context *ctx, unsigned count, · line 283

Quoted 10 lines
tools/libxc/xc_sr_restore.c +2 -2
-    if ( !mfns || !map_errs )
+    if ( !map_errs )
     {
         rc = -1;
         ERROR("Failed to allocate %zu bytes to process page data",
-              count * (sizeof(*mfns) + sizeof(*map_errs)));
+              count * sizeof(*map_errs));
         goto err;
     }
 

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

#15 lore raw

Re: [PATCH RFC 05/20] libxc/xc_sr: factor out filter_pages()

Quoted 9 lines · Andrew Cooper
Quoted 8 lines · Joshua Otto
tools/libxc/xc_sr_restore.c +0 -0
index 481a904..8574ee8 100644
@@ -194,6 +194,68 @@ int populate_pfns(struct xc_sr_context *ctx, unsigned count,
     return rc;
 }
 
Quoted 6 lines

tools/libxc/xc_sr_restore.c int populate_pfns(struct xc_sr_context *ctx, unsigned count, · line 200

Quoted 4 lines
tools/libxc/xc_sr_restore.c +4 -0
+static void set_page_types(struct xc_sr_context *ctx, unsigned count,
+                           xen_pfn_t *pfns, uint32_t *types)
+{
+    unsigned i;

Please use unsigned int rather than just "unsigned" throughout.

Okay. (For what it's worth, I chose plain "unsigned" here for consistency with the rest of xc_sr_save/xc_sr_restore)

Quoted 32 lines
Quoted 11 lines
tools/libxc/xc_sr_restore.c +11 -0
+
+    for ( i = 0; i < count; ++i )
+        ctx->restore.ops.set_page_type(ctx, pfns[i], types[i]);
+}
+
+/*
+ * Given count pfns and their types, allocate and fill in buffer bpfns with only
+ * those pfns that are 'backed' by real page data that needs to be migrated.
+ * The caller must later free() *bpfns.
+ *
+ * Returns 0 on success and non-0 on failure.  *bpfns can be free()ed even after

tools/libxc/xc_sr_restore.c int populate_pfns(struct xc_sr_context *ctx, unsigned count, · line 221

Quoted 10 lines
tools/libxc/xc_sr_restore.c +10 -0
+ * failure.
+ */
+static int filter_pages(struct xc_sr_context *ctx,
+                        unsigned count,
+                        xen_pfn_t *pfns,
+                        uint32_t *types,
+                        /* OUT */ unsigned *nr_pages,
+                        /* OUT */ xen_pfn_t **bpfns)
+{
+    xc_interface *xch = ctx->xch;

Pointers to arrays are very easy to get wrong in C. This code will be less error if you use

xen_pfn_t *_pfns; (variable name subject to improvement)

tools/libxc/xc_sr_restore.c int populate_pfns(struct xc_sr_context *ctx, unsigned count, · line 225

Quoted 4 lines
tools/libxc/xc_sr_restore.c +4 -0
+    unsigned i;
+
+    *nr_pages = 0;
+    *bpfns = malloc(count * sizeof(*bpfns));
Quoted 7 lines

_pfns = *bfns = malloc(...).

Then use _pfns in place of (*bpfns) everywhere else.

However, your sizeof has the wrong indirection. It works on x86 because xen_pfn_t is the same size as a pointer, but it will blow up on 32bit ARM, where a pointer is 4 bytes but xen_pfn_t is 8 bytes.

Agh! Oh dear.

Quoted 47 lines
Quoted 37 lines
tools/libxc/xc_sr_restore.c +33 -0
+    if ( !(*bpfns) )
+    {
+        ERROR("Failed to allocate %zu bytes to process page data",
+              count * (sizeof(*bpfns)));
+        return -1;
+    }
+
+    for ( i = 0; i < count; ++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:
+
+            (*bpfns)[(*nr_pages)++] = pfns[i];
+            break;
+        }
+    }
+
+    return 0;
+}
+
 /*
  * 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

tools/libxc/xc_sr_restore.c static int process_page_data(struct xc_sr_context *ctx, unsigned count, · line 268

Quoted 5 lines
tools/libxc/xc_sr_restore.c +1 -1
@@ -203,7 +265,7 @@ 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));
+    xen_pfn_t *mfns = NULL;

This shows a naming bug, which is my fault. This should be named gfns, not mfns. (It inherits its name from the legacy migration code, but that was also wrong.)

Quoted 2 lines

Please correct it, either in this patch or another; the memory management terms are hard enough, even when all the code is correct.

Ahhhhhhh - I actually found this desperately confusing when trying to grok the code originally. Thanks for clearing that up!

Josh

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

#16 lore raw

RFC PATCH 6/20 libxc/xc_sr: factor helpers out of handle_page_data()

In reply to Joshua Otto

When processing a PAGE_DATA record, the restore code:
1) applies a number of sanity checks on the record's headers and size
2) decodes the list of packed page info into pfns and their types
3) using the pfn and type info, populates and fills the pages into the guest using process_page_data()

Steps 1) and 2) are also useful at various other stages of postcopy live migrations, so factor them into reusable helper routines.

No functional change.

---
 tools/libxc/xc_sr_common.c        | 38 +++++++++++++++-
 tools/libxc/xc_sr_common.h        | 10 +++++
 tools/libxc/xc_sr_restore.c       | 94 ++++++++++++++++++++++++---------------
 tools/libxc/xc_sr_save.c          |  2 +-
 tools/libxc/xc_sr_stream_format.h |  6 +--
 5 files changed, 109 insertions(+), 41 deletions(-)
tools/libxc/xc_sr_common.c +37 -1
index c1babf6..f443974 100644
@@ -140,13 +140,49 @@ int read_record(struct xc_sr_context *ctx, int fd, struct xc_sr_record *rec)
     return 0;
 };
 
+int validate_pages_record(struct xc_sr_context *ctx, struct xc_sr_record *rec,
+                          uint32_t expected_type)
+{
+    xc_interface *xch = ctx->xch;
+    struct xc_sr_rec_pages_header *pages = rec->data;
+
+    if ( rec->type != expected_type )
+    {
+        ERROR("%s record type expected, instead received record of type "
+              "%08x (%s)", rec_type_to_str(expected_type), rec->type,
+              rec_type_to_str(rec->type));
+        return -1;
+    }
+    else if ( rec->length < sizeof(*pages) )
+    {
+        ERROR("%s record truncated: length %u, min %zu",
+              rec_type_to_str(rec->type), rec->length, sizeof(*pages));
+        return -1;
+    }
+    else if ( pages->count < 1 )
+    {
+        ERROR("Expected at least 1 pfn in %s record",
+              rec_type_to_str(rec->type));
+        return -1;
+    }
+    else if ( rec->length < sizeof(*pages) + (pages->count * sizeof(uint64_t)) )
+    {
+        ERROR("%s record (length %u) too short to contain %u"
+              " pfns worth of information", rec_type_to_str(rec->type),
+              rec->length, pages->count);
+        return -1;
+    }
+
+    return 0;
+}
+
 static void __attribute__((unused)) build_assertions(void)
 {
     BUILD_BUG_ON(sizeof(struct xc_sr_ihdr) != 24);
     BUILD_BUG_ON(sizeof(struct xc_sr_dhdr) != 16);
     BUILD_BUG_ON(sizeof(struct xc_sr_rhdr) != 8);
 
-    BUILD_BUG_ON(sizeof(struct xc_sr_rec_page_data_header)  != 8);
+    BUILD_BUG_ON(sizeof(struct xc_sr_rec_pages_header)      != 8);
     BUILD_BUG_ON(sizeof(struct xc_sr_rec_x86_pv_info)       != 8);
     BUILD_BUG_ON(sizeof(struct xc_sr_rec_x86_pv_p2m_frames) != 8);
     BUILD_BUG_ON(sizeof(struct xc_sr_rec_x86_pv_vcpu_hdr)   != 8);
tools/libxc/xc_sr_common.h +10 -0
index 2f33ccc..b1aa88e 100644
@@ -392,6 +392,16 @@ static inline int write_record(struct xc_sr_context *ctx, int fd,
 int read_record(struct xc_sr_context *ctx, int fd, struct xc_sr_record *rec);
 
 /*
+ * Given a record of one of the page data types, validate it by:
+ * - checking its actual type against its specific expected type
+ * - sanity checking its actual length against its claimed length
+ *
+ * Returns 0 on success and non-0 on failure.
+ */
+int validate_pages_record(struct xc_sr_context *ctx, struct xc_sr_record *rec,
+                          uint32_t expected_type);
+
+/*
  * 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.
tools/libxc/xc_sr_restore.c +58 -36

125 lines not on this page · raw message

tools/libxc/xc_sr_save.c +1 -1
index 86f6903..797aec5 100644
@@ -83,7 +83,7 @@ static int write_batch(struct xc_sr_context *ctx)
     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_rec_pages_header hdr = { 0 };
     struct xc_sr_record rec =
     {
         .type = REC_TYPE_PAGE_DATA,
tools/libxc/xc_sr_stream_format.h +3 -3
index 3291b25..32400b2 100644
@@ -80,15 +80,15 @@ struct xc_sr_rhdr
 #define REC_TYPE_OPTIONAL             0x80000000U
 
 /* PAGE_DATA */
-struct xc_sr_rec_page_data_header
+struct xc_sr_rec_pages_header
 {
     uint32_t count;
     uint32_t _res1;
     uint64_t pfn[0];
 };
 
-#define PAGE_DATA_PFN_MASK  0x000fffffffffffffULL
-#define PAGE_DATA_TYPE_MASK 0xf000000000000000ULL
+#define REC_PFINFO_PFN_MASK  0x000fffffffffffffULL
+#define REC_PFINFO_TYPE_MASK 0xf000000000000000ULL
 
 /* X86_PV_INFO */
 struct xc_sr_rec_x86_pv_info
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#17 lore raw

Re: [PATCH RFC 06/20] libxc/xc_sr: factor helpers out of handle_page_data()

Quoted 13 lines · Joshua Otto
tools/libxc/xc_sr_stream_format.h +1 -1
index 3291b25..32400b2 100644
@@ -80,15 +80,15 @@ struct xc_sr_rhdr
 #define REC_TYPE_OPTIONAL             0x80000000U
 
 /* PAGE_DATA */
-struct xc_sr_rec_page_data_header
+struct xc_sr_rec_pages_header
 {
     uint32_t count;
     uint32_t _res1;

tools/libxc/xc_sr_stream_format.h struct xc_sr_rhdr · line 94

Quoted 10 lines
tools/libxc/xc_sr_stream_format.h +2 -2
     uint64_t pfn[0];
 };
 
-#define PAGE_DATA_PFN_MASK  0x000fffffffffffffULL
-#define PAGE_DATA_TYPE_MASK 0xf000000000000000ULL
+#define REC_PFINFO_PFN_MASK  0x000fffffffffffffULL
+#define REC_PFINFO_TYPE_MASK 0xf000000000000000ULL
 
 /* X86_PV_INFO */
 struct xc_sr_rec_x86_pv_info

What are the purposes of these name changes?

~Andrew

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

#18 lore raw

Re: [PATCH RFC 06/20] libxc/xc_sr: factor helpers out of handle_page_data()

Quoted 22 lines · Andrew Cooper
Quoted 21 lines · Joshua Otto
tools/libxc/xc_sr_stream_format.h +3 -3
index 3291b25..32400b2 100644
@@ -80,15 +80,15 @@ struct xc_sr_rhdr
 #define REC_TYPE_OPTIONAL             0x80000000U
 
 /* PAGE_DATA */
-struct xc_sr_rec_page_data_header
+struct xc_sr_rec_pages_header
 {
     uint32_t count;
     uint32_t _res1;
     uint64_t pfn[0];
 };
 
-#define PAGE_DATA_PFN_MASK  0x000fffffffffffffULL
-#define PAGE_DATA_TYPE_MASK 0xf000000000000000ULL
+#define REC_PFINFO_PFN_MASK  0x000fffffffffffffULL
+#define REC_PFINFO_TYPE_MASK 0xf000000000000000ULL
 
Quoted 4 lines

tools/libxc/xc_sr_stream_format.h struct xc_sr_rhdr · line 94

Quoted 2 lines
tools/libxc/xc_sr_stream_format.h +0 -0
 /* X86_PV_INFO */
 struct xc_sr_rec_x86_pv_info

What are the purposes of these name changes?

I should definitely have explained this more explicitly, sorry about that. I use the same exact structure (a count followed by a list of encoded pfns+types) for three additional record types (POSTCOPY_PFNS, POSTCOPY_PAGE_DATA, and POSTCOPY_FAULT) later in the series when postcopy is introduced. To enable the generation and validation logic to be shared between all of the code that processes this sort of record, I renamed the structure and its associated masks to be more generic.

Josh

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

#19 lore raw

Re: [PATCH RFC 06/20] libxc/xc_sr: factor helpers out of handle_page_data()

Quoted 28 lines · Joshua Otto
Quoted 22 lines · Andrew Cooper
Quoted 21 lines · Joshua Otto
tools/libxc/xc_sr_stream_format.h +3 -3
index 3291b25..32400b2 100644
@@ -80,15 +80,15 @@ struct xc_sr_rhdr
 #define REC_TYPE_OPTIONAL             0x80000000U
 
 /* PAGE_DATA */
-struct xc_sr_rec_page_data_header
+struct xc_sr_rec_pages_header
 {
     uint32_t count;
     uint32_t _res1;
     uint64_t pfn[0];
 };
 
-#define PAGE_DATA_PFN_MASK  0x000fffffffffffffULL
-#define PAGE_DATA_TYPE_MASK 0xf000000000000000ULL
+#define REC_PFINFO_PFN_MASK  0x000fffffffffffffULL
+#define REC_PFINFO_TYPE_MASK 0xf000000000000000ULL
 
Quoted 4 lines

tools/libxc/xc_sr_stream_format.h struct xc_sr_rhdr · line 94

Quoted 2 lines
tools/libxc/xc_sr_stream_format.h +0 -0
 /* X86_PV_INFO */
 struct xc_sr_rec_x86_pv_info

What are the purposes of these name changes?

Quoted 7 lines

I should definitely have explained this more explicitly, sorry about that. I use the same exact structure (a count followed by a list of encoded pfns+types) for three additional record types (POSTCOPY_PFNS, POSTCOPY_PAGE_DATA, and POSTCOPY_FAULT) later in the series when postcopy is introduced. To enable the generation and validation logic to be shared between all of the code that processes this sort of record, I renamed the structure and its associated masks to be more generic.

This should be part of the commit message.

Wei.

Quoted 2 lines

Josh

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

#20 lore raw

RFC PATCH 7/20 migration: defer precopy policy to libxl

In reply to Joshua Otto

The precopy phase of the xc_domain_save() live migration algorithm has historically been implemented to run until either a) (almost) no pages are dirty or b) some fixed, hard-coded maximum number of precopy iterations has been exceeded. This policy and its implementation are less than ideal for a few reasons:
- the logic of the policy is intertwined with the control flow of the mechanism of the precopy stage
- it can't take into account facts external to the immediate migration context, such as interactive user input or the passage of wall-clock time
- it does not permit the user to change their mind, over time, about what to do at the end of the precopy (they get an unconditional transition into the stop-and-copy phase of the migration)

To permit users to implement arbitrary higher-level policies governing when the live migration precopy phase should end, and what should be done next:
- add a precopy_policy() callback to the xc_domain_save() user-supplied callbacks
- during the precopy phase of live migrations, consult this policy after each batch of pages transmitted and take the dictated action, which may be to a) abort the migration entirely, b) continue with the precopy, or c) proceed to the stop-and-copy phase.
- provide an implementation of the old policy as such a callback in libxl and plumb it through the IPC machinery to libxc, effectively maintaing the old policy for now

---
 tools/libxc/include/xenguest.h     |  23 ++++-
 tools/libxc/xc_nomigrate.c         |   3 +-
 tools/libxc/xc_sr_common.h         |   7 +-
 tools/libxc/xc_sr_save.c           | 194 ++++++++++++++++++++++++++-----------
 tools/libxl/libxl_dom_save.c       |  20 ++++
 tools/libxl/libxl_save_callout.c   |   3 +-
 tools/libxl/libxl_save_helper.c    |   7 +-
 tools/libxl/libxl_save_msgs_gen.pl |   4 +-
 8 files changed, 189 insertions(+), 72 deletions(-)
tools/libxc/include/xenguest.h +21 -2
index aa8cc8b..30ffb6f 100644
@@ -39,6 +39,14 @@
  */
 struct xenevtchn_handle;
 
+/* For save's precopy_policy(). */
+struct precopy_stats
+{
+    unsigned iteration;
+    unsigned total_written;
+    long dirty_count; /* -1 if unknown */
+};
+
 /* callbacks provided by xc_domain_save */
 struct save_callbacks {
     /* Called after expiration of checkpoint interval,
@@ -46,6 +54,17 @@ struct save_callbacks {
      */
     int (*suspend)(void* data);
 
+    /* Called after every batch of page data sent during the precopy phase of a
+     * live migration to ask the caller what to do next based on the current
+     * state of the precopy migration.
+     */
+#define XGS_POLICY_ABORT          (-1) /* Abandon the migration entirely and
+                                        * tidy up. */
+#define XGS_POLICY_CONTINUE_PRECOPY 0  /* Remain in the precopy phase. */
+#define XGS_POLICY_STOP_AND_COPY    1  /* Immediately suspend and transmit the
+                                        * remaining dirty pages. */
+    int (*precopy_policy)(struct precopy_stats stats, void *data);
+
     /* Called after the guest's dirty pages have been
      *  copied into an output buffer.
      * Callback function resumes the guest & the device model,
@@ -100,8 +119,8 @@ typedef enum {
  *        doesn't use checkpointing
  * @return 0 on success, -1 on failure
  */
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags /* XCFLAGS_xxx */,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
+                   uint32_t flags /* XCFLAGS_xxx */,
                    struct save_callbacks* callbacks, int hvm,
                    xc_migration_stream_t stream_type, int recv_fd);
 
tools/libxc/xc_nomigrate.c +1 -2
index 15c838f..2af64e4 100644
@@ -20,8 +20,7 @@
 #include <xenctrl.h>
 #include <xenguest.h>
 
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t flags,
                    struct save_callbacks* callbacks, int hvm,
                    xc_migration_stream_t stream_type, int recv_fd)
 {
tools/libxc/xc_sr_common.h +3 -4
index b1aa88e..a9160bd 100644
@@ -198,12 +198,11 @@ struct xc_sr_context
             /* Further debugging information in the stream. */
             bool debug;
 
-            /* Parameters for tweaking live migration. */
-            unsigned max_iterations;
-            unsigned dirty_threshold;
-
             unsigned long p2m_size;
 
+            struct precopy_stats stats;
+            int policy_decision;
+
             xen_pfn_t *batch_pfns;
             unsigned nr_batch_pfns;
             unsigned long *deferred_pages;
tools/libxc/xc_sr_save.c +138 -56

332 lines not on this page · raw message

tools/libxl/libxl_dom_save.c +20 -0
index 77fe30e..6d28cce 100644
@@ -328,6 +328,25 @@ int libxl__save_emulator_xenstore_data(libxl__domain_save_state *dss,
     return rc;
 }
 
+/*
+ * This is the live migration precopy policy - it's called periodically during
+ * the precopy phase of live migrations, and is responsible for deciding when
+ * the precopy phase should terminate and what should be done next.
+ *
+ * The policy implemented here behaves identically to the policy previously
+ * hard-coded into xc_domain_save() - it proceeds to the stop-and-copy phase of
+ * the live migration when there are either fewer than 50 dirty pages, or more
+ * than 5 precopy rounds have completed.
+ */
+static int libxl__save_live_migration_simple_precopy_policy(
+    struct precopy_stats stats, void *user)
+{
+    return ((stats.dirty_count >= 0 && stats.dirty_count < 50) ||
+            stats.iteration >= 5)
+        ? XGS_POLICY_STOP_AND_COPY
+        : XGS_POLICY_CONTINUE_PRECOPY;
+}
+
 /*----- main code for saving, in order of execution -----*/
 
 void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)
@@ -401,6 +420,7 @@ void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)
     if (dss->checkpointed_stream == LIBXL_CHECKPOINTED_STREAM_NONE)
         callbacks->suspend = libxl__domain_suspend_callback;
 
+    callbacks->precopy_policy = libxl__save_live_migration_simple_precopy_policy;
     callbacks->switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
 
     dss->sws.ao  = dss->ao;
tools/libxl/libxl_save_callout.c +1 -2
index 46b892c..026b572 100644
@@ -89,8 +89,7 @@ void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_save_state *dss,
         libxl__srm_callout_enumcallbacks_save(&shs->callbacks.save.a);
 
     const unsigned long argnums[] = {
-        dss->domid, 0, 0, dss->xcflags, dss->hvm,
-        cbflags, dss->checkpointed_stream,
+        dss->domid, dss->xcflags, dss->hvm, cbflags, dss->checkpointed_stream,
     };
 
     shs->ao = ao;
tools/libxl/libxl_save_helper.c +2 -5
index d3def6b..0241a6b 100644
@@ -251,8 +251,6 @@ int main(int argc, char **argv)
         io_fd =                             atoi(NEXTARG);
         recv_fd =                           atoi(NEXTARG);
         uint32_t dom =                      strtoul(NEXTARG,0,10);
-        uint32_t max_iters =                strtoul(NEXTARG,0,10);
-        uint32_t max_factor =               strtoul(NEXTARG,0,10);
         uint32_t flags =                    strtoul(NEXTARG,0,10);
         int hvm =                           atoi(NEXTARG);
         unsigned cbflags =                  strtoul(NEXTARG,0,10);
@@ -264,9 +262,8 @@ int main(int argc, char **argv)
         startup("save");
         setup_signals(save_signal_handler);
 
-        r = xc_domain_save(xch, io_fd, dom, max_iters, max_factor, flags,
-                           &helper_save_callbacks, hvm, stream_type,
-                           recv_fd);
+        r = xc_domain_save(xch, io_fd, dom, flags, &helper_save_callbacks, hvm,
+                           stream_type, recv_fd);
         complete(r);
 
     } else if (!strcmp(mode,"--restore-domain")) {
tools/libxl/libxl_save_msgs_gen.pl +3 -1
index 27845bb..50c97b4 100755
@@ -33,6 +33,7 @@ our @msgs = (
                                               'xen_pfn_t', 'console_gfn'] ],
     [  9, 'srW',    "complete",              [qw(int retval
                                                  int errnoval)] ],
+    [ 10, 'scxW',   "precopy_policy", ['struct precopy_stats', 'stats'] ]
 );
 
 #----------------------------------------
@@ -141,7 +142,8 @@ static void bytes_put(unsigned char *const buf, int *len,
 
 END
 
-foreach my $simpletype (qw(int uint16_t uint32_t unsigned), 'unsigned long', 'xen_pfn_t') {
+foreach my $simpletype (qw(int uint16_t uint32_t unsigned),
+                        'unsigned long', 'xen_pfn_t', 'struct precopy_stats') {
     my $typeid = typeid($simpletype);
     $out_body{'callout'} .= <<END;
 static int ${typeid}_get(const unsigned char **msg,
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#21 lore raw

Re: [PATCH RFC 07/20] migration: defer precopy policy to libxl

Hi,

I would like to encourage this patch - as I have use for it outside of your postcopy work.

Some things people will comment on:
You've used 'unsigned' without the int keyword, which people don't like. Also on line 324, your missing space between 'if (' and 'ctx->save.policy_decision'.

Also, I'm not a fan of your CONSULT_POLICY macro, which you've defined at a odd point in your function, and I think could be done more elegantly. Worst of all ... its a macro - which I think should generally be avoided unless
there is little choice. I'm sure you could write a helper function to replace this.

Cheers,

-jenny

Quoted 561 lines · Joshua Otto

The precopy phase of the xc_domain_save() live migration algorithm has historically been implemented to run until either a) (almost) no pages are dirty or b) some fixed, hard-coded maximum number of precopy iterations has been exceeded. This policy and its implementation are less than ideal for a few reasons:
- the logic of the policy is intertwined with the control flow of the mechanism of the precopy stage
- it can't take into account facts external to the immediate migration context, such as interactive user input or the passage of wall-clock time
- it does not permit the user to change their mind, over time, about what to do at the end of the precopy (they get an unconditional transition into the stop-and-copy phase of the migration)

To permit users to implement arbitrary higher-level policies governing when the live migration precopy phase should end, and what should be done next:
- add a precopy_policy() callback to the xc_domain_save() user-supplied callbacks
- during the precopy phase of live migrations, consult this policy after each batch of pages transmitted and take the dictated action, which may be to a) abort the migration entirely, b) continue with the precopy, or c) proceed to the stop-and-copy phase.
- provide an implementation of the old policy as such a callback in libxl and plumb it through the IPC machinery to libxc, effectively maintaing the old policy for now

---
  tools/libxc/include/xenguest.h     |  23 ++++-
  tools/libxc/xc_nomigrate.c         |   3 +-
  tools/libxc/xc_sr_common.h         |   7 +-
  tools/libxc/xc_sr_save.c           | 194 ++++++++++++++++++++++++++-----------
  tools/libxl/libxl_dom_save.c       |  20 ++++
  tools/libxl/libxl_save_callout.c   |   3 +-
  tools/libxl/libxl_save_helper.c    |   7 +-
  tools/libxl/libxl_save_msgs_gen.pl |   4 +-
  8 files changed, 189 insertions(+), 72 deletions(-)
tools/libxc/include/xenguest.h +21 -2
index aa8cc8b..30ffb6f 100644
@@ -39,6 +39,14 @@
   */
  struct xenevtchn_handle;
 
+/* For save's precopy_policy(). */
+struct precopy_stats
+{
+    unsigned iteration;
+    unsigned total_written;
+    long dirty_count; /* -1 if unknown */
+};
+
  /* callbacks provided by xc_domain_save */
  struct save_callbacks {
      /* Called after expiration of checkpoint interval,
@@ -46,6 +54,17 @@ struct save_callbacks {
       */
      int (*suspend)(void* data);
 
+    /* Called after every batch of page data sent during the precopy phase of a
+     * live migration to ask the caller what to do next based on the current
+     * state of the precopy migration.
+     */
+#define XGS_POLICY_ABORT          (-1) /* Abandon the migration entirely and
+                                        * tidy up. */
+#define XGS_POLICY_CONTINUE_PRECOPY 0  /* Remain in the precopy phase. */
+#define XGS_POLICY_STOP_AND_COPY    1  /* Immediately suspend and transmit the
+                                        * remaining dirty pages. */
+    int (*precopy_policy)(struct precopy_stats stats, void *data);
+
      /* Called after the guest's dirty pages have been
       *  copied into an output buffer.
       * Callback function resumes the guest & the device model,
@@ -100,8 +119,8 @@ typedef enum {
   *        doesn't use checkpointing
   * @return 0 on success, -1 on failure
   */
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags /* XCFLAGS_xxx */,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
+                   uint32_t flags /* XCFLAGS_xxx */,
                     struct save_callbacks* callbacks, int hvm,
                     xc_migration_stream_t stream_type, int recv_fd);
 
tools/libxc/xc_nomigrate.c +1 -2
index 15c838f..2af64e4 100644
@@ -20,8 +20,7 @@
  #include <xenctrl.h>
  #include <xenguest.h>
 
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t flags,
                     struct save_callbacks* callbacks, int hvm,
                     xc_migration_stream_t stream_type, int recv_fd)
  {
tools/libxc/xc_sr_common.h +3 -4
index b1aa88e..a9160bd 100644
@@ -198,12 +198,11 @@ struct xc_sr_context
              /* Further debugging information in the stream. */
              bool debug;
 
-            /* Parameters for tweaking live migration. */
-            unsigned max_iterations;
-            unsigned dirty_threshold;
-
              unsigned long p2m_size;
 
+            struct precopy_stats stats;
+            int policy_decision;
+
              xen_pfn_t *batch_pfns;
              unsigned nr_batch_pfns;
              unsigned long *deferred_pages;
tools/libxc/xc_sr_save.c +138 -56
index 797aec5..eb95334 100644
@@ -271,13 +271,29 @@ static int write_batch(struct xc_sr_context *ctx)
  }
 
  /*
+ * Test if the batch is full.
+ */
+static bool batch_full(struct xc_sr_context *ctx)
+{
+    return ctx->save.nr_batch_pfns == MAX_BATCH_SIZE;
+}
+
+/*
+ * Test if the batch is empty.
+ */
+static bool batch_empty(struct xc_sr_context *ctx)
+{
+    return ctx->save.nr_batch_pfns == 0;
+}
+
+/*
   * 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 )
+    if ( batch_empty(ctx) )
          return rc;
 
      rc = write_batch(ctx);
@@ -293,19 +309,12 @@ static int flush_batch(struct xc_sr_context *ctx)
  }
 
  /*
- * Add a single pfn to the batch, flushing the batch if full.
+ * Add a single pfn to the batch.
   */
-static int add_to_batch(struct xc_sr_context *ctx, xen_pfn_t pfn)
+static void 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;
+    assert(ctx->save.nr_batch_pfns < MAX_BATCH_SIZE);
+    ctx->save.batch_pfns[ctx->save.nr_batch_pfns++] = pfn;
  }
 
  /*
@@ -352,10 +361,15 @@ static int suspend_domain(struct xc_sr_context *ctx)
   * Send a subset of pages in the guests p2m, according to the dirty bitmap.
   * Used for each subsequent iteration of the live migration loop.
   *
+ * During the precopy stage of a live migration, test the user-supplied
+ * policy function after each batch of pages and cut off the operation
+ * early if indicated.  Unless aborting, the dirty pages remaining in this round
+ * are transferred into the deferred_pages bitmap.
+ *
   * Bitmap is bounded by p2m_size.
   */
  static int send_dirty_pages(struct xc_sr_context *ctx,
-                            unsigned long entries)
+                            unsigned long entries, bool precopy)
  {
      xc_interface *xch = ctx->xch;
      xen_pfn_t p;
@@ -364,31 +378,57 @@ static int send_dirty_pages(struct xc_sr_context *ctx,
      DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
                                      &ctx->save.dirty_bitmap_hbuf);
 
-    for ( p = 0, written = 0; p < ctx->save.p2m_size; ++p )
+    int (*precopy_policy)(struct precopy_stats, void *) =
+        ctx->save.callbacks->precopy_policy;
+    void *data = ctx->save.callbacks->data;
+
+    assert(batch_empty(ctx));
+    for ( p = 0, written = 0; p < ctx->save.p2m_size; )
      {
-        if ( !test_bit(p, dirty_bitmap) )
-            continue;
+        if ( ctx->save.live && precopy )
+        {
+            ctx->save.policy_decision = precopy_policy(ctx->save.stats, data);
+            if ( ctx->save.policy_decision == XGS_POLICY_ABORT )
+            {
+                return -1;
+            }
+            else if ( ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )
+            {
+                /* Any outstanding dirty pages are now deferred until the next
+                 * phase of the migration. */
+                bitmap_or(ctx->save.deferred_pages, dirty_bitmap,
+                          ctx->save.p2m_size);
+                if ( entries > written )
+                    ctx->save.nr_deferred_pages += entries - written;
+
+                goto done;
+            }
+        }
 
-        rc = add_to_batch(ctx, p);
+        for ( ; p < ctx->save.p2m_size && !batch_full(ctx); ++p )
+        {
+            if ( test_and_clear_bit(p, dirty_bitmap) )
+            {
+                add_to_batch(ctx, p);
+                ++written;
+                ++ctx->save.stats.total_written;
+            }
+        }
+
+        rc = flush_batch(ctx);
          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;
+        /* Update progress after every batch (4MB) worth of memory sent. */
+        xc_report_progress_step(xch, written, entries);
      }
 
-    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);
 
+ done:
      return ctx->save.ops.check_vm_state(ctx);
  }
 
@@ -396,14 +436,14 @@ static int send_dirty_pages(struct xc_sr_context *ctx,
   * 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)
+static int send_all_pages(struct xc_sr_context *ctx, bool precopy)
  {
      DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
                                      &ctx->save.dirty_bitmap_hbuf);
 
      bitmap_set(dirty_bitmap, ctx->save.p2m_size);
 
-    return send_dirty_pages(ctx, ctx->save.p2m_size);
+    return send_dirty_pages(ctx, ctx->save.p2m_size, precopy);
  }
 
  static int enable_logdirty(struct xc_sr_context *ctx)
@@ -446,8 +486,7 @@ static int update_progress_string(struct xc_sr_context *ctx,
      xc_interface *xch = ctx->xch;
      char *new_str = NULL;
 
-    if ( asprintf(&new_str, "Frames iteration %u of %u",
-                  iter, ctx->save.max_iterations) == -1 )
+    if ( asprintf(&new_str, "Frames iteration %u", iter) == -1 )
      {
          PERROR("Unable to allocate new progress string");
          return -1;
@@ -468,20 +507,47 @@ static int send_memory_live(struct xc_sr_context *ctx)
      xc_interface *xch = ctx->xch;
      xc_shadow_op_stats_t stats = { 0, ctx->save.p2m_size };
      char *progress_str = NULL;
-    unsigned x;
      int rc;
 
+    DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
+                                    &ctx->save.dirty_bitmap_hbuf);
+
+    int (*precopy_policy)(struct precopy_stats, void *) =
+        ctx->save.callbacks->precopy_policy;
+    void *data = ctx->save.callbacks->data;
+
      rc = update_progress_string(ctx, &progress_str, 0);
      if ( rc )
          goto out;
 
-    rc = send_all_pages(ctx);
+#define CONSULT_POLICY                                                        \
+    do {                                                                      \
+        if ( ctx->save.policy_decision == XGS_POLICY_ABORT )                  \
+        {                                                                     \
+            rc = -1;                                                          \
+            goto out;                                                         \
+        }                                                                     \
+        else if ( ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )  \
+        {                                                                     \
+            rc = 0;                                                           \
+            goto out;                                                         \
+        }                                                                     \
+    } while (0)
+
+    ctx->save.stats = (struct precopy_stats)
+        {
+            .iteration     = 0,
+            .total_written = 0,
+            .dirty_count   = -1
+        };
+    rc = send_all_pages(ctx, /* precopy */ true);
      if ( rc )
          goto out;
 
-    for ( x = 1;
-          ((x < ctx->save.max_iterations) &&
-           (stats.dirty_count > ctx->save.dirty_threshold)); ++x )
+    /* send_all_pages() has updated the stats */
+    CONSULT_POLICY;
+
+    for ( ctx->save.stats.iteration = 1; ; ++ctx->save.stats.iteration )
      {
          if ( xc_shadow_control(
                   xch, ctx->domid, XEN_DOMCTL_SHADOW_OP_CLEAN,
@@ -493,18 +559,42 @@ static int send_memory_live(struct xc_sr_context *ctx)
              goto out;
          }
 
-        if ( stats.dirty_count == 0 )
-            break;
+        /* Check the new dirty_count against the policy. */
+        ctx->save.stats.dirty_count = stats.dirty_count;
+        ctx->save.policy_decision = precopy_policy(ctx->save.stats, data);
+        if ( ctx->save.policy_decision == XGS_POLICY_ABORT )
+        {
+            rc = -1;
+            goto out;
+        }
+        else if (ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )
+        {
+            bitmap_or(ctx->save.deferred_pages, dirty_bitmap,
+                      ctx->save.p2m_size);
+            ctx->save.nr_deferred_pages += stats.dirty_count;
+            rc = 0;
+            goto out;
+        }
+
+        /* After this point we won't know how many pages are really dirty until
+         * the next iteration. */
+        ctx->save.stats.dirty_count = -1;
 
-        rc = update_progress_string(ctx, &progress_str, x);
+        rc = update_progress_string(ctx, &progress_str,
+                                    ctx->save.stats.iteration);
          if ( rc )
              goto out;
 
-        rc = send_dirty_pages(ctx, stats.dirty_count);
+        rc = send_dirty_pages(ctx, stats.dirty_count, /* precopy */ true);
          if ( rc )
              goto out;
+
+        /* send_dirty_pages() has updated the stats */
+        CONSULT_POLICY;
      }
 
+#undef CONSULT_POLICY
+
   out:
      xc_set_progress_prefix(xch, NULL);
      free(progress_str);
@@ -595,7 +685,7 @@ static int suspend_and_send_dirty(struct xc_sr_context *ctx)
      if ( ctx->save.live )
      {
          rc = update_progress_string(ctx, &progress_str,
-                                    ctx->save.max_iterations);
+                                    ctx->save.stats.iteration);
          if ( rc )
              goto out;
      }
@@ -614,7 +704,8 @@ static int suspend_and_send_dirty(struct xc_sr_context *ctx)
          }
      }
 
-    rc = send_dirty_pages(ctx, stats.dirty_count + ctx->save.nr_deferred_pages);
+    rc = send_dirty_pages(ctx, stats.dirty_count + ctx->save.nr_deferred_pages,
+                          /* precopy */ false);
      if ( rc )
          goto out;
 
@@ -645,7 +736,7 @@ static int verify_frames(struct xc_sr_context *ctx)
          goto out;
 
      xc_set_progress_prefix(xch, "Frames verify");
-    rc = send_all_pages(ctx);
+    rc = send_all_pages(ctx, /* precopy */ false);
      if ( rc )
          goto out;
 
@@ -719,7 +810,7 @@ static int send_domain_memory_nonlive(struct xc_sr_context *ctx)
 
      xc_set_progress_prefix(xch, "Frames");
 
-    rc = send_all_pages(ctx);
+    rc = send_all_pages(ctx, /* precopy */ false);
      if ( rc )
          goto err;
 
@@ -910,8 +1001,7 @@ static int save(struct xc_sr_context *ctx, uint16_t guest_type)
  };
 
  int xc_domain_save(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,
+                   uint32_t flags, struct save_callbacks* callbacks, int hvm,
                     xc_migration_stream_t stream_type, int recv_fd)
  {
      struct xc_sr_context ctx =
@@ -932,25 +1022,17 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
             stream_type == XC_MIG_STREAM_REMUS ||
             stream_type == XC_MIG_STREAM_COLO);
 
-    /*
-     * 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;
-
      /* Sanity checks for callbacks. */
      if ( hvm )
          assert(callbacks->switch_qemu_logdirty);
+    if ( ctx.save.live )
+        assert(callbacks->precopy_policy);
      if ( ctx.save.checkpointed )
          assert(callbacks->checkpoint && callbacks->aftercopy);
      if ( ctx.save.checkpointed == XC_MIG_STREAM_COLO )
          assert(callbacks->wait_checkpoint);
 
-    DPRINTF("fd %d, dom %u, max_iters %u, max_factor %u, flags %u, hvm %d",
-            io_fd, dom, max_iters, max_factor, flags, hvm);
+    DPRINTF("fd %d, dom %u, flags %u, hvm %d", io_fd, dom, flags, hvm);
 
      if ( xc_domain_getinfo(xch, dom, 1, &ctx.dominfo) != 1 )
      {
tools/libxl/libxl_dom_save.c +20 -0
index 77fe30e..6d28cce 100644
@@ -328,6 +328,25 @@ int libxl__save_emulator_xenstore_data(libxl__domain_save_state *dss,
      return rc;
  }
 
+/*
+ * This is the live migration precopy policy - it's called periodically during
+ * the precopy phase of live migrations, and is responsible for deciding when
+ * the precopy phase should terminate and what should be done next.
+ *
+ * The policy implemented here behaves identically to the policy previously
+ * hard-coded into xc_domain_save() - it proceeds to the stop-and-copy phase of
+ * the live migration when there are either fewer than 50 dirty pages, or more
+ * than 5 precopy rounds have completed.
+ */
+static int libxl__save_live_migration_simple_precopy_policy(
+    struct precopy_stats stats, void *user)
+{
+    return ((stats.dirty_count >= 0 && stats.dirty_count < 50) ||
+            stats.iteration >= 5)
+        ? XGS_POLICY_STOP_AND_COPY
+        : XGS_POLICY_CONTINUE_PRECOPY;
+}
+
  /*----- main code for saving, in order of execution -----*/
 
  void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)
@@ -401,6 +420,7 @@ void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)
      if (dss->checkpointed_stream == LIBXL_CHECKPOINTED_STREAM_NONE)
          callbacks->suspend = libxl__domain_suspend_callback;
 
+    callbacks->precopy_policy = libxl__save_live_migration_simple_precopy_policy;
      callbacks->switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
 
      dss->sws.ao  = dss->ao;
tools/libxl/libxl_save_callout.c +1 -2
index 46b892c..026b572 100644
@@ -89,8 +89,7 @@ void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_save_state *dss,
          libxl__srm_callout_enumcallbacks_save(&shs->callbacks.save.a);
 
      const unsigned long argnums[] = {
-        dss->domid, 0, 0, dss->xcflags, dss->hvm,
-        cbflags, dss->checkpointed_stream,
+        dss->domid, dss->xcflags, dss->hvm, cbflags, dss->checkpointed_stream,
      };
 
      shs->ao = ao;
tools/libxl/libxl_save_helper.c +2 -5
index d3def6b..0241a6b 100644
@@ -251,8 +251,6 @@ int main(int argc, char **argv)
          io_fd =                             atoi(NEXTARG);
          recv_fd =                           atoi(NEXTARG);
          uint32_t dom =                      strtoul(NEXTARG,0,10);
-        uint32_t max_iters =                strtoul(NEXTARG,0,10);
-        uint32_t max_factor =               strtoul(NEXTARG,0,10);
          uint32_t flags =                    strtoul(NEXTARG,0,10);
          int hvm =                           atoi(NEXTARG);
          unsigned cbflags =                  strtoul(NEXTARG,0,10);
@@ -264,9 +262,8 @@ int main(int argc, char **argv)
          startup("save");
          setup_signals(save_signal_handler);
 
-        r = xc_domain_save(xch, io_fd, dom, max_iters, max_factor, flags,
-                           &helper_save_callbacks, hvm, stream_type,
-                           recv_fd);
+        r = xc_domain_save(xch, io_fd, dom, flags, &helper_save_callbacks, hvm,
+                           stream_type, recv_fd);
          complete(r);
 
      } else if (!strcmp(mode,"--restore-domain")) {
tools/libxl/libxl_save_msgs_gen.pl +1 -0
index 27845bb..50c97b4 100755
@@ -33,6 +33,7 @@ our @msgs = (
                                                'xen_pfn_t', 'console_gfn'] ],
      [  9, 'srW',    "complete",              [qw(int retval
                                                   int errnoval)] ],
+    [ 10, 'scxW',   "precopy_policy", ['struct precopy_stats', 'stats'] ]
  );
 
  #----------------------------------------

tools/libxl/libxl_save_msgs_gen.pl static void bytes_put(unsigned char *const buf, int *len, · line 149

Quoted 9 lines
tools/libxl/libxl_save_msgs_gen.pl +2 -1
@@ -141,7 +142,8 @@ static void bytes_put(unsigned char *const buf, int *len,
 
  END
 
-foreach my $simpletype (qw(int uint16_t uint32_t unsigned), 'unsigned long', 'xen_pfn_t') {
+foreach my $simpletype (qw(int uint16_t uint32_t unsigned),
+                        'unsigned long', 'xen_pfn_t', 'struct precopy_stats') {
      my $typeid = typeid($simpletype);
      $out_body{'callout'} .= <<END;
  static int ${typeid}_get(const unsigned char **msg,

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

#22 lore raw

Re: [PATCH RFC 07/20] migration: defer precopy policy to libxl

Quoted 2 lines · Jennifer Herbert

I would like to encourage this patch - as I have use for it outside of your postcopy work.

Glad to hear that!

Quoted 4 lines

Some things people will comment on:
You've used 'unsigned' without the int keyword, which people don't like. Also on line 324, your missing space between 'if (' and 'ctx->save.policy_decision'.

Ack. All of the existing code in xc_sr_save/xc_sr_restore uses plain "unsigned" so I tried to be consistent.

Quoted 7 lines

Also, I'm not a fan of your CONSULT_POLICY macro, which you've defined at a odd point in your function, and I think could be done more elegantly. Worst of all ... its a macro - which I think should generally be avoided unless
there is little choice. I'm sure you could write a helper function to
replace this.

Yes, you're right, will fix.

Thank you for the review!

Josh

Quoted 517 lines

Cheers,

-jenny

Quoted 511 lines · Joshua Otto

The precopy phase of the xc_domain_save() live migration algorithm has historically been implemented to run until either a) (almost) no pages are dirty or b) some fixed, hard-coded maximum number of precopy iterations has been exceeded. This policy and its implementation are less than ideal for a few reasons:
- the logic of the policy is intertwined with the control flow of the mechanism of the precopy stage
- it can't take into account facts external to the immediate migration context, such as interactive user input or the passage of wall-clock time
- it does not permit the user to change their mind, over time, about what to do at the end of the precopy (they get an unconditional transition into the stop-and-copy phase of the migration)

To permit users to implement arbitrary higher-level policies governing when the live migration precopy phase should end, and what should be done next:
- add a precopy_policy() callback to the xc_domain_save() user-supplied callbacks
- during the precopy phase of live migrations, consult this policy after each batch of pages transmitted and take the dictated action, which may be to a) abort the migration entirely, b) continue with the precopy, or c) proceed to the stop-and-copy phase.
- provide an implementation of the old policy as such a callback in libxl and plumb it through the IPC machinery to libxc, effectively maintaing the old policy for now

---
 tools/libxc/include/xenguest.h     |  23 ++++-
 tools/libxc/xc_nomigrate.c         |   3 +-
 tools/libxc/xc_sr_common.h         |   7 +-
 tools/libxc/xc_sr_save.c           | 194 ++++++++++++++++++++++++++-----------
 tools/libxl/libxl_dom_save.c       |  20 ++++
 tools/libxl/libxl_save_callout.c   |   3 +-
 tools/libxl/libxl_save_helper.c    |   7 +-
 tools/libxl/libxl_save_msgs_gen.pl |   4 +-
 8 files changed, 189 insertions(+), 72 deletions(-)
tools/libxc/include/xenguest.h +21 -2
index aa8cc8b..30ffb6f 100644
@@ -39,6 +39,14 @@
  */
 struct xenevtchn_handle;
+/* For save's precopy_policy(). */
+struct precopy_stats
+{
+    unsigned iteration;
+    unsigned total_written;
+    long dirty_count; /* -1 if unknown */
+};
+
 /* callbacks provided by xc_domain_save */
 struct save_callbacks {
     /* Called after expiration of checkpoint interval,
@@ -46,6 +54,17 @@ struct save_callbacks {
      */
     int (*suspend)(void* data);
+    /* Called after every batch of page data sent during the precopy phase of a
+     * live migration to ask the caller what to do next based on the current
+     * state of the precopy migration.
+     */
+#define XGS_POLICY_ABORT          (-1) /* Abandon the migration entirely and
+                                        * tidy up. */
+#define XGS_POLICY_CONTINUE_PRECOPY 0  /* Remain in the precopy phase. */
+#define XGS_POLICY_STOP_AND_COPY    1  /* Immediately suspend and transmit the
+                                        * remaining dirty pages. */
+    int (*precopy_policy)(struct precopy_stats stats, void *data);
+
     /* Called after the guest's dirty pages have been
      *  copied into an output buffer.
      * Callback function resumes the guest & the device model,
@@ -100,8 +119,8 @@ typedef enum {
  *        doesn't use checkpointing
  * @return 0 on success, -1 on failure
  */
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags /* XCFLAGS_xxx */,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
+                   uint32_t flags /* XCFLAGS_xxx */,
                    struct save_callbacks* callbacks, int hvm,
                    xc_migration_stream_t stream_type, int recv_fd);
tools/libxc/xc_nomigrate.c +1 -2
index 15c838f..2af64e4 100644
@@ -20,8 +20,7 @@
 #include <xenctrl.h>
 #include <xenguest.h>
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t flags,
                    struct save_callbacks* callbacks, int hvm,
                    xc_migration_stream_t stream_type, int recv_fd)
 {
tools/libxc/xc_sr_common.h +3 -4
index b1aa88e..a9160bd 100644
@@ -198,12 +198,11 @@ struct xc_sr_context
             /* Further debugging information in the stream. */
             bool debug;
-            /* Parameters for tweaking live migration. */
-            unsigned max_iterations;
-            unsigned dirty_threshold;
-
             unsigned long p2m_size;
+            struct precopy_stats stats;
+            int policy_decision;
+
             xen_pfn_t *batch_pfns;
             unsigned nr_batch_pfns;
             unsigned long *deferred_pages;
tools/libxc/xc_sr_save.c +138 -56
index 797aec5..eb95334 100644
@@ -271,13 +271,29 @@ static int write_batch(struct xc_sr_context *ctx)
 }
 /*
+ * Test if the batch is full.
+ */
+static bool batch_full(struct xc_sr_context *ctx)
+{
+    return ctx->save.nr_batch_pfns == MAX_BATCH_SIZE;
+}
+
+/*
+ * Test if the batch is empty.
+ */
+static bool batch_empty(struct xc_sr_context *ctx)
+{
+    return ctx->save.nr_batch_pfns == 0;
+}
+
+/*
  * 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 )
+    if ( batch_empty(ctx) )
         return rc;
     rc = write_batch(ctx);
@@ -293,19 +309,12 @@ static int flush_batch(struct xc_sr_context *ctx)
 }
 /*
- * Add a single pfn to the batch, flushing the batch if full.
+ * Add a single pfn to the batch.
  */
-static int add_to_batch(struct xc_sr_context *ctx, xen_pfn_t pfn)
+static void 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;
+    assert(ctx->save.nr_batch_pfns < MAX_BATCH_SIZE);
+    ctx->save.batch_pfns[ctx->save.nr_batch_pfns++] = pfn;
 }
 /*
@@ -352,10 +361,15 @@ static int suspend_domain(struct xc_sr_context *ctx)
  * Send a subset of pages in the guests p2m, according to the dirty bitmap.
  * Used for each subsequent iteration of the live migration loop.
  *
+ * During the precopy stage of a live migration, test the user-supplied
+ * policy function after each batch of pages and cut off the operation
+ * early if indicated.  Unless aborting, the dirty pages remaining in this round
+ * are transferred into the deferred_pages bitmap.
+ *
  * Bitmap is bounded by p2m_size.
  */
 static int send_dirty_pages(struct xc_sr_context *ctx,
-                            unsigned long entries)
+                            unsigned long entries, bool precopy)
 {
     xc_interface *xch = ctx->xch;
     xen_pfn_t p;
@@ -364,31 +378,57 @@ static int send_dirty_pages(struct xc_sr_context *ctx,
     DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
                                     &ctx->save.dirty_bitmap_hbuf);
-    for ( p = 0, written = 0; p < ctx->save.p2m_size; ++p )
+    int (*precopy_policy)(struct precopy_stats, void *) =
+        ctx->save.callbacks->precopy_policy;
+    void *data = ctx->save.callbacks->data;
+
+    assert(batch_empty(ctx));
+    for ( p = 0, written = 0; p < ctx->save.p2m_size; )
     {
-        if ( !test_bit(p, dirty_bitmap) )
-            continue;
+        if ( ctx->save.live && precopy )
+        {
+            ctx->save.policy_decision = precopy_policy(ctx->save.stats, data);
+            if ( ctx->save.policy_decision == XGS_POLICY_ABORT )
+            {
+                return -1;
+            }
+            else if ( ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )
+            {
+                /* Any outstanding dirty pages are now deferred until the next
+                 * phase of the migration. */
+                bitmap_or(ctx->save.deferred_pages, dirty_bitmap,
+                          ctx->save.p2m_size);
+                if ( entries > written )
+                    ctx->save.nr_deferred_pages += entries - written;
+
+                goto done;
+            }
+        }
-        rc = add_to_batch(ctx, p);
+        for ( ; p < ctx->save.p2m_size && !batch_full(ctx); ++p )
+        {
+            if ( test_and_clear_bit(p, dirty_bitmap) )
+            {
+                add_to_batch(ctx, p);
+                ++written;
+                ++ctx->save.stats.total_written;
+            }
+        }
+
+        rc = flush_batch(ctx);
         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;
+        /* Update progress after every batch (4MB) worth of memory sent. */
+        xc_report_progress_step(xch, written, entries);
     }
-    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);
+ done:
     return ctx->save.ops.check_vm_state(ctx);
 }
@@ -396,14 +436,14 @@ static int send_dirty_pages(struct xc_sr_context *ctx,
  * 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)
+static int send_all_pages(struct xc_sr_context *ctx, bool precopy)
 {
     DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
                                     &ctx->save.dirty_bitmap_hbuf);
     bitmap_set(dirty_bitmap, ctx->save.p2m_size);
-    return send_dirty_pages(ctx, ctx->save.p2m_size);
+    return send_dirty_pages(ctx, ctx->save.p2m_size, precopy);
 }
 static int enable_logdirty(struct xc_sr_context *ctx)
@@ -446,8 +486,7 @@ static int update_progress_string(struct xc_sr_context *ctx,
     xc_interface *xch = ctx->xch;
     char *new_str = NULL;
-    if ( asprintf(&new_str, "Frames iteration %u of %u",
-                  iter, ctx->save.max_iterations) == -1 )
+    if ( asprintf(&new_str, "Frames iteration %u", iter) == -1 )
     {
         PERROR("Unable to allocate new progress string");
         return -1;
@@ -468,20 +507,47 @@ static int send_memory_live(struct xc_sr_context *ctx)
     xc_interface *xch = ctx->xch;
     xc_shadow_op_stats_t stats = { 0, ctx->save.p2m_size };
     char *progress_str = NULL;
-    unsigned x;
     int rc;
+    DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
+                                    &ctx->save.dirty_bitmap_hbuf);
+
+    int (*precopy_policy)(struct precopy_stats, void *) =
+        ctx->save.callbacks->precopy_policy;
+    void *data = ctx->save.callbacks->data;
+
     rc = update_progress_string(ctx, &progress_str, 0);
     if ( rc )
         goto out;
-    rc = send_all_pages(ctx);
+#define CONSULT_POLICY                                                        \
+    do {                                                                      \
+        if ( ctx->save.policy_decision == XGS_POLICY_ABORT )                  \
+        {                                                                     \
+            rc = -1;                                                          \
+            goto out;                                                         \
+        }                                                                     \
+        else if ( ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )  \
+        {                                                                     \
+            rc = 0;                                                           \
+            goto out;                                                         \
+        }                                                                     \
+    } while (0)
+
+    ctx->save.stats = (struct precopy_stats)
+        {
+            .iteration     = 0,
+            .total_written = 0,
+            .dirty_count   = -1
+        };
+    rc = send_all_pages(ctx, /* precopy */ true);
     if ( rc )
         goto out;
-    for ( x = 1;
-          ((x < ctx->save.max_iterations) &&
-           (stats.dirty_count > ctx->save.dirty_threshold)); ++x )
+    /* send_all_pages() has updated the stats */
+    CONSULT_POLICY;
+
+    for ( ctx->save.stats.iteration = 1; ; ++ctx->save.stats.iteration )
     {
         if ( xc_shadow_control(
                  xch, ctx->domid, XEN_DOMCTL_SHADOW_OP_CLEAN,
@@ -493,18 +559,42 @@ static int send_memory_live(struct xc_sr_context *ctx)
             goto out;
         }
-        if ( stats.dirty_count == 0 )
-            break;
+        /* Check the new dirty_count against the policy. */
+        ctx->save.stats.dirty_count = stats.dirty_count;
+        ctx->save.policy_decision = precopy_policy(ctx->save.stats, data);
+        if ( ctx->save.policy_decision == XGS_POLICY_ABORT )
+        {
+            rc = -1;
+            goto out;
+        }
+        else if (ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )
+        {
+            bitmap_or(ctx->save.deferred_pages, dirty_bitmap,
+                      ctx->save.p2m_size);
+            ctx->save.nr_deferred_pages += stats.dirty_count;
+            rc = 0;
+            goto out;
+        }
+
+        /* After this point we won't know how many pages are really dirty until
+         * the next iteration. */
+        ctx->save.stats.dirty_count = -1;
-        rc = update_progress_string(ctx, &progress_str, x);
+        rc = update_progress_string(ctx, &progress_str,
+                                    ctx->save.stats.iteration);
         if ( rc )
             goto out;
-        rc = send_dirty_pages(ctx, stats.dirty_count);
+        rc = send_dirty_pages(ctx, stats.dirty_count, /* precopy */ true);
         if ( rc )
             goto out;
+
+        /* send_dirty_pages() has updated the stats */
+        CONSULT_POLICY;
     }
+#undef CONSULT_POLICY
+
  out:
     xc_set_progress_prefix(xch, NULL);
     free(progress_str);
@@ -595,7 +685,7 @@ static int suspend_and_send_dirty(struct xc_sr_context *ctx)
     if ( ctx->save.live )
     {
         rc = update_progress_string(ctx, &progress_str,
-                                    ctx->save.max_iterations);
+                                    ctx->save.stats.iteration);
         if ( rc )
             goto out;
     }
@@ -614,7 +704,8 @@ static int suspend_and_send_dirty(struct xc_sr_context *ctx)
         }
     }
-    rc = send_dirty_pages(ctx, stats.dirty_count + ctx->save.nr_deferred_pages);
+    rc = send_dirty_pages(ctx, stats.dirty_count + ctx->save.nr_deferred_pages,
+                          /* precopy */ false);
     if ( rc )
         goto out;
@@ -645,7 +736,7 @@ static int verify_frames(struct xc_sr_context *ctx)
         goto out;
     xc_set_progress_prefix(xch, "Frames verify");
-    rc = send_all_pages(ctx);
+    rc = send_all_pages(ctx, /* precopy */ false);
     if ( rc )
         goto out;
@@ -719,7 +810,7 @@ static int send_domain_memory_nonlive(struct xc_sr_context *ctx)
     xc_set_progress_prefix(xch, "Frames");
-    rc = send_all_pages(ctx);
+    rc = send_all_pages(ctx, /* precopy */ false);
     if ( rc )
         goto err;
@@ -910,8 +1001,7 @@ static int save(struct xc_sr_context *ctx, uint16_t guest_type)
 };
 int xc_domain_save(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,
+                   uint32_t flags, struct save_callbacks* callbacks, int hvm,
                    xc_migration_stream_t stream_type, int recv_fd)
 {
     struct xc_sr_context ctx =
@@ -932,25 +1022,17 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
            stream_type == XC_MIG_STREAM_REMUS ||
            stream_type == XC_MIG_STREAM_COLO);
-    /*
-     * 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;
-
     /* Sanity checks for callbacks. */
     if ( hvm )
         assert(callbacks->switch_qemu_logdirty);
+    if ( ctx.save.live )
+        assert(callbacks->precopy_policy);
     if ( ctx.save.checkpointed )
         assert(callbacks->checkpoint && callbacks->aftercopy);
     if ( ctx.save.checkpointed == XC_MIG_STREAM_COLO )
         assert(callbacks->wait_checkpoint);
-    DPRINTF("fd %d, dom %u, max_iters %u, max_factor %u, flags %u, hvm %d",
-            io_fd, dom, max_iters, max_factor, flags, hvm);
+    DPRINTF("fd %d, dom %u, flags %u, hvm %d", io_fd, dom, flags, hvm);
     if ( xc_domain_getinfo(xch, dom, 1, &ctx.dominfo) != 1 )
     {
tools/libxl/libxl_dom_save.c +20 -0
index 77fe30e..6d28cce 100644
@@ -328,6 +328,25 @@ int libxl__save_emulator_xenstore_data(libxl__domain_save_state *dss,
     return rc;
 }
+/*
+ * This is the live migration precopy policy - it's called periodically during
+ * the precopy phase of live migrations, and is responsible for deciding when
+ * the precopy phase should terminate and what should be done next.
+ *
+ * The policy implemented here behaves identically to the policy previously
+ * hard-coded into xc_domain_save() - it proceeds to the stop-and-copy phase of
+ * the live migration when there are either fewer than 50 dirty pages, or more
+ * than 5 precopy rounds have completed.
+ */
+static int libxl__save_live_migration_simple_precopy_policy(
+    struct precopy_stats stats, void *user)
+{
+    return ((stats.dirty_count >= 0 && stats.dirty_count < 50) ||
+            stats.iteration >= 5)
+        ? XGS_POLICY_STOP_AND_COPY
+        : XGS_POLICY_CONTINUE_PRECOPY;
+}
+
 /*----- main code for saving, in order of execution -----*/
 void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)
@@ -401,6 +420,7 @@ void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)
     if (dss->checkpointed_stream == LIBXL_CHECKPOINTED_STREAM_NONE)
         callbacks->suspend = libxl__domain_suspend_callback;
+    callbacks->precopy_policy = libxl__save_live_migration_simple_precopy_policy;
     callbacks->switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
     dss->sws.ao  = dss->ao;
tools/libxl/libxl_save_callout.c +1 -2
index 46b892c..026b572 100644
@@ -89,8 +89,7 @@ void libxl__xc_domain_save(libxl__egc *egc, libxl__domain_save_state *dss,
         libxl__srm_callout_enumcallbacks_save(&shs->callbacks.save.a);
     const unsigned long argnums[] = {
-        dss->domid, 0, 0, dss->xcflags, dss->hvm,
-        cbflags, dss->checkpointed_stream,
+        dss->domid, dss->xcflags, dss->hvm, cbflags, dss->checkpointed_stream,
     };
     shs->ao = ao;
tools/libxl/libxl_save_helper.c +2 -5
index d3def6b..0241a6b 100644
@@ -251,8 +251,6 @@ int main(int argc, char **argv)
         io_fd =                             atoi(NEXTARG);
         recv_fd =                           atoi(NEXTARG);
         uint32_t dom =                      strtoul(NEXTARG,0,10);
-        uint32_t max_iters =                strtoul(NEXTARG,0,10);
-        uint32_t max_factor =               strtoul(NEXTARG,0,10);
         uint32_t flags =                    strtoul(NEXTARG,0,10);
         int hvm =                           atoi(NEXTARG);
         unsigned cbflags =                  strtoul(NEXTARG,0,10);
@@ -264,9 +262,8 @@ int main(int argc, char **argv)
         startup("save");
         setup_signals(save_signal_handler);
-        r = xc_domain_save(xch, io_fd, dom, max_iters, max_factor, flags,
-                           &helper_save_callbacks, hvm, stream_type,
-                           recv_fd);
+        r = xc_domain_save(xch, io_fd, dom, flags, &helper_save_callbacks, hvm,
+                           stream_type, recv_fd);
         complete(r);
     } else if (!strcmp(mode,"--restore-domain")) {
tools/libxl/libxl_save_msgs_gen.pl +1 -0
index 27845bb..50c97b4 100755
@@ -33,6 +33,7 @@ our @msgs = (
                                               'xen_pfn_t', 'console_gfn'] ],
     [  9, 'srW',    "complete",              [qw(int retval
                                                  int errnoval)] ],
+    [ 10, 'scxW',   "precopy_policy", ['struct precopy_stats', 'stats'] ]
 );
 #----------------------------------------
Quoted 9 lines

tools/libxl/libxl_save_msgs_gen.pl static void bytes_put(unsigned char *const buf, int *len, · line 147

Quoted 8 lines
tools/libxl/libxl_save_msgs_gen.pl +2 -1
@@ -141,7 +142,8 @@ static void bytes_put(unsigned char *const buf, int *len,
 END
-foreach my $simpletype (qw(int uint16_t uint32_t unsigned), 'unsigned long', 'xen_pfn_t') {
+foreach my $simpletype (qw(int uint16_t uint32_t unsigned),
+                        'unsigned long', 'xen_pfn_t', 'struct precopy_stats') {
     my $typeid = typeid($simpletype);
     $out_body{'callout'} .= <<END;
 static int ${typeid}_get(const unsigned char **msg,

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

#23 lore raw

Re: [PATCH RFC 07/20] migration: defer precopy policy to libxl

In reply to Joshua Otto
Quoted 27 lines · Joshua Otto

The precopy phase of the xc_domain_save() live migration algorithm has historically been implemented to run until either a) (almost) no pages are dirty or b) some fixed, hard-coded maximum number of precopy iterations has been exceeded. This policy and its implementation are less than ideal for a few reasons:
- the logic of the policy is intertwined with the control flow of the mechanism of the precopy stage
- it can't take into account facts external to the immediate migration context, such as interactive user input or the passage of wall-clock time
- it does not permit the user to change their mind, over time, about what to do at the end of the precopy (they get an unconditional transition into the stop-and-copy phase of the migration)

To permit users to implement arbitrary higher-level policies governing when the live migration precopy phase should end, and what should be done next:
- add a precopy_policy() callback to the xc_domain_save() user-supplied callbacks
- during the precopy phase of live migrations, consult this policy after each batch of pages transmitted and take the dictated action, which may be to a) abort the migration entirely, b) continue with the precopy, or c) proceed to the stop-and-copy phase.
- provide an implementation of the old policy as such a callback in libxl and plumb it through the IPC machinery to libxc, effectively maintaing the old policy for now

Quoted 1 line

This patch should be split into two. One modifying libxc to use struct precopy_stats, and a second to wire up the RPC call.

Quoted 16 lines
---
 tools/libxc/include/xenguest.h     |  23 ++++-
 tools/libxc/xc_nomigrate.c         |   3 +-
 tools/libxc/xc_sr_common.h         |   7 +-
 tools/libxc/xc_sr_save.c           | 194 ++++++++++++++++++++++++++-----------
 tools/libxl/libxl_dom_save.c       |  20 ++++
 tools/libxl/libxl_save_callout.c   |   3 +-
 tools/libxl/libxl_save_helper.c    |   7 +-
 tools/libxl/libxl_save_msgs_gen.pl |   4 +-
 8 files changed, 189 insertions(+), 72 deletions(-)
tools/libxc/include/xenguest.h +0 -0
index aa8cc8b..30ffb6f 100644

tools/libxc/include/xenguest.h line 47

Quoted 9 lines
tools/libxc/include/xenguest.h +6 -0
@@ -39,6 +39,14 @@
  */
 struct xenevtchn_handle;
 
+/* For save's precopy_policy(). */
+struct precopy_stats
+{
+    unsigned iteration;
+    unsigned total_written;
+    long dirty_count; /* -1 if unknown */

total_written and dirty_count are liable to be equal, so having them as different widths of integer clearly can't be correct.

Quoted 9 lines
tools/libxc/include/xenguest.h +2 -0
+};
+
 /* callbacks provided by xc_domain_save */
 struct save_callbacks {
     /* Called after expiration of checkpoint interval,
@@ -46,6 +54,17 @@ struct save_callbacks {
      */
     int (*suspend)(void* data);
 

tools/libxc/include/xenguest.h struct save_callbacks { · line 66

Quoted 10 lines
tools/libxc/include/xenguest.h +10 -0
+    /* Called after every batch of page data sent during the precopy phase of a
+     * live migration to ask the caller what to do next based on the current
+     * state of the precopy migration.
+     */
+#define XGS_POLICY_ABORT          (-1) /* Abandon the migration entirely and
+                                        * tidy up. */
+#define XGS_POLICY_CONTINUE_PRECOPY 0  /* Remain in the precopy phase. */
+#define XGS_POLICY_STOP_AND_COPY    1  /* Immediately suspend and transmit the
+                                        * remaining dirty pages. */
+    int (*precopy_policy)(struct precopy_stats stats, void *data);

Structures shouldn't be passed by value like this, as the compiler has to do a lot of memcpy() work to make it happen. You should pass by const pointer, as (as far as I can tell), they are strictly read-only to the implementation of this hook?

Quoted 5 lines
tools/libxc/include/xenguest.h +1 -0
+
     /* Called after the guest's dirty pages have been
      *  copied into an output buffer.
      * Callback function resumes the guest & the device model,

tools/libxc/include/xenguest.h typedef enum { · line 125

Quoted 9 lines
tools/libxc/include/xenguest.h +2 -2
@@ -100,8 +119,8 @@ typedef enum {
  *        doesn't use checkpointing
  * @return 0 on success, -1 on failure
  */
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags /* XCFLAGS_xxx */,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
+                   uint32_t flags /* XCFLAGS_xxx */,
                    struct save_callbacks* callbacks, int hvm,
                    xc_migration_stream_t stream_type, int recv_fd);

It would be cleaner for existing callers, and to extend in the future, to encapsulate all of these parameters in a struct domain_save_params and pass it by pointer to here.

That way, we'd avoid the situation we currently have where some information is passed in bitfields in a single parameter, whereas other booleans are passed as integers.

The hvm parameter specifically is useless, and can be removed by rearranging the sanity checks until after the xc_domain_getinfo() call.

Quoted 40 lines
tools/libxc/xc_nomigrate.c +1 -2
index 15c838f..2af64e4 100644
@@ -20,8 +20,7 @@
 #include <xenctrl.h>
 #include <xenguest.h>
 
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t flags,
                    struct save_callbacks* callbacks, int hvm,
                    xc_migration_stream_t stream_type, int recv_fd)
 {
tools/libxc/xc_sr_common.h +3 -4
index b1aa88e..a9160bd 100644
@@ -198,12 +198,11 @@ struct xc_sr_context
             /* Further debugging information in the stream. */
             bool debug;
 
-            /* Parameters for tweaking live migration. */
-            unsigned max_iterations;
-            unsigned dirty_threshold;
-
             unsigned long p2m_size;
 
+            struct precopy_stats stats;
+            int policy_decision;
+
             xen_pfn_t *batch_pfns;
             unsigned nr_batch_pfns;
             unsigned long *deferred_pages;
tools/libxc/xc_sr_save.c +0 -0
index 797aec5..eb95334 100644

tools/libxc/xc_sr_save.c static int write_batch(struct xc_sr_context *ctx) · line 276

Quoted 6 lines
tools/libxc/xc_sr_save.c +3 -0
@@ -271,13 +271,29 @@ static int write_batch(struct xc_sr_context *ctx)
 }
 
 /*
+ * Test if the batch is full.
+ */
+static bool batch_full(struct xc_sr_context *ctx)

const struct xc_sr_context *ctx

This is a predicate, after all.

Quoted 49 lines
tools/libxc/xc_sr_save.c +18 -12
+{
+    return ctx->save.nr_batch_pfns == MAX_BATCH_SIZE;
+}
+
+/*
+ * Test if the batch is empty.
+ */
+static bool batch_empty(struct xc_sr_context *ctx)
+{
+    return ctx->save.nr_batch_pfns == 0;
+}
+
+/*
  * 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 )
+    if ( batch_empty(ctx) )
         return rc;
 
     rc = write_batch(ctx);
@@ -293,19 +309,12 @@ static int flush_batch(struct xc_sr_context *ctx)
 }
 
 /*
- * Add a single pfn to the batch, flushing the batch if full.
+ * Add a single pfn to the batch.
  */
-static int add_to_batch(struct xc_sr_context *ctx, xen_pfn_t pfn)
+static void 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;
+    assert(ctx->save.nr_batch_pfns < MAX_BATCH_SIZE);
+    ctx->save.batch_pfns[ctx->save.nr_batch_pfns++] = pfn;
 }
 
 /*

tools/libxc/xc_sr_save.c static int suspend_domain(struct xc_sr_context *ctx) · line 367

Quoted 7 lines
tools/libxc/xc_sr_save.c +4 -0
@@ -352,10 +361,15 @@ static int suspend_domain(struct xc_sr_context *ctx)
  * Send a subset of pages in the guests p2m, according to the dirty bitmap.
  * Used for each subsequent iteration of the live migration loop.
  *
+ * During the precopy stage of a live migration, test the user-supplied
+ * policy function after each batch of pages and cut off the operation
+ * early if indicated.  Unless aborting, the dirty pages remaining in this round
+ * are transferred into the deferred_pages bitmap.

Is this actually a sensible thing to do? On iteration 0, this is going to be a phenomenal number of RPC calls, which are all going to make the same decision.

tools/libxc/xc_sr_save.c static int suspend_domain(struct xc_sr_context *ctx) · line 372

Quoted 6 lines
tools/libxc/xc_sr_save.c +2 -1
+ *
  * Bitmap is bounded by p2m_size.
  */
 static int send_dirty_pages(struct xc_sr_context *ctx,
-                            unsigned long entries)
+                            unsigned long entries, bool precopy)

Shouldn't this precopy boolean be some kind of state variable in ctx ?

Quoted 4 lines
tools/libxc/xc_sr_save.c +0 -0
 {
     xc_interface *xch = ctx->xch;
     xen_pfn_t p;

tools/libxc/xc_sr_save.c static int send_dirty_pages(struct xc_sr_context *ctx, · line 386

Quoted 10 lines
tools/libxc/xc_sr_save.c +6 -1
@@ -364,31 +378,57 @@ static int send_dirty_pages(struct xc_sr_context *ctx,
     DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
                                     &ctx->save.dirty_bitmap_hbuf);
 
-    for ( p = 0, written = 0; p < ctx->save.p2m_size; ++p )
+    int (*precopy_policy)(struct precopy_stats, void *) =
+        ctx->save.callbacks->precopy_policy;
+    void *data = ctx->save.callbacks->data;
+
+    assert(batch_empty(ctx));
+    for ( p = 0, written = 0; p < ctx->save.p2m_size; )

This looks suspicious without an increment. Conceptually, it might be better as a do {} while ( decision == XGS_POLICY_CONTINUE_PRECOPY ); loop?

tools/libxc/xc_sr_save.c static int send_dirty_pages(struct xc_sr_context *ctx, · line 390

Quoted 6 lines
tools/libxc/xc_sr_save.c +3 -2
     {
-        if ( !test_bit(p, dirty_bitmap) )
-            continue;
+        if ( ctx->save.live && precopy )
+        {
+            ctx->save.policy_decision = precopy_policy(ctx->save.stats, data);

Newline here please.

tools/libxc/xc_sr_save.c static int send_dirty_pages(struct xc_sr_context *ctx, · line 392

Quoted 2 lines
tools/libxc/xc_sr_save.c +2 -0
+            if ( ctx->save.policy_decision == XGS_POLICY_ABORT )
+            {

Please but a log message here indicating that abort has been requested. Otherwise, the migration will give up with a failure and no obvious indication why.

tools/libxc/xc_sr_save.c static int send_dirty_pages(struct xc_sr_context *ctx, · line 398

Quoted 6 lines
tools/libxc/xc_sr_save.c +6 -0
+                return -1;
+            }
+            else if ( ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )
+            {
+                /* Any outstanding dirty pages are now deferred until the next
+                 * phase of the migration. */

/*
* The comment style for multiline comments
* is like this.
*/

Quoted 83 lines
tools/libxc/xc_sr_save.c +28 -15
+                bitmap_or(ctx->save.deferred_pages, dirty_bitmap,
+                          ctx->save.p2m_size);
+                if ( entries > written )
+                    ctx->save.nr_deferred_pages += entries - written;
+
+                goto done;
+            }
+        }
 
-        rc = add_to_batch(ctx, p);
+        for ( ; p < ctx->save.p2m_size && !batch_full(ctx); ++p )
+        {
+            if ( test_and_clear_bit(p, dirty_bitmap) )
+            {
+                add_to_batch(ctx, p);
+                ++written;
+                ++ctx->save.stats.total_written;
+            }
+        }
+
+        rc = flush_batch(ctx);
         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;
+        /* Update progress after every batch (4MB) worth of memory sent. */
+        xc_report_progress_step(xch, written, entries);
     }
 
-    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);
 
+ done:
     return ctx->save.ops.check_vm_state(ctx);
 }
 
@@ -396,14 +436,14 @@ static int send_dirty_pages(struct xc_sr_context *ctx,
  * 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)
+static int send_all_pages(struct xc_sr_context *ctx, bool precopy)
 {
     DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
                                     &ctx->save.dirty_bitmap_hbuf);
 
     bitmap_set(dirty_bitmap, ctx->save.p2m_size);
 
-    return send_dirty_pages(ctx, ctx->save.p2m_size);
+    return send_dirty_pages(ctx, ctx->save.p2m_size, precopy);
 }
 
 static int enable_logdirty(struct xc_sr_context *ctx)
@@ -446,8 +486,7 @@ static int update_progress_string(struct xc_sr_context *ctx,
     xc_interface *xch = ctx->xch;
     char *new_str = NULL;
 
-    if ( asprintf(&new_str, "Frames iteration %u of %u",
-                  iter, ctx->save.max_iterations) == -1 )
+    if ( asprintf(&new_str, "Frames iteration %u", iter) == -1 )
     {
         PERROR("Unable to allocate new progress string");
         return -1;
@@ -468,20 +507,47 @@ static int send_memory_live(struct xc_sr_context *ctx)
     xc_interface *xch = ctx->xch;
     xc_shadow_op_stats_t stats = { 0, ctx->save.p2m_size };
     char *progress_str = NULL;
-    unsigned x;
     int rc;
 
+    DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
+                                    &ctx->save.dirty_bitmap_hbuf);
+

tools/libxc/xc_sr_save.c static int send_memory_live(struct xc_sr_context *ctx) · line 523

Quoted 10 lines
tools/libxc/xc_sr_save.c +5 -1
+    int (*precopy_policy)(struct precopy_stats, void *) =
+        ctx->save.callbacks->precopy_policy;
+    void *data = ctx->save.callbacks->data;
+
     rc = update_progress_string(ctx, &progress_str, 0);
     if ( rc )
         goto out;
 
-    rc = send_all_pages(ctx);
+#define CONSULT_POLICY                                                        \

:(

The reason this code is readable and (hopefully) easy to follow, is due in large part to a lack of macros like this trying to hide what is actually going on.

Quoted 20 lines
tools/libxc/xc_sr_save.c +20 -0
+    do {                                                                      \
+        if ( ctx->save.policy_decision == XGS_POLICY_ABORT )                  \
+        {                                                                     \
+            rc = -1;                                                          \
+            goto out;                                                         \
+        }                                                                     \
+        else if ( ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )  \
+        {                                                                     \
+            rc = 0;                                                           \
+            goto out;                                                         \
+        }                                                                     \
+    } while (0)
+
+    ctx->save.stats = (struct precopy_stats)
+        {
+            .iteration     = 0,
+            .total_written = 0,
+            .dirty_count   = -1
+        };
+    rc = send_all_pages(ctx, /* precopy */ true);

tools/libxc/xc_sr_save.c static int send_memory_live(struct xc_sr_context *ctx) · line 550

Quoted 10 lines
tools/libxc/xc_sr_save.c +4 -3
     if ( rc )
         goto out;
 
-    for ( x = 1;
-          ((x < ctx->save.max_iterations) &&
-           (stats.dirty_count > ctx->save.dirty_threshold)); ++x )
+    /* send_all_pages() has updated the stats */
+    CONSULT_POLICY;
+
+    for ( ctx->save.stats.iteration = 1; ; ++ctx->save.stats.iteration )

Again, without an exit condition, this looks suspicious.

~Andrew

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

#24 lore raw

Re: [PATCH RFC 07/20] migration: defer precopy policy to libxl

Quoted 28 lines · Andrew Cooper
Quoted 27 lines · Joshua Otto

The precopy phase of the xc_domain_save() live migration algorithm has historically been implemented to run until either a) (almost) no pages are dirty or b) some fixed, hard-coded maximum number of precopy iterations has been exceeded. This policy and its implementation are less than ideal for a few reasons:
- the logic of the policy is intertwined with the control flow of the mechanism of the precopy stage
- it can't take into account facts external to the immediate migration context, such as interactive user input or the passage of wall-clock time
- it does not permit the user to change their mind, over time, about what to do at the end of the precopy (they get an unconditional transition into the stop-and-copy phase of the migration)

To permit users to implement arbitrary higher-level policies governing when the live migration precopy phase should end, and what should be done next:
- add a precopy_policy() callback to the xc_domain_save() user-supplied callbacks
- during the precopy phase of live migrations, consult this policy after each batch of pages transmitted and take the dictated action, which may be to a) abort the migration entirely, b) continue with the precopy, or c) proceed to the stop-and-copy phase.
- provide an implementation of the old policy as such a callback in libxl and plumb it through the IPC machinery to libxc, effectively maintaing the old policy for now

Quoted 4 lines
Quoted 1 line

This patch should be split into two. One modifying libxc to use struct precopy_stats, and a second to wire up the RPC call.

Will do.

Quoted 19 lines
Quoted 19 lines
---
 tools/libxc/include/xenguest.h     |  23 ++++-
 tools/libxc/xc_nomigrate.c         |   3 +-
 tools/libxc/xc_sr_common.h         |   7 +-
 tools/libxc/xc_sr_save.c           | 194 ++++++++++++++++++++++++++-----------
 tools/libxl/libxl_dom_save.c       |  20 ++++
 tools/libxl/libxl_save_callout.c   |   3 +-
 tools/libxl/libxl_save_helper.c    |   7 +-
 tools/libxl/libxl_save_msgs_gen.pl |   4 +-
 8 files changed, 189 insertions(+), 72 deletions(-)
tools/libxc/include/xenguest.h +0 -0
index aa8cc8b..30ffb6f 100644
@@ -39,6 +39,14 @@
  */
 struct xenevtchn_handle;
 
Quoted 9 lines

tools/libxc/include/xenguest.h line 47

Quoted 6 lines
tools/libxc/include/xenguest.h +6 -0
+/* For save's precopy_policy(). */
+struct precopy_stats
+{
+    unsigned iteration;
+    unsigned total_written;
+    long dirty_count; /* -1 if unknown */

total_written and dirty_count are liable to be equal, so having them as different widths of integer clearly can't be correct.

Hmmm, I could have sworn that I chose the width to match the type of dirty_count in the shadow op stats, but I've checked again and it's uint32_t there so I'm not sure what I was thinking.

Quoted 10 lines
Quoted 10 lines
tools/libxc/include/xenguest.h +2 -0
+};
+
 /* callbacks provided by xc_domain_save */
 struct save_callbacks {
     /* Called after expiration of checkpoint interval,
@@ -46,6 +54,17 @@ struct save_callbacks {
      */
     int (*suspend)(void* data);
 
Quoted 15 lines

tools/libxc/include/xenguest.h struct save_callbacks { · line 66

Quoted 10 lines
tools/libxc/include/xenguest.h +10 -0
+    /* Called after every batch of page data sent during the precopy phase of a
+     * live migration to ask the caller what to do next based on the current
+     * state of the precopy migration.
+     */
+#define XGS_POLICY_ABORT          (-1) /* Abandon the migration entirely and
+                                        * tidy up. */
+#define XGS_POLICY_CONTINUE_PRECOPY 0  /* Remain in the precopy phase. */
+#define XGS_POLICY_STOP_AND_COPY    1  /* Immediately suspend and transmit the
+                                        * remaining dirty pages. */
+    int (*precopy_policy)(struct precopy_stats stats, void *data);

Structures shouldn't be passed by value like this, as the compiler has to do a lot of memcpy() work to make it happen. You should pass by const pointer, as (as far as I can tell), they are strictly read-only to the implementation of this hook?

I chose to pass by value to make the IPC plumbing easier - libxl_save_msgs_gen.pl doesn't know what to do about pointers, and (not being the strongest Perl programmer...) I didn't want to volunteer to be the one to teach it.

Is the memcpy() really significant here? If this were a tight loop, sure, but every invocation of the policy callback implies both a 4MB network transfer _and_ a synchronous RPC.

Quoted 124 lines
Quoted 5 lines
tools/libxc/include/xenguest.h +1 -0
+
     /* Called after the guest's dirty pages have been
      *  copied into an output buffer.
      * Callback function resumes the guest & the device model,

tools/libxc/include/xenguest.h typedef enum { · line 125

Quoted 9 lines
tools/libxc/include/xenguest.h +2 -2
@@ -100,8 +119,8 @@ typedef enum {
  *        doesn't use checkpointing
  * @return 0 on success, -1 on failure
  */
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags /* XCFLAGS_xxx */,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom,
+                   uint32_t flags /* XCFLAGS_xxx */,
                    struct save_callbacks* callbacks, int hvm,
                    xc_migration_stream_t stream_type, int recv_fd);

It would be cleaner for existing callers, and to extend in the future, to encapsulate all of these parameters in a struct domain_save_params and pass it by pointer to here.

That way, we'd avoid the situation we currently have where some information is passed in bitfields in a single parameter, whereas other booleans are passed as integers.

The hvm parameter specifically is useless, and can be removed by rearranging the sanity checks until after the xc_domain_getinfo() call.

Quoted 40 lines
tools/libxc/xc_nomigrate.c +1 -2
index 15c838f..2af64e4 100644
@@ -20,8 +20,7 @@
 #include <xenctrl.h>
 #include <xenguest.h>
 
-int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t max_iters,
-                   uint32_t max_factor, uint32_t flags,
+int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, uint32_t flags,
                    struct save_callbacks* callbacks, int hvm,
                    xc_migration_stream_t stream_type, int recv_fd)
 {
tools/libxc/xc_sr_common.h +3 -4
index b1aa88e..a9160bd 100644
@@ -198,12 +198,11 @@ struct xc_sr_context
             /* Further debugging information in the stream. */
             bool debug;
 
-            /* Parameters for tweaking live migration. */
-            unsigned max_iterations;
-            unsigned dirty_threshold;
-
             unsigned long p2m_size;
 
+            struct precopy_stats stats;
+            int policy_decision;
+
             xen_pfn_t *batch_pfns;
             unsigned nr_batch_pfns;
             unsigned long *deferred_pages;
tools/libxc/xc_sr_save.c +0 -0
index 797aec5..eb95334 100644

tools/libxc/xc_sr_save.c static int write_batch(struct xc_sr_context *ctx) · line 276

Quoted 6 lines
tools/libxc/xc_sr_save.c +3 -0
@@ -271,13 +271,29 @@ static int write_batch(struct xc_sr_context *ctx)
 }
 
 /*
+ * Test if the batch is full.
+ */
+static bool batch_full(struct xc_sr_context *ctx)

const struct xc_sr_context *ctx

This is a predicate, after all.

Quoted 47 lines
tools/libxc/xc_sr_save.c +18 -12
+{
+    return ctx->save.nr_batch_pfns == MAX_BATCH_SIZE;
+}
+
+/*
+ * Test if the batch is empty.
+ */
+static bool batch_empty(struct xc_sr_context *ctx)
+{
+    return ctx->save.nr_batch_pfns == 0;
+}
+
+/*
  * 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 )
+    if ( batch_empty(ctx) )
         return rc;
 
     rc = write_batch(ctx);
@@ -293,19 +309,12 @@ static int flush_batch(struct xc_sr_context *ctx)
 }
 
 /*
- * Add a single pfn to the batch, flushing the batch if full.
+ * Add a single pfn to the batch.
  */
-static int add_to_batch(struct xc_sr_context *ctx, xen_pfn_t pfn)
+static void 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;
+    assert(ctx->save.nr_batch_pfns < MAX_BATCH_SIZE);
+    ctx->save.batch_pfns[ctx->save.nr_batch_pfns++] = pfn;
 }
 
Quoted 13 lines

tools/libxc/xc_sr_save.c static int suspend_domain(struct xc_sr_context *ctx) · line 367

Quoted 9 lines
tools/libxc/xc_sr_save.c +4 -0
 /*
@@ -352,10 +361,15 @@ static int suspend_domain(struct xc_sr_context *ctx)
  * Send a subset of pages in the guests p2m, according to the dirty bitmap.
  * Used for each subsequent iteration of the live migration loop.
  *
+ * During the precopy stage of a live migration, test the user-supplied
+ * policy function after each batch of pages and cut off the operation
+ * early if indicated.  Unless aborting, the dirty pages remaining in this round
+ * are transferred into the deferred_pages bitmap.

Is this actually a sensible thing to do? On iteration 0, this is going to be a phenomenal number of RPC calls, which are all going to make the same decision.

With the existing policy? No. However, the grand idea is to permit other policies where this does make sense. As an example, I think it would be really useful for users to be able to specify a timeout, in seconds, for the precopy phase, after which the migration advances to its next phase (I'll elaborate more on this in the other discussion thread).

It's true that this means a lot of RPC. The hope is that the cost of each RPC should be negligible in comparison to a 4MB synchronous network copy.

Quoted 9 lines

tools/libxc/xc_sr_save.c static int suspend_domain(struct xc_sr_context *ctx) · line 372

Quoted 7 lines
tools/libxc/xc_sr_save.c +2 -1
+ *
  * Bitmap is bounded by p2m_size.
  */
 static int send_dirty_pages(struct xc_sr_context *ctx,
-                            unsigned long entries)
+                            unsigned long entries, bool precopy)

Shouldn't this precopy boolean be some kind of state variable in ctx ?

I suppose it could be. I was a bit worried that there would be objections to piling too many additional variables into the context, because each is essentially an implicit extra parameter to every function here.

Quoted 8 lines
Quoted 8 lines
tools/libxc/xc_sr_save.c +0 -0
 {
     xc_interface *xch = ctx->xch;
     xen_pfn_t p;
@@ -364,31 +378,57 @@ static int send_dirty_pages(struct xc_sr_context *ctx,
     DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
                                     &ctx->save.dirty_bitmap_hbuf);
 
Quoted 10 lines

tools/libxc/xc_sr_save.c static int send_dirty_pages(struct xc_sr_context *ctx, · line 386

Quoted 7 lines
tools/libxc/xc_sr_save.c +6 -1
-    for ( p = 0, written = 0; p < ctx->save.p2m_size; ++p )
+    int (*precopy_policy)(struct precopy_stats, void *) =
+        ctx->save.callbacks->precopy_policy;
+    void *data = ctx->save.callbacks->data;
+
+    assert(batch_empty(ctx));
+    for ( p = 0, written = 0; p < ctx->save.p2m_size; )

This looks suspicious without an increment. Conceptually, it might be better as a do {} while ( decision == XGS_POLICY_CONTINUE_PRECOPY ); loop?

Sure, I think that would read just fine too.

Quoted 120 lines

tools/libxc/xc_sr_save.c static int send_dirty_pages(struct xc_sr_context *ctx, · line 390

Quoted 7 lines
tools/libxc/xc_sr_save.c +3 -2
     {
-        if ( !test_bit(p, dirty_bitmap) )
-            continue;
+        if ( ctx->save.live && precopy )
+        {
+            ctx->save.policy_decision = precopy_policy(ctx->save.stats, data);

Newline here please.

tools/libxc/xc_sr_save.c static int send_dirty_pages(struct xc_sr_context *ctx, · line 392

Quoted 2 lines
tools/libxc/xc_sr_save.c +2 -0
+            if ( ctx->save.policy_decision == XGS_POLICY_ABORT )
+            {

Please but a log message here indicating that abort has been requested. Otherwise, the migration will give up with a failure and no obvious indication why.

tools/libxc/xc_sr_save.c static int send_dirty_pages(struct xc_sr_context *ctx, · line 398

Quoted 6 lines
tools/libxc/xc_sr_save.c +6 -0
+                return -1;
+            }
+            else if ( ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )
+            {
+                /* Any outstanding dirty pages are now deferred until the next
+                 * phase of the migration. */

/*
* The comment style for multiline comments
* is like this.
*/

Quoted 91 lines
tools/libxc/xc_sr_save.c +32 -15
+                bitmap_or(ctx->save.deferred_pages, dirty_bitmap,
+                          ctx->save.p2m_size);
+                if ( entries > written )
+                    ctx->save.nr_deferred_pages += entries - written;
+
+                goto done;
+            }
+        }
 
-        rc = add_to_batch(ctx, p);
+        for ( ; p < ctx->save.p2m_size && !batch_full(ctx); ++p )
+        {
+            if ( test_and_clear_bit(p, dirty_bitmap) )
+            {
+                add_to_batch(ctx, p);
+                ++written;
+                ++ctx->save.stats.total_written;
+            }
+        }
+
+        rc = flush_batch(ctx);
         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;
+        /* Update progress after every batch (4MB) worth of memory sent. */
+        xc_report_progress_step(xch, written, entries);
     }
 
-    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);
 
+ done:
     return ctx->save.ops.check_vm_state(ctx);
 }
 
@@ -396,14 +436,14 @@ static int send_dirty_pages(struct xc_sr_context *ctx,
  * 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)
+static int send_all_pages(struct xc_sr_context *ctx, bool precopy)
 {
     DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
                                     &ctx->save.dirty_bitmap_hbuf);
 
     bitmap_set(dirty_bitmap, ctx->save.p2m_size);
 
-    return send_dirty_pages(ctx, ctx->save.p2m_size);
+    return send_dirty_pages(ctx, ctx->save.p2m_size, precopy);
 }
 
 static int enable_logdirty(struct xc_sr_context *ctx)
@@ -446,8 +486,7 @@ static int update_progress_string(struct xc_sr_context *ctx,
     xc_interface *xch = ctx->xch;
     char *new_str = NULL;
 
-    if ( asprintf(&new_str, "Frames iteration %u of %u",
-                  iter, ctx->save.max_iterations) == -1 )
+    if ( asprintf(&new_str, "Frames iteration %u", iter) == -1 )
     {
         PERROR("Unable to allocate new progress string");
         return -1;
@@ -468,20 +507,47 @@ static int send_memory_live(struct xc_sr_context *ctx)
     xc_interface *xch = ctx->xch;
     xc_shadow_op_stats_t stats = { 0, ctx->save.p2m_size };
     char *progress_str = NULL;
-    unsigned x;
     int rc;
 
+    DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
+                                    &ctx->save.dirty_bitmap_hbuf);
+
+    int (*precopy_policy)(struct precopy_stats, void *) =
+        ctx->save.callbacks->precopy_policy;
+    void *data = ctx->save.callbacks->data;
+
     rc = update_progress_string(ctx, &progress_str, 0);
     if ( rc )
         goto out;
 
Quoted 8 lines

tools/libxc/xc_sr_save.c static int send_memory_live(struct xc_sr_context *ctx) · line 523

Quoted 2 lines
tools/libxc/xc_sr_save.c +1 -1
-    rc = send_all_pages(ctx);
+#define CONSULT_POLICY                                                        \

:(

The reason this code is readable and (hopefully) easy to follow, is due in large part to a lack of macros like this trying to hide what is actually going on.

Okay, I'll inline it. I guess I thought I might get away with it because it's never more than a screen buffer away from its callsites.

Quoted 24 lines
Quoted 24 lines
tools/libxc/xc_sr_save.c +20 -0
+    do {                                                                      \
+        if ( ctx->save.policy_decision == XGS_POLICY_ABORT )                  \
+        {                                                                     \
+            rc = -1;                                                          \
+            goto out;                                                         \
+        }                                                                     \
+        else if ( ctx->save.policy_decision != XGS_POLICY_CONTINUE_PRECOPY )  \
+        {                                                                     \
+            rc = 0;                                                           \
+            goto out;                                                         \
+        }                                                                     \
+    } while (0)
+
+    ctx->save.stats = (struct precopy_stats)
+        {
+            .iteration     = 0,
+            .total_written = 0,
+            .dirty_count   = -1
+        };
+    rc = send_all_pages(ctx, /* precopy */ true);
     if ( rc )
         goto out;
 
Quoted 9 lines

tools/libxc/xc_sr_save.c static int send_memory_live(struct xc_sr_context *ctx) · line 550

Quoted 7 lines
tools/libxc/xc_sr_save.c +4 -3
-    for ( x = 1;
-          ((x < ctx->save.max_iterations) &&
-           (stats.dirty_count > ctx->save.dirty_threshold)); ++x )
+    /* send_all_pages() has updated the stats */
+    CONSULT_POLICY;
+
+    for ( ctx->save.stats.iteration = 1; ; ++ctx->save.stats.iteration )

Again, without an exit condition, this looks suspicious.

Sure, I'll turn this one into a do {} while() too.

Thank you for the review!

Josh

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

#25 lore raw

Re: [PATCH RFC 07/20] migration: defer precopy policy to libxl

Quoted 26 lines · Joshua Otto
Quoted 10 lines
Quoted 10 lines
tools/libxc/include/xenguest.h +2 -0
+};
+
 /* callbacks provided by xc_domain_save */
 struct save_callbacks {
     /* Called after expiration of checkpoint interval,
@@ -46,6 +54,17 @@ struct save_callbacks {
      */
     int (*suspend)(void* data);
 
Quoted 15 lines

tools/libxc/include/xenguest.h struct save_callbacks { · line 66

Quoted 10 lines
tools/libxc/include/xenguest.h +10 -0
+    /* Called after every batch of page data sent during the precopy phase of a
+     * live migration to ask the caller what to do next based on the current
+     * state of the precopy migration.
+     */
+#define XGS_POLICY_ABORT          (-1) /* Abandon the migration entirely and
+                                        * tidy up. */
+#define XGS_POLICY_CONTINUE_PRECOPY 0  /* Remain in the precopy phase. */
+#define XGS_POLICY_STOP_AND_COPY    1  /* Immediately suspend and transmit the
+                                        * remaining dirty pages. */
+    int (*precopy_policy)(struct precopy_stats stats, void *data);

Structures shouldn't be passed by value like this, as the compiler has to do a lot of memcpy() work to make it happen. You should pass by const pointer, as (as far as I can tell), they are strictly read-only to the implementation of this hook?

Quoted 8 lines

I chose to pass by value to make the IPC plumbing easier - libxl_save_msgs_gen.pl doesn't know what to do about pointers, and (not being the strongest Perl programmer...) I didn't want to volunteer to be the one to teach it.

Is the memcpy() really significant here? If this were a tight loop, sure, but every invocation of the policy callback implies both a 4MB network transfer _and_ a synchronous RPC.

Ian, How can Joshua pass a pointer across RPC boundary to avoid excessive copying?

Wei.

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

#26 lore raw

Re: [PATCH RFC 07/20] migration: defer precopy policy to libxl

Wei Liu writes ("Re: [PATCH RFC 07/20] migration: defer precopy policy to libxl"):

Quoted 7 lines · Joshua Otto
Quoted 3 lines

Is the memcpy() really significant here? If this were a tight loop, sure, but every invocation of the policy callback implies both a 4MB network transfer _and_ a synchronous RPC.

Ian, How can Joshua pass a pointer across RPC boundary to avoid excessive copying?

You can't pass a pointer across the IPC boundary. The two bits of code run in different processes, with different address spaces.

Also, this precopy stats struct is tiny: two unsigned and a long. Josuha is entirely right to ask whether the overhead is significant. I think it isn't.

If the performance of the proposed arrangements is inadequate, the whole design needs reconsideration - the synchronous callback is more of a concer, as Joshua suggests. But I assume it's not, or Joshua would have noticed !

Thanks,
Ian.

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

#27 lore raw

RFC PATCH 8/20 libxl/migration: add precopy tuning parameters

In reply to Joshua Otto

In the context of the live migration algorithm, the precopy iteration count refers to the number of page-copying iterations performed prior to the suspension of the guest and transmission of the final set of dirty pages. Similarly, the precopy dirty threshold refers to the dirty page count below which we judge it more profitable to proceed to stop-and-copy rather than continue with the precopy. These would be helpful tuning parameters to work with when migrating particularly busy guests, as they enable an administrator to reap the available benefits of the precopy algorithm (the transmission of guest pages _not_ in the writable working set can be completed without guest downtime) while reducing the total amount of time required for the migration (as iterations of the precopy loop that will certainly be redundant can be skipped in favour of an earlier suspension).

To expose these tuning parameters to users:
- introduce a new libxl API function, libxl_domain_live_migrate(), taking the same parameters as libxl_domain_suspend() _and_ precopy_iterations and precopy_dirty_threshold parameters, and consider these parameters in the precopy policy

(though a pair of new parameters on their own might not warrant an entirely new API function, it is added in anticipation of a number of additional migration-only parameters that would be cumbersome on the whole to tack on to the existing suspend API)

- switch xl migrate to the new libxl_domain_live_migrate() and add new --postcopy-iterations and --postcopy-threshold parameters to pass through

---
 tools/libxl/libxl.h          | 10 ++++++++++
 tools/libxl/libxl_dom_save.c | 20 +++++++++++---------
 tools/libxl/libxl_domain.c   | 27 +++++++++++++++++++++++++--
 tools/libxl/libxl_internal.h |  2 ++
 tools/xl/xl_cmdtable.c       | 22 +++++++++++++---------
 tools/xl/xl_migrate.c        | 31 +++++++++++++++++++++++++++----
 6 files changed, 88 insertions(+), 24 deletions(-)
tools/libxl/libxl.h +10 -0
index 833f866..84ac96a 100644
@@ -1375,6 +1375,16 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd,
 #define LIBXL_SUSPEND_DEBUG 1
 #define LIBXL_SUSPEND_LIVE 2
 
+int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int fd,
+                              int flags, /* LIBXL_SUSPEND_* */
+                              unsigned int precopy_iterations,
+                              unsigned int precopy_dirty_threshold,
+                              const libxl_asyncop_how *ao_how)
+                              LIBXL_EXTERNAL_CALLERS_ONLY;
+
+#define LIBXL_LM_PRECOPY_ITERATIONS_DEFAULT 5
+#define LIBXL_LM_DIRTY_THRESHOLD_DEFAULT 50
+
 /* @param suspend_cancel [from xenctrl.h:xc_domain_resume( @param fast )]
  *   If this parameter is true, use co-operative resume. The guest
  *   must support this.
tools/libxl/libxl_dom_save.c +11 -9
index 6d28cce..10d5012 100644
@@ -332,19 +332,21 @@ int libxl__save_emulator_xenstore_data(libxl__domain_save_state *dss,
  * This is the live migration precopy policy - it's called periodically during
  * the precopy phase of live migrations, and is responsible for deciding when
  * the precopy phase should terminate and what should be done next.
- *
- * The policy implemented here behaves identically to the policy previously
- * hard-coded into xc_domain_save() - it proceeds to the stop-and-copy phase of
- * the live migration when there are either fewer than 50 dirty pages, or more
- * than 5 precopy rounds have completed.
  */
 static int libxl__save_live_migration_simple_precopy_policy(
     struct precopy_stats stats, void *user)
 {
-    return ((stats.dirty_count >= 0 && stats.dirty_count < 50) ||
-            stats.iteration >= 5)
-        ? XGS_POLICY_STOP_AND_COPY
-        : XGS_POLICY_CONTINUE_PRECOPY;
+    libxl__save_helper_state *shs = user;
+    libxl__domain_save_state *dss = shs->caller_state;
+
+    if (stats.dirty_count >= 0 &&
+        stats.dirty_count <= dss->precopy_dirty_threshold)
+        return XGS_POLICY_STOP_AND_COPY;
+
+    if (stats.iteration >= dss->precopy_iterations)
+        return XGS_POLICY_STOP_AND_COPY;
+
+    return XGS_POLICY_CONTINUE_PRECOPY;
 }
 
 /*----- main code for saving, in order of execution -----*/
tools/libxl/libxl_domain.c +25 -2
index 08eccd0..b1cf643 100644
@@ -486,8 +486,10 @@ static void domain_suspend_cb(libxl__egc *egc,
 
 }
 
-int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
-                         const libxl_asyncop_how *ao_how)
+static int do_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
+                             unsigned int precopy_iterations,
+                             unsigned int precopy_dirty_threshold,
+                             const libxl_asyncop_how *ao_how)
 {
     AO_CREATE(ctx, domid, ao_how);
     int rc;
@@ -510,6 +512,8 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
     dss->live = flags & LIBXL_SUSPEND_LIVE;
     dss->debug = flags & LIBXL_SUSPEND_DEBUG;
     dss->checkpointed_stream = LIBXL_CHECKPOINTED_STREAM_NONE;
+    dss->precopy_iterations = precopy_iterations;
+    dss->precopy_dirty_threshold = precopy_dirty_threshold;
 
     rc = libxl__fd_flags_modify_save(gc, dss->fd,
                                      ~(O_NONBLOCK|O_NDELAY), 0,
@@ -523,6 +527,25 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
     return AO_CREATE_FAIL(rc);
 }
 
+int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
+                         const libxl_asyncop_how *ao_how)
+{
+    return do_domain_suspend(ctx, domid, fd, flags,
+                             LIBXL_LM_PRECOPY_ITERATIONS_DEFAULT,
+                             LIBXL_LM_DIRTY_THRESHOLD_DEFAULT, ao_how);
+}
+
+int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
+                              unsigned int precopy_iterations,
+                              unsigned int precopy_dirty_threshold,
+                              const libxl_asyncop_how *ao_how)
+{
+    flags |= LIBXL_SUSPEND_LIVE;
+
+    return do_domain_suspend(ctx, domid, fd, flags, precopy_iterations,
+                             precopy_dirty_threshold, ao_how);
+}
+
 int libxl_domain_pause(libxl_ctx *ctx, uint32_t domid)
 {
     int ret;
tools/libxl/libxl_internal.h +2 -0
index f1d8f9a..45d607a 100644
@@ -3292,6 +3292,8 @@ struct libxl__domain_save_state {
     int live;
     int debug;
     int checkpointed_stream;
+    unsigned int precopy_iterations;
+    unsigned int precopy_dirty_threshold;
     const libxl_domain_remus_info *remus;
     /* private */
     int rc;
tools/xl/xl_cmdtable.c +13 -9
index 7d97811..6df66fb 100644
@@ -157,15 +157,19 @@ struct cmd_spec cmd_table[] = {
       &main_migrate, 0, 1,
       "Migrate a domain to another host",
       "[options] <Domain> <host>",
-      "-h              Print this help.\n"
-      "-C <config>     Send <config> instead of config file from creation.\n"
-      "-s <sshcommand> Use <sshcommand> instead of ssh.  String will be passed\n"
-      "                to sh. If empty, run <host> instead of ssh <host> xl\n"
-      "                migrate-receive [-d -e]\n"
-      "-e              Do not wait in the background (on <host>) for the death\n"
-      "                of the domain.\n"
-      "--debug         Print huge (!) amount of debug during the migration process.\n"
-      "-p              Do not unpause domain after migrating it."
+      "-h                   Print this help.\n"
+      "-C <config>          Send <config> instead of config file from creation.\n"
+      "-s <sshcommand>      Use <sshcommand> instead of ssh.  String will be passed\n"
+      "                     to sh. If empty, run <host> instead of ssh <host> xl\n"
+      "                     migrate-receive [-d -e]\n"
+      "-e                   Do not wait in the background (on <host>) for the death\n"
+      "                     of the domain.\n"
+      "--debug              Print huge (!) amount of debug during the migration process.\n"
+      "-p                   Do not unpause domain after migrating it.\n"
+      "--precopy-iterations Perform at most this many iterations of the precopy\n"
+      "                     memory migration loop before suspending the domain.\n"
+      "--precopy-threshold  If fewer than this many pages are dirty at the end of a\n"
+      "                     copy round, exit the precopy loop and suspend the domain."
     },
     { "restore",
       &main_restore, 0, 1,
tools/xl/xl_migrate.c +27 -4
index 1f0e87d..1bb3fb4 100644
@@ -177,7 +177,9 @@ static void migrate_do_preamble(int send_fd, int recv_fd, pid_t child,
 }
 
 static void migrate_domain(uint32_t domid, const char *rune, int debug,
-                           const char *override_config_file)
+                           const char *override_config_file,
+                           unsigned int precopy_iterations,
+                           unsigned int precopy_dirty_threshold)
 {
     pid_t child = -1;
     int rc;
@@ -205,7 +207,9 @@ static void migrate_domain(uint32_t domid, const char *rune, int debug,
 
     if (debug)
         flags |= LIBXL_SUSPEND_DEBUG;
-    rc = libxl_domain_suspend(ctx, domid, send_fd, flags, NULL);
+    rc = libxl_domain_live_migrate(ctx, domid, send_fd, flags,
+                                   precopy_iterations, precopy_dirty_threshold,
+                                   NULL);
     if (rc) {
         fprintf(stderr, "migration sender: libxl_domain_suspend failed"
                 " (rc=%d)\n", rc);
@@ -537,13 +541,17 @@ int main_migrate(int argc, char **argv)
     char *rune = NULL;
     char *host;
     int opt, daemonize = 1, monitor = 1, debug = 0, pause_after_migration = 0;
+    int precopy_iterations = LIBXL_LM_PRECOPY_ITERATIONS_DEFAULT,
+        precopy_dirty_threshold = LIBXL_LM_DIRTY_THRESHOLD_DEFAULT;
     static struct option opts[] = {
         {"debug", 0, 0, 0x100},
         {"live", 0, 0, 0x200},
+        {"precopy-iterations", 1, 0, 'i'},
+        {"precopy-threshold", 1, 0, 'd'},
         COMMON_LONG_OPTS
     };
 
-    SWITCH_FOREACH_OPT(opt, "FC:s:ep", opts, "migrate", 2) {
+    SWITCH_FOREACH_OPT(opt, "FC:s:epi:d:", opts, "migrate", 2) {
     case 'C':
         config_filename = optarg;
         break;
@@ -560,6 +568,20 @@ int main_migrate(int argc, char **argv)
     case 'p':
         pause_after_migration = 1;
         break;
+    case 'i':
+        precopy_iterations = atoi(optarg);
+        if (precopy_iterations < 0) {
+            fprintf(stderr, "negative precopy iterations not supported\n");
+            return EXIT_FAILURE;
+        }
+        break;
+    case 'd':
+        precopy_dirty_threshold = atoi(optarg);
+        if (precopy_dirty_threshold < 0) {
+            fprintf(stderr, "negative dirty threshold not supported\n");
+            return EXIT_FAILURE;
+        }
+        break;
     case 0x100: /* --debug */
         debug = 1;
         break;
@@ -596,7 +618,8 @@ int main_migrate(int argc, char **argv)
                   pause_after_migration ? " -p" : "");
     }
 
-    migrate_domain(domid, rune, debug, config_filename);
+    migrate_domain(domid, rune, debug, config_filename, precopy_iterations,
+                   precopy_dirty_threshold);
     return EXIT_SUCCESS;
 }
 
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#28 lore raw

Re: [PATCH RFC 08/20] libxl/migration: add precopy tuning parameters

Quoted 25 lines · Joshua Otto

In the context of the live migration algorithm, the precopy iteration count refers to the number of page-copying iterations performed prior to the suspension of the guest and transmission of the final set of dirty pages. Similarly, the precopy dirty threshold refers to the dirty page count below which we judge it more profitable to proceed to stop-and-copy rather than continue with the precopy. These would be helpful tuning parameters to work with when migrating particularly busy guests, as they enable an administrator to reap the available benefits of the precopy algorithm (the transmission of guest pages _not_ in the writable working set can be completed without guest downtime) while reducing the total amount of time required for the migration (as iterations of the precopy loop that will certainly be redundant can be skipped in favour of an earlier suspension).

To expose these tuning parameters to users:
- introduce a new libxl API function, libxl_domain_live_migrate(), taking the same parameters as libxl_domain_suspend() _and_ precopy_iterations and precopy_dirty_threshold parameters, and consider these parameters in the precopy policy

(though a pair of new parameters on their own might not warrant an entirely new API function, it is added in anticipation of a number of additional migration-only parameters that would be cumbersome on the whole to tack on to the existing suspend API)

Quoted 5 lines

- switch xl migrate to the new libxl_domain_live_migrate() and add new --postcopy-iterations and --postcopy-threshold parameters to pass through

This will have to defer to the tools maintainers, but I purposefully didn't expose these knobs to users when rewriting live migration, because they cannot be meaningfully chosen by anyone outside of a testing scenario. (That is not to say they aren't useful for testing purposes, but I didn't upstream my version of this patch.)

I spent quite a while wondering how best to expose these tunables in a way that end users could sensibly use them, and the best I came up with was this:

First, run the guest under logdirty for a period of time to establish the working set, and how steady it is. From this, you have a baseline for the target threshold, and a plausible way of estimating the downtime. (Better yet, as XenCenter, XenServers windows GUI, has proved time and time again, users love graphs! Even if they don't necessarily understand them.)

From this baseline, the conditions you need to care about are the rate of convergence. On a steady VM, you should converge asymptotically to the measured threshold, although on 5 or fewer iterations, the asymptotic properties don't appear cleanly. (Of course, the larger the VM, the more iterations, and the more likely to spot this.)

Users will either care about the migration completing successfully, or avoiding interrupting the workload. The majority case would be both, but every user will have one of these two options which is more important than the other. As a result, there need to be some options to cover "if $X happens, do I continue or abort".

The case where the VM becomes more busy is harder however. For the users which care about not interrupting the workload, there will be a point above which they'd prefer to abort the migration rather than continue it. For the users which want the migration to complete, they'd prefer to pause the VM and take a downtime hit, rather than aborting.

Therefore, you really need two thresholds; the one above which you always abort, the one where you would normally choose to pause. The decision as to what to do depends on where you are between these thresholds when the dirty state converges. (Of course, if the VM suddenly becomes more idle, it is sensible to continue beyond the lower threshold, as it will reduce the downtime.) The absolute number of iterations on the other hand doesn't actually matter from a users point of view, so isn't a useful control to have.

Another thing to be careful with is the measure of convergence with respect to guest busyness, and other factors influencing the absolute iteration time, such as congestion of the network between the two hosts. I haven't yet come up with a sensible way of reconciling this with the above, in a way which can be expressed as a useful set of controls.

The plan, following migration v2, was always to come back to this and see about doing something better than the current hard coded parameters, but I am still working on fixing migration in other areas (not having VMs crash when moving, because they observe important differences in the hardware).

How does your postcopy proposal influence/change the above logic?

~Andrew

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

#29 lore raw

Re: [PATCH RFC 08/20] libxl/migration: add precopy tuning parameters

Quoted 30 lines · Andrew Cooper
Quoted 29 lines · Joshua Otto

In the context of the live migration algorithm, the precopy iteration count refers to the number of page-copying iterations performed prior to the suspension of the guest and transmission of the final set of dirty pages. Similarly, the precopy dirty threshold refers to the dirty page count below which we judge it more profitable to proceed to stop-and-copy rather than continue with the precopy. These would be helpful tuning parameters to work with when migrating particularly busy guests, as they enable an administrator to reap the available benefits of the precopy algorithm (the transmission of guest pages _not_ in the writable working set can be completed without guest downtime) while reducing the total amount of time required for the migration (as iterations of the precopy loop that will certainly be redundant can be skipped in favour of an earlier suspension).

To expose these tuning parameters to users:
- introduce a new libxl API function, libxl_domain_live_migrate(), taking the same parameters as libxl_domain_suspend() _and_ precopy_iterations and precopy_dirty_threshold parameters, and consider these parameters in the precopy policy

(though a pair of new parameters on their own might not warrant an entirely new API function, it is added in anticipation of a number of additional migration-only parameters that would be cumbersome on the whole to tack on to the existing suspend API)

- switch xl migrate to the new libxl_domain_live_migrate() and add new --postcopy-iterations and --postcopy-threshold parameters to pass through

Quoted 7 lines
Quoted 1 line

This will have to defer to the tools maintainers, but I purposefully didn't expose these knobs to users when rewriting live migration, because they cannot be meaningfully chosen by anyone outside of a testing scenario. (That is not to say they aren't useful for testing purposes, but I didn't upstream my version of this patch.)

Ahhh, I wondered why those parameters to xc_domain_save() were present but ignored. That's reasonable.

I guess the way I had imagined an administrator using them would be in a non-production/test environment - if they could run workloads representative of their production application in this environment, they could experiment with different --precopy-iterations and --precopy-threshold values (having just a high-level understanding of what they control) and choose the ones that result in the best outcome for later use in production.

Quoted 45 lines

I spent quite a while wondering how best to expose these tunables in a way that end users could sensibly use them, and the best I came up with was this:

First, run the guest under logdirty for a period of time to establish the working set, and how steady it is. From this, you have a baseline for the target threshold, and a plausible way of estimating the downtime. (Better yet, as XenCenter, XenServers windows GUI, has proved time and time again, users love graphs! Even if they don't necessarily understand them.)

From this baseline, the conditions you need to care about are the rate of convergence. On a steady VM, you should converge asymptotically to the measured threshold, although on 5 or fewer iterations, the asymptotic properties don't appear cleanly. (Of course, the larger the VM, the more iterations, and the more likely to spot this.)

Users will either care about the migration completing successfully, or avoiding interrupting the workload. The majority case would be both, but every user will have one of these two options which is more important than the other. As a result, there need to be some options to cover "if $X happens, do I continue or abort".

The case where the VM becomes more busy is harder however. For the users which care about not interrupting the workload, there will be a point above which they'd prefer to abort the migration rather than continue it. For the users which want the migration to complete, they'd prefer to pause the VM and take a downtime hit, rather than aborting.

Therefore, you really need two thresholds; the one above which you always abort, the one where you would normally choose to pause. The decision as to what to do depends on where you are between these thresholds when the dirty state converges. (Of course, if the VM suddenly becomes more idle, it is sensible to continue beyond the lower threshold, as it will reduce the downtime.) The absolute number of iterations on the other hand doesn't actually matter from a users point of view, so isn't a useful control to have.

Another thing to be careful with is the measure of convergence with respect to guest busyness, and other factors influencing the absolute iteration time, such as congestion of the network between the two hosts. I haven't yet come up with a sensible way of reconciling this with the above, in a way which can be expressed as a useful set of controls.

Quoted 5 lines

The plan, following migration v2, was always to come back to this and see about doing something better than the current hard coded parameters, but I am still working on fixing migration in other areas (not having VMs crash when moving, because they observe important differences in the hardware).

I think a good strategy would be to solicit three parameters from the user:
- the precopy duration they're willing to tolerate
- the downtime duration they're willing to tolerate
- the bandwidth of the link between the hosts (we could try and estimate it for them but I'd rather just make them run iperf)

Then, after applying this patch, alter the policy so that precopy simply runs for the duration that the user is willing to wait. After that, using the bandwidth estimate, compute the approximate downtime required to transfer the final set of dirty-pages. If this is less than what the user indicated is acceptable, proceed with the stop-and-copy - otherwise abort.

This still requires the user to figure out for themselves how long their workload can really wait, but hopefully they already had some idea before deciding to attempt live migration in the first place.

Quoted 1 line

How does your postcopy proposal influence/change the above logic?

Well, the 'downtime' phase of the migration becomes a very short, fixed interval, regardless of guest busyness, so you can't ask the user 'how much downtime can you tolerate?' Instead, the question becomes the murkier 'how much memory performance degradation can your guest tolerate?' I.e. is the postcopy migration going to essentially be downtime, or can useful work get done between faults? (for example, guests that are I/O bound would do much better with postcopy than they would with a long stop-and-copy)

To answer that question, they're back to the approach I outlined at the beginning - they'd have to experiment in a test environment and observe their workload's response to the alternatives to make an informed choice.

Cheers,

Josh

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

#30 lore raw

Re: [PATCH RFC 08/20] libxl/migration: add precopy tuning parameters

Quoted 42 lines · Joshua Otto
Quoted 30 lines · Andrew Cooper
Quoted 29 lines · Joshua Otto

In the context of the live migration algorithm, the precopy iteration count refers to the number of page-copying iterations performed prior to the suspension of the guest and transmission of the final set of dirty pages. Similarly, the precopy dirty threshold refers to the dirty page count below which we judge it more profitable to proceed to stop-and-copy rather than continue with the precopy. These would be helpful tuning parameters to work with when migrating particularly busy guests, as they enable an administrator to reap the available benefits of the precopy algorithm (the transmission of guest pages _not_ in the writable working set can be completed without guest downtime) while reducing the total amount of time required for the migration (as iterations of the precopy loop that will certainly be redundant can be skipped in favour of an earlier suspension).

To expose these tuning parameters to users:
- introduce a new libxl API function, libxl_domain_live_migrate(), taking the same parameters as libxl_domain_suspend() _and_ precopy_iterations and precopy_dirty_threshold parameters, and consider these parameters in the precopy policy

(though a pair of new parameters on their own might not warrant an entirely new API function, it is added in anticipation of a number of additional migration-only parameters that would be cumbersome on the whole to tack on to the existing suspend API)

- switch xl migrate to the new libxl_domain_live_migrate() and add new --postcopy-iterations and --postcopy-threshold parameters to pass through

Quoted 7 lines
Quoted 1 line

This will have to defer to the tools maintainers, but I purposefully didn't expose these knobs to users when rewriting live migration, because they cannot be meaningfully chosen by anyone outside of a testing scenario. (That is not to say they aren't useful for testing purposes, but I didn't upstream my version of this patch.)

Ahhh, I wondered why those parameters to xc_domain_save() were present but ignored. That's reasonable.

Quoted 8 lines

I guess the way I had imagined an administrator using them would be in a non-production/test environment - if they could run workloads representative of their production application in this environment, they could experiment with different --precopy-iterations and --precopy-threshold values (having just a high-level understanding of what they control) and choose the ones that result in the best outcome for later use in production.

Running in a test environment isn't always an option -- think about public cloud providers who don't have control over the VMs or the workload.

Quoted 38 lines
Quoted 38 lines

I spent quite a while wondering how best to expose these tunables in a way that end users could sensibly use them, and the best I came up with was this:

First, run the guest under logdirty for a period of time to establish the working set, and how steady it is. From this, you have a baseline for the target threshold, and a plausible way of estimating the downtime. (Better yet, as XenCenter, XenServers windows GUI, has proved time and time again, users love graphs! Even if they don't necessarily understand them.)

From this baseline, the conditions you need to care about are the rate of convergence. On a steady VM, you should converge asymptotically to the measured threshold, although on 5 or fewer iterations, the asymptotic properties don't appear cleanly. (Of course, the larger the VM, the more iterations, and the more likely to spot this.)

Users will either care about the migration completing successfully, or avoiding interrupting the workload. The majority case would be both, but every user will have one of these two options which is more important than the other. As a result, there need to be some options to cover "if $X happens, do I continue or abort".

The case where the VM becomes more busy is harder however. For the users which care about not interrupting the workload, there will be a point above which they'd prefer to abort the migration rather than continue it. For the users which want the migration to complete, they'd prefer to pause the VM and take a downtime hit, rather than aborting.

Therefore, you really need two thresholds; the one above which you always abort, the one where you would normally choose to pause. The decision as to what to do depends on where you are between these thresholds when the dirty state converges. (Of course, if the VM suddenly becomes more idle, it is sensible to continue beyond the lower threshold, as it will reduce the downtime.) The absolute number of iterations on the other hand doesn't actually matter from a users point of view, so isn't a useful control to have.

Quoted 6 lines
Quoted 6 lines

Another thing to be careful with is the measure of convergence with respect to guest busyness, and other factors influencing the absolute iteration time, such as congestion of the network between the two hosts. I haven't yet come up with a sensible way of reconciling this with the above, in a way which can be expressed as a useful set of controls.

My thought as well.

Quoted 21 lines
Quoted 6 lines

The plan, following migration v2, was always to come back to this and see about doing something better than the current hard coded parameters, but I am still working on fixing migration in other areas (not having VMs crash when moving, because they observe important differences in the hardware).

I think a good strategy would be to solicit three parameters from the user:
- the precopy duration they're willing to tolerate
- the downtime duration they're willing to tolerate
- the bandwidth of the link between the hosts (we could try and estimate it for them but I'd rather just make them run iperf)

Then, after applying this patch, alter the policy so that precopy simply runs for the duration that the user is willing to wait. After that, using the bandwidth estimate, compute the approximate downtime required to transfer the final set of dirty-pages. If this is less than what the user indicated is acceptable, proceed with the stop-and-copy - otherwise abort.

Quoted 4 lines

This still requires the user to figure out for themselves how long their workload can really wait, but hopefully they already had some idea before deciding to attempt live migration in the first place.

I am not entirely sure what to make of this. I'm not convinced using durations would cover all cases, but I can't come up with a counter example that doesn't sound contrived.

Given this series is already complex enough, I think we should set this aside for another day.

How hard would it be to _not_ include all the knobs in this series?

Wei.

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

#31 lore raw

Re: [PATCH RFC 08/20] libxl/migration: add precopy tuning parameters

Quoted 10 lines · Wei Liu
Quoted 8 lines · Joshua Otto

I guess the way I had imagined an administrator using them would be in a non-production/test environment - if they could run workloads representative of their production application in this environment, they could experiment with different --precopy-iterations and --precopy-threshold values (having just a high-level understanding of what they control) and choose the ones that result in the best outcome for later use in production.

Quoted 3 lines

Running in a test environment isn't always an option -- think about public cloud providers who don't have control over the VMs or the workload.

Sure, it definitely won't always be an option, but sometimes it might. The question is whether or not the benefit in the cases where it can be used justifies the added complexity to the interface. I think so, but that's just my intuition.

Quoted 26 lines
Quoted 21 lines
Quoted 6 lines

The plan, following migration v2, was always to come back to this and see about doing something better than the current hard coded parameters, but I am still working on fixing migration in other areas (not having VMs crash when moving, because they observe important differences in the hardware).

I think a good strategy would be to solicit three parameters from the user:
- the precopy duration they're willing to tolerate
- the downtime duration they're willing to tolerate
- the bandwidth of the link between the hosts (we could try and estimate it for them but I'd rather just make them run iperf)

Then, after applying this patch, alter the policy so that precopy simply runs for the duration that the user is willing to wait. After that, using the bandwidth estimate, compute the approximate downtime required to transfer the final set of dirty-pages. If this is less than what the user indicated is acceptable, proceed with the stop-and-copy - otherwise abort.

Quoted 4 lines

This still requires the user to figure out for themselves how long their workload can really wait, but hopefully they already had some idea before deciding to attempt live migration in the first place.

Quoted 8 lines

I am not entirely sure what to make of this. I'm not convinced using durations would cover all cases, but I can't come up with a counter example that doesn't sound contrived.

Given this series is already complex enough, I think we should set this aside for another day.

How hard would it be to _not_ include all the knobs in this series?

Fair enough. It wouldn't be much trouble, so I'll drop it for now.

As a general comment on the patch series for anyone following: I've just finished with the last of my academic commitments and now have time to pick this back up. I'll follow up in the next few weeks with the suggested revisions, the design document and the quantitative performance evaluation.

Thanks!

Josh

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

#32 lore raw

RFC PATCH 9/20 libxc/xc_sr_save: introduce save batch types

In reply to Joshua Otto

To write guest pages into the stream, the save logic builds up batches of pfns to be written and performs all of the work necessary to write them whenever a full batch has been accumulated. Writing a PAGE_DATA batch entails determining the types of all pfns in the batch, mapping the subset of pfns that are backed by real memory constructing a PAGE_DATA record describing the batch and writing everything into the stream.

Postcopy live migration introduces several new types of batches. To enable the postcopy logic to re-use the bulk of the code used to manage and write PAGE_DATA records, introduce a batch_type member to the save context (which for now can take on only a single value), and refactor write_batch() to take the batch_type into account when preparing and writing each record.

While refactoring write_batch(), factor the operation of querying the page types of a batch into a subroutine that is useable independently of write_batch().

No functional change.

---
 tools/libxc/xc_sr_common.h    |   3 +
 tools/libxc/xc_sr_save.c      | 217 ++++++++++++++++++++++++++++--------------
 tools/libxc/xg_save_restore.h |   2 +-
 3 files changed, 151 insertions(+), 71 deletions(-)
tools/libxc/xc_sr_common.h +3 -0
index a9160bd..ee463d9 100644
@@ -203,6 +203,9 @@ struct xc_sr_context
             struct precopy_stats stats;
             int policy_decision;
 
+            enum {
+                XC_SR_SAVE_BATCH_PRECOPY_PAGE
+            } batch_type;
             xen_pfn_t *batch_pfns;
             unsigned nr_batch_pfns;
             unsigned long *deferred_pages;
tools/libxc/xc_sr_save.c +147 -70

322 lines not on this page · raw message

tools/libxc/xg_save_restore.h +1 -1
index 303081d..40debf6 100644
@@ -24,7 +24,7 @@
 ** We process save/restore/migrate in batches of pages; the below
 ** determines how many pages we (at maximum) deal with in each batch.
 */
-#define MAX_BATCH_SIZE 1024   /* up to 1024 pages (4MB) at a time */
+#define MAX_PRECOPY_BATCH_SIZE 1024   /* up to 1024 pages (4MB) at a time */
 
 /* When pinning page tables at the end of restore, we also use batching. */
 #define MAX_PIN_BATCH  1024
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#33 lore raw

RFC PATCH 10/20 libxc/xc_sr_save.c: initialise rec.data before free()

In reply to Joshua Otto

colo_merge_secondary_dirty_bitmap() unconditionally free()s the .data member of its local xc_sr_record structure rec on its exit path. However, if the initial call to read_record() fails then this member is uninitialised. Initialise it.

---
 tools/libxc/xc_sr_save.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/libxc/xc_sr_save.c +1 -1
index ac97d93..6acc8d3 100644
@@ -681,7 +681,7 @@ static int send_memory_live(struct xc_sr_context *ctx)
 static int colo_merge_secondary_dirty_bitmap(struct xc_sr_context *ctx)
 {
     xc_interface *xch = ctx->xch;
-    struct xc_sr_record rec;
+    struct xc_sr_record rec = { 0, 0, NULL };
     uint64_t *pfns = NULL;
     uint64_t pfn;
     unsigned count, i;
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
Reviewed-by on v1 10/20
#34 lore raw

Re: [PATCH RFC 10/20] libxc/xc_sr_save.c: initialise rec.data before free()

Quoted 6 lines · Joshua Otto

colo_merge_secondary_dirty_bitmap() unconditionally free()s the .data member of its local xc_sr_record structure rec on its exit path. However, if the initial call to read_record() fails then this member is uninitialised. Initialise it.

This bugfix should be taken ASAP, and needs backporting to Xen 4.7 and 4.8

Quoted 9 lines
---
 tools/libxc/xc_sr_save.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/libxc/xc_sr_save.c +0 -0
index ac97d93..6acc8d3 100644

tools/libxc/xc_sr_save.c static int send_memory_live(struct xc_sr_context *ctx) · line 687

Quoted 8 lines
tools/libxc/xc_sr_save.c +1 -1
@@ -681,7 +681,7 @@ static int send_memory_live(struct xc_sr_context *ctx)
 static int colo_merge_secondary_dirty_bitmap(struct xc_sr_context *ctx)
 {
     xc_interface *xch = ctx->xch;
-    struct xc_sr_record rec;
+    struct xc_sr_record rec = { 0, 0, NULL };
     uint64_t *pfns = NULL;
     uint64_t pfn;
     unsigned count, i;

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

#35 lore raw

Re: [PATCH RFC 10/20] libxc/xc_sr_save.c: initialise rec.data before free()

Quoted 11 lines · Andrew Cooper
Quoted 6 lines · Joshua Otto

colo_merge_secondary_dirty_bitmap() unconditionally free()s the .data member of its local xc_sr_record structure rec on its exit path. However, if the initial call to read_record() fails then this member is uninitialised. Initialise it.

This bugfix should be taken ASAP, and needs backporting to Xen 4.7 and 4.8

Acked + applied.

Quoted 5 lines
Quoted 5 lines
---
 tools/libxc/xc_sr_save.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Quoted 14 lines

tools/libxc/xc_sr_save.c static int send_memory_live(struct xc_sr_context *ctx) · line 687

Quoted 13 lines
tools/libxc/xc_sr_save.c +1 -1
index ac97d93..6acc8d3 100644
@@ -681,7 +681,7 @@ static int send_memory_live(struct xc_sr_context *ctx)
 static int colo_merge_secondary_dirty_bitmap(struct xc_sr_context *ctx)
 {
     xc_interface *xch = ctx->xch;
-    struct xc_sr_record rec;
+    struct xc_sr_record rec = { 0, 0, NULL };
     uint64_t *pfns = NULL;
     uint64_t pfn;
     unsigned count, i;

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

#36 lore raw

RFC PATCH 11/20 libxc/migration: correct hvm record ordering specification

In reply to Joshua Otto

The libxc migration stream specification document asserts that, within an hvm migration stream, "HVM_PARAMS must precede HVM_CONTEXT, as certain parameters can affect the validity of architectural state in the context." This sounds reasonable, but the in-tree implementation of hvm domain save actually writes these records in the _reverse_ order, with HVM_CONTEXT first and HVM_PARAMS next. This has been the case for the entire history of that implementation, seemingly to no ill effect, so update the spec to reflect this.

---
 docs/specs/libxc-migration-stream.pandoc | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
docs/specs/libxc-migration-stream.pandoc +2 -5
index 31eba10..96a6cb0 100644
@@ -668,11 +668,8 @@ A typical save record for an x86 HVM guest image would look like:
 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.
+5. HVM\_CONTEXT
+6. HVM\_PARAMS
 
 
 Legacy Images (x86 only)
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#37 lore raw

RFC PATCH 12/20 libxc/migration: specify postcopy live migration

In reply to Joshua Otto

- allocate the new postcopy record type numbers
- augment the stream format specification to include these new types and their role in the protocol

---
 docs/specs/libxc-migration-stream.pandoc | 177 ++++++++++++++++++++++++++++++-
 tools/libxc/xc_sr_common.c               |   7 ++
 tools/libxc/xc_sr_stream_format.h        |   9 +-
 3 files changed, 191 insertions(+), 2 deletions(-)
docs/specs/libxc-migration-stream.pandoc +176 -1
index 96a6cb0..8ff8da5 100644
@@ -3,7 +3,8 @@
   Andrew Cooper <<[email protected]>>
   Wen Congyang <<[email protected]>>
   Yang Hongyang <<[email protected]>>
-% Revision 1
+  Joshua Otto <<[email protected]>>
+% Revision 2
 
 Introduction
 ============
@@ -231,6 +232,20 @@ type         0x00000000: END
 
              0x0000000F: CHECKPOINT_DIRTY_PFN_LIST (Secondary -> Primary)
 
+             0x00000010: POSTCOPY_BEGIN
+
+             0x00000011: POSTCOPY_PFNS_BEGIN
+
+             0x00000012: POSTCOPY_PFNS
+
+             0x00000013: POSTCOPY_TRANSITION
+
+             0x00000014: POSTCOPY_PAGE_DATA
+
+             0x00000015: POSTCOPY_FAULT
+
+             0x00000016: POSTCOPY_COMPLETE
+
              0x00000010 - 0x7FFFFFFF: Reserved for future _mandatory_
              records.
 
@@ -624,6 +639,142 @@ The count of pfns is: record->length/sizeof(uint64_t).
 
 \clearpage
 
+POSTCOPY_BEGIN
+--------------
+
+This record must only appear in a truly _live_ migration stream, and is
+transmitted by the migration sender to signal to the destination that
+the migration will (as soon as possible) transition from the memory
+pre-copy phase to the post-copy phase, during which remaining unmigrated
+domain memory is paged over the network on-demand _after_ the guest has
+resumed.
+
+This record _must_ be followed immediately by the domain CPU context
+records (e.g. TSC_INFO, HVM_CONTEXT and HVM_PARAMS for HVM domains).
+This is for practical reasons: in the HVM case, the PAGING_RING_PFN
+parameter must be known at the destination before preparation for paging
+can begin.
+
+This record contains no fields; its body_length is 0.
+
+\clearpage
+
+POSTCOPY_PFNS_BEGIN
+-------------------
+
+During the initiation sequence of a postcopy live migration, this record
+immediately follows the final domain CPU context record and indicates
+the beginning of a sequence of 0 or more POSTCOPY_PFNS records.  The
+destination uses this record as a cue to prepare for postcopy paging.
+
+This record contains no fields; its body_length is 0.
+
+\clearpage
+
+POSTCOPY_PFNS
+-------------
+
+Each POSTCOPY_PFNS record contains an unordered list of 'postcopy PFNS'
+- i.e. pfns that are dirty at the sender and require migration during
+the postcopy phase.  The structure of the record is identical that of
+the PAGE_DATA record type, but omitting any actual trailing page
+contents.
+
+     0     1     2     3     4     5     6     7 octet
+    +-----------------------+-------------------------+
+    | count (C)             | (reserved)              |
+    +-----------------------+-------------------------+
+    | pfn[0]                                          |
+    +-------------------------------------------------+
+    ...
+    +-------------------------------------------------+
+    | pfn[C-1]                                        |
+    +-------------------------------------------------+
+
+\clearpage
+
+POSTCOPY_TRANSITION
+-------------------
+
+This record is transmitted by a postcopy live migration sender after the
+final POSTCOPY_PFNS record, and indicates that the embedded libxc stream
+will be interrupted by content in the higher-layer stream necessary to
+permit resumption of the domain at the destination, and further than
+when the higher-layer content is complete the domain should be resumed
+in postcopy mode at the destination.
+
+This record contains no fields; its body_length is 0.
+
+\clearpage
+
+POSTCOPY_PAGE_DATA
+------------------
+
+This record is identical in meaning and format to the PAGE_DATA record
+type, and is transmitted during live migration by the sender during the
+postcopy phase to transfer batches of outstanding domain memory.
+
+     0     1     2     3     4     5     6     7 octet
+    +-----------------------+-------------------------+
+    | count (C)             | (reserved)              |
+    +-----------------------+-------------------------+
+    | pfn[0]                                          |
+    +-------------------------------------------------+
+    ...
+    +-------------------------------------------------+
+    | pfn[C-1]                                        |
+    +-------------------------------------------------+
+    | page_data[0]...                                 |
+    ...
+    +-------------------------------------------------+
+    | page_data[C-1]...                               |
+    ...
+    +-------------------------------------------------+
+
+It is an error for an XTAB, BROKEN or XALLOC pfn to be transmitted in a
+record of this type, so all pfns must be accompanied by backing data.
+It is an error for a pfn not previously included in a POSTCOPY_PFNS
+record to be included in a record of this type.
+
+\clearpage
+
+POSTCOPY_FAULT
+--------------
+
+A POSTCOPY_FAULT record is transmitted by a postcopy live migration
+_destination_ to communicate an urgent need for a batch of pfns.  It is
+identical in format to the POSTCOPY_PFNS record type, _except_ that the
+type of each page is not encoded in the transmitted pfns.
+
+     0     1     2     3     4     5     6     7 octet
+    +-----------------------+-------------------------+
+    | count (C)             | (reserved)              |
+    +-----------------------+-------------------------+
+    | pfn[0]                                          |
+    +-------------------------------------------------+
+    ...
+    +-------------------------------------------------+
+    | pfn[C-1]                                        |
+    +-------------------------------------------------+
+
+\clearpage
+
+POSTCOPY_COMPLETE
+-----------------
+
+A postcopy live migration _destination_ transmits a POSTCOPY_COMPLETE
+record when the postcopy phase of a migration is complete, if one was
+entered.
+
+This record contains no fields; its body_length is 0.
+
+In addition to reporting the phase completion to the sender, this record
+also enables the migration sender to flush its receive stream of
+in-flight POSTCOPY_FAULT records before handing control of the stream
+back to a higher layer.
+
+\clearpage
+
 Layout
 ======
 
@@ -671,6 +822,30 @@ A typical save record for an x86 HVM guest image would look like:
 5. HVM\_CONTEXT
 6. HVM\_PARAMS
 
+x86 HVM Postcopy Live Migration
+-------------------------------
+
+The bi-directional migration stream for postcopy live migration of an
+x86 HVM guest image would look like:
+
+ 1. Image header
+ 2. Domain header
+ 3. Many (or few!) PAGE\_DATA records
+ 4. POSTCOPY\_BEGIN
+ 5. TSC\_INFO
+ 6. HVM\_CONTEXT
+ 7. HVM\_PARAMS
+ 8. POSTCOPY\_PFNS\_BEGIN
+ 9. Many POSTCOPY\_PFNS records
+10. POSTCOPY\_TRANSITION
+... higher layer stream content ...
+11. Many POSTCOPY\_PAGE\_DATA records
+
+During 11, the destination would reply with (hopefully not too) many
+POSTCOPY\_FAULT records.
+
+After 11, the destination would transmit a final POSTCOPY\_COMPLETE.
+
 
 Legacy Images (x86 only)
 ========================
tools/libxc/xc_sr_common.c +7 -0
index f443974..090b5fd 100644
@@ -38,6 +38,13 @@ static const char *mandatory_rec_types[] =
     [REC_TYPE_VERIFY]                       = "Verify",
     [REC_TYPE_CHECKPOINT]                   = "Checkpoint",
     [REC_TYPE_CHECKPOINT_DIRTY_PFN_LIST]    = "Checkpoint dirty pfn list",
+    [REC_TYPE_POSTCOPY_BEGIN]               = "Postcopy begin",
+    [REC_TYPE_POSTCOPY_PFNS_BEGIN]          = "Postcopy pfns begin",
+    [REC_TYPE_POSTCOPY_PFNS]                = "Postcopy pfns",
+    [REC_TYPE_POSTCOPY_TRANSITION]          = "Postcopy transition",
+    [REC_TYPE_POSTCOPY_PAGE_DATA]           = "Postcopy page data",
+    [REC_TYPE_POSTCOPY_FAULT]               = "Postcopy fault",
+    [REC_TYPE_POSTCOPY_COMPLETE]            = "Postcopy complete",
 };
 
 const char *rec_type_to_str(uint32_t type)
tools/libxc/xc_sr_stream_format.h +8 -1
index 32400b2..d16d0c7 100644
@@ -76,10 +76,17 @@ struct xc_sr_rhdr
 #define REC_TYPE_VERIFY                     0x0000000dU
 #define REC_TYPE_CHECKPOINT                 0x0000000eU
 #define REC_TYPE_CHECKPOINT_DIRTY_PFN_LIST  0x0000000fU
+#define REC_TYPE_POSTCOPY_BEGIN             0x00000010U
+#define REC_TYPE_POSTCOPY_PFNS_BEGIN        0x00000011U
+#define REC_TYPE_POSTCOPY_PFNS              0x00000012U
+#define REC_TYPE_POSTCOPY_TRANSITION        0x00000013U
+#define REC_TYPE_POSTCOPY_PAGE_DATA         0x00000014U
+#define REC_TYPE_POSTCOPY_FAULT             0x00000015U
+#define REC_TYPE_POSTCOPY_COMPLETE          0x00000016U
 
 #define REC_TYPE_OPTIONAL             0x80000000U
 
-/* PAGE_DATA */
+/* PAGE_DATA/POSTCOPY_PFNS/POSTCOPY_PAGE_DATA/POSTCOPY_FAULT */
 struct xc_sr_rec_pages_header
 {
     uint32_t count;
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#38 lore raw

RFC PATCH 13/20 libxc/migration: add try_read_record()

In reply to Joshua Otto

Enable non-blocking migration record reads by adding a helper routine that manages the context of a record read across multiple invocations as the record's data becomes available over time.

---
 tools/libxc/xc_private.c   | 21 +++++++++++----
 tools/libxc/xc_private.h   |  2 ++
 tools/libxc/xc_sr_common.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++
 tools/libxc/xc_sr_common.h | 39 +++++++++++++++++++++++++++
 4 files changed, 124 insertions(+), 5 deletions(-)
tools/libxc/xc_private.c +16 -5
index 72e6242..2c53b22 100644
@@ -633,26 +633,37 @@ void bitmap_byte_to_64(uint64_t *lp, const uint8_t *bp, int nbits)
     }
 }
 
-int read_exact(int fd, void *data, size_t size)
+int try_read_exact(int fd, void *data, size_t size, size_t *offset)
 {
-    size_t offset = 0;
     ssize_t len;
 
-    while ( offset < size )
+    assert(offset);
+    *offset = 0;
+    while ( *offset < size )
     {
-        len = read(fd, (char *)data + offset, size - offset);
+        len = read(fd, (char *)data + *offset, size - *offset);
         if ( (len == -1) && (errno == EINTR) )
             continue;
         if ( len == 0 )
             errno = 0;
         if ( len <= 0 )
             return -1;
-        offset += len;
+        *offset += len;
     }
 
     return 0;
 }
 
+int read_exact(int fd, void *data, size_t size)
+{
+    size_t offset;
+    int rc;
+
+    rc = try_read_exact(fd, data, size, &offset);
+    assert(rc == -1 || offset == size);
+    return rc;
+}
+
 int write_exact(int fd, const void *data, size_t size)
 {
     size_t offset = 0;
tools/libxc/xc_private.h +2 -0
index 1c27b0f..aaae344 100644
@@ -384,6 +384,8 @@ int xc_flush_mmu_updates(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 */
+/* Like read_exact(), but stores the length read before error to *offset. */
+int try_read_exact(int fd, void *data, size_t size, size_t *offset);
 int write_exact(int fd, const void *data, size_t size);
 int writev_exact(int fd, const struct iovec *iov, int iovcnt);
 
tools/libxc/xc_sr_common.c +67 -0

73 lines not on this page · raw message

tools/libxc/xc_sr_common.h +39 -0
index ee463d9..b52355d 100644
@@ -394,6 +394,45 @@ static inline int write_record(struct xc_sr_context *ctx, int fd,
 int read_record(struct xc_sr_context *ctx, int fd, struct xc_sr_record *rec);
 
 /*
+ * try_read_record() (prototype below) reads a record from a _non-blocking_
+ * stream over the course of one or more invocations.  Context for the record
+ * read is maintained in an xc_sr_read_record_context.
+ *
+ * The protocol is:
+ * - call read_record_init() on an uninitialized or previously-destroyed
+ *   read-record context prior to using it to read a record
+ * - call try_read_record() with this initialized context one or more times
+ *   - rc < 0 and errno == EAGAIN/EWOULDBLOCK => try again
+ *   - rc < 0 otherwise => failure
+ *   - rc == 0 => a complete record has been read, and is filled into
+ *     try_read_record()'s rec argument
+ * - after either failure or completion of a record, destroy the context with
+ *   read_record_destroy()
+ */
+struct xc_sr_read_record_context
+{
+    struct xc_sr_context *ctx;
+    size_t offset;
+    struct xc_sr_rhdr rhdr;
+    void *data;
+};
+
+static inline void read_record_init(struct xc_sr_read_record_context *rrctx,
+                                    struct xc_sr_context *ctx)
+{
+    *rrctx = (struct xc_sr_read_record_context) { .ctx = ctx };
+}
+
+int try_read_record(struct xc_sr_read_record_context *rrctx, int fd,
+                    struct xc_sr_record *rec);
+
+static inline void read_record_destroy(struct xc_sr_read_record_context *rrctx)
+{
+    free(rrctx->data);
+    rrctx->data = NULL;
+}
+
+/*
  * Given a record of one of the page data types, validate it by:
  * - checking its actual type against its specific expected type
  * - sanity checking its actual length against its claimed length
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#39 lore raw

Re: [PATCH RFC 13/20] libxc/migration: add try_read_record()

On Mon, Mar 27, 2017 at 05:06:25AM -0400, Joshua Otto wrote:
[...]

Quoted 9 lines
tools/libxc/xc_sr_common.c +8 -0
+int try_read_record(struct xc_sr_read_record_context *rrctx, int fd,
+                    struct xc_sr_record *rec)
+{
+    int rc;
+    xc_interface *xch = rrctx->ctx->xch;
+    size_t offset_out, dataoff, datasz;
+
+    /* If the header isn't yet complete, attempt to finish it first. */

tools/libxc/xc_sr_common.c int read_record(struct xc_sr_context *ctx, int fd, struct xc_sr_record *rec) · line 167

Quoted 10 lines
tools/libxc/xc_sr_common.c +10 -0
+    if ( rrctx->offset < sizeof(rrctx->rhdr) )
+    {
+        rc = try_read_exact(fd, (char *)&rrctx->rhdr + rrctx->offset,
+                            sizeof(rrctx->rhdr) - rrctx->offset, &offset_out);
+        rrctx->offset += offset_out;
+
+        if ( rc )
+            return rc;
+        else
+            assert(rrctx->offset == sizeof(rrctx->rhdr));

No need to have the "else" branch.

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

#40 lore raw

RFC PATCH 14/20 libxc/migration: implement the sender side of postcopy live migration

In reply to Joshua Otto

Add a new 'postcopy' phase to the live migration algorithm, during which unmigrated domain memory is paged over the network on-demand _after_ the guest has been resumed at the destination.

To do so:
- Add a new precopy policy option, XGS_POLICY_POSTCOPY, that policies can use to request a transition to the postcopy live migration phase rather than a stop-and-copy of the remaining dirty pages.
- Add support to xc_domain_save() for this policy option by breaking out of the precopy loop early, transmitting the final set of dirty pfns and all remaining domain state (including higher-layer state) except memory, and entering a postcopy loop during which the remaining page data is pushed in the background. Remote requests for specific pages in response to faults in the domain are serviced with priority in this loop.

The new save callbacks required for this migration phase are stubbed in libxl for now, to be replaced in a subsequent patch that adds libxl support for this migration phase. Support for this phase on the migration receiver side follows immediately in the next patch.

---
 tools/libxc/include/xenguest.h     |  82 +++++---
 tools/libxc/xc_sr_common.h         |   5 +-
 tools/libxc/xc_sr_save.c           | 421 ++++++++++++++++++++++++++++++++++---
 tools/libxc/xc_sr_save_x86_hvm.c   |  13 ++
 tools/libxc/xg_save_restore.h      |  16 +-
 tools/libxl/libxl_dom_save.c       |  11 +-
 tools/libxl/libxl_save_msgs_gen.pl |   6 +-
 7 files changed, 487 insertions(+), 67 deletions(-)
tools/libxc/include/xenguest.h +49 -33
index 30ffb6f..16441c9 100644
@@ -63,41 +63,57 @@ struct save_callbacks {
 #define XGS_POLICY_CONTINUE_PRECOPY 0  /* Remain in the precopy phase. */
 #define XGS_POLICY_STOP_AND_COPY    1  /* Immediately suspend and transmit the
                                         * remaining dirty pages. */
+#define XGS_POLICY_POSTCOPY         2  /* Suspend the guest and transition into
+                                        * the postcopy phase of the migration. */
     int (*precopy_policy)(struct precopy_stats stats, void *data);
 
-    /* Called after the guest's dirty pages have been
-     *  copied into an output buffer.
-     * Callback function resumes the guest & the device model,
-     *  returns to xc_domain_save.
-     * xc_domain_save then flushes the output buffer, while the
-     *  guest continues to run.
-     */
-    int (*aftercopy)(void* data);
-
-    /* Called after the memory checkpoint has been flushed
-     * out into the network. Typical actions performed in this
-     * callback include:
-     *   (a) send the saved device model state (for HVM guests),
-     *   (b) wait for checkpoint ack
-     *   (c) release the network output buffer pertaining to the acked checkpoint.
-     *   (c) sleep for the checkpoint interval.
-     *
-     * returns:
-     * 0: terminate checkpointing gracefully
-     * 1: take another checkpoint */
-    int (*checkpoint)(void* data);
-
-    /*
-     * Called after the checkpoint callback.
-     *
-     * returns:
-     * 0: terminate checkpointing gracefully
-     * 1: take another checkpoint
-     */
-    int (*wait_checkpoint)(void* data);
-
-    /* Enable qemu-dm logging dirty pages to xen */
-    int (*switch_qemu_logdirty)(int domid, unsigned enable, void *data); /* HVM only */
+    /* Checkpointing and postcopy live migration are mutually exclusive. */
+    union {
+        struct {
+            /* Called during a live migration's transition to the postcopy phase
+             * to yield control of the stream back to a higher layer so it can
+             * transmit records needed for resumption of the guest at the
+             * destination (e.g. device model state, xenstore context) */
+            int (*postcopy_transition)(void *data);
+        };
+
+        struct {
+            /* Called after the guest's dirty pages have been
+             *  copied into an output buffer.
+             * Callback function resumes the guest & the device model,
+             *  returns to xc_domain_save.
+             * xc_domain_save then flushes the output buffer, while the
+             *  guest continues to run.
+             */
+            int (*aftercopy)(void* data);
+
+            /* Called after the memory checkpoint has been flushed
+             * out into the network. Typical actions performed in this
+             * callback include:
+             *   (a) send the saved device model state (for HVM guests),
+             *   (b) wait for checkpoint ack
+             *   (c) release the network output buffer pertaining to the acked
+             *       checkpoint.
+             *   (c) sleep for the checkpoint interval.
+             *
+             * returns:
+             * 0: terminate checkpointing gracefully
+             * 1: take another checkpoint */
+            int (*checkpoint)(void* data);
+
+            /*
+             * Called after the checkpoint callback.
+             *
+             * returns:
+             * 0: terminate checkpointing gracefully
+             * 1: take another checkpoint
+             */
+            int (*wait_checkpoint)(void* data);
+
+            /* Enable qemu-dm logging dirty pages to xen */
+            int (*switch_qemu_logdirty)(int domid, unsigned enable, void *data); /* HVM only */
+        };
+    };
 
     /* to be provided as the last argument to each callback function */
     void* data;
tools/libxc/xc_sr_common.h +4 -1
index b52355d..0043791 100644
@@ -204,13 +204,16 @@ struct xc_sr_context
             int policy_decision;
 
             enum {
-                XC_SR_SAVE_BATCH_PRECOPY_PAGE
+                XC_SR_SAVE_BATCH_PRECOPY_PAGE,
+                XC_SR_SAVE_BATCH_POSTCOPY_PFN,
+                XC_SR_SAVE_BATCH_POSTCOPY_PAGE
             } batch_type;
             xen_pfn_t *batch_pfns;
             unsigned nr_batch_pfns;
             unsigned long *deferred_pages;
             unsigned long nr_deferred_pages;
             xc_hypercall_buffer_t dirty_bitmap_hbuf;
+            unsigned long nr_final_dirty_pages;
         } save;
 
         struct /* Restore data. */
tools/libxc/xc_sr_save.c +392 -29

520 lines not on this page · raw message

tools/libxc/xc_sr_save_x86_hvm.c +13 -0
index ea4b780..13df25b 100644
@@ -92,6 +92,9 @@ static int write_hvm_params(struct xc_sr_context *ctx)
     unsigned int i;
     int rc;
 
+    DECLARE_HYPERCALL_BUFFER_SHADOW(unsigned long, dirty_bitmap,
+                                    &ctx->save.dirty_bitmap_hbuf);
+
     for ( i = 0; i < ARRAY_SIZE(params); i++ )
     {
         uint32_t index = params[i];
@@ -106,6 +109,16 @@ static int write_hvm_params(struct xc_sr_context *ctx)
 
         if ( value != 0 )
         {
+            if ( ctx->save.live &&
+                 ctx->save.policy_decision == XGS_POLICY_POSTCOPY &&
+                 ( index == HVM_PARAM_CONSOLE_PFN ||
+                   index == HVM_PARAM_STORE_PFN ||
+                   index == HVM_PARAM_IOREQ_PFN ||
+                   index == HVM_PARAM_BUFIOREQ_PFN ||
+                   index == HVM_PARAM_PAGING_RING_PFN ) &&
+                 test_and_clear_bit(value, dirty_bitmap) )
+                --ctx->save.nr_final_dirty_pages;
+
             entries[hdr.count].index = index;
             entries[hdr.count].value = value;
             hdr.count++;
tools/libxc/xg_save_restore.h +15 -1
index 40debf6..9f5b223 100644
@@ -24,7 +24,21 @@
 ** We process save/restore/migrate in batches of pages; the below
 ** determines how many pages we (at maximum) deal with in each batch.
 */
-#define MAX_PRECOPY_BATCH_SIZE 1024   /* up to 1024 pages (4MB) at a time */
+#define MAX_PRECOPY_BATCH_SIZE ((size_t)1024U)   /* up to 1024 pages (4MB) */
+
+/*
+** We process the migration postcopy transition in batches of pfns to ensure
+** that we stay within the record size bound.  Because these records contain
+** only pfns (and _not_ their contents), we can accomodate many more of them
+** in a batch.
+*/
+#define MAX_PFN_BATCH_SIZE ((4U << 20) / sizeof(uint64_t)) /* up to 512k pfns */
+
+/*
+** The postcopy background copy uses a smaller batch size to ensure it can
+** quickly respond to remote faults.
+*/
+#define MAX_POSTCOPY_BATCH_SIZE ((size_t)64U)
 
 /* When pinning page tables at the end of restore, we also use batching. */
 #define MAX_PIN_BATCH  1024
tools/libxl/libxl_dom_save.c +10 -1
index 10d5012..4ef9ca5 100644
@@ -349,6 +349,12 @@ static int libxl__save_live_migration_simple_precopy_policy(
     return XGS_POLICY_CONTINUE_PRECOPY;
 }
 
+static void libxl__save_live_migration_postcopy_transition_callback(void *user)
+{
+    /* XXX we're not yet ready to deal with this */
+    assert(0);
+}
+
 /*----- main code for saving, in order of execution -----*/
 
 void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)
@@ -419,8 +425,11 @@ void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)
             dss->xcflags |= XCFLAGS_CHECKPOINT_COMPRESS;
     }
 
-    if (dss->checkpointed_stream == LIBXL_CHECKPOINTED_STREAM_NONE)
+    if (dss->checkpointed_stream == LIBXL_CHECKPOINTED_STREAM_NONE) {
         callbacks->suspend = libxl__domain_suspend_callback;
+        callbacks->postcopy_transition =
+            libxl__save_live_migration_postcopy_transition_callback;
+    }
 
     callbacks->precopy_policy = libxl__save_live_migration_simple_precopy_policy;
     callbacks->switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
tools/libxl/libxl_save_msgs_gen.pl +4 -2
index 50c97b4..5647b97 100755
@@ -33,7 +33,8 @@ our @msgs = (
                                               'xen_pfn_t', 'console_gfn'] ],
     [  9, 'srW',    "complete",              [qw(int retval
                                                  int errnoval)] ],
-    [ 10, 'scxW',   "precopy_policy", ['struct precopy_stats', 'stats'] ]
+    [ 10, 'scxW',   "precopy_policy", ['struct precopy_stats', 'stats'] ],
+    [ 11, 'scxA',   "postcopy_transition", [] ]
 );
 
 #----------------------------------------
@@ -225,6 +226,7 @@ foreach my $sr (qw(save restore)) {
 
     f_decl("${setcallbacks}_${sr}", 'helper', 'void',
            "(struct ${sr}_callbacks *cbs, unsigned cbflags)");
+    f_more("${setcallbacks}_${sr}", "    memset(cbs, 0, sizeof(*cbs));\n");
 
     f_more("${receiveds}_${sr}",
            <<END_ALWAYS.($debug ? <<END_DEBUG : '').<<END_ALWAYS);
@@ -335,7 +337,7 @@ END_ALWAYS
         my $c_v = "(1u<<$msgnum)";
         my $c_cb = "cbs->$name";
         $f_more_sr->("    if ($c_cb) cbflags |= $c_v;\n", $enumcallbacks);
-        $f_more_sr->("    $c_cb = (cbflags & $c_v) ? ${encode}_${name} : 0;\n",
+        $f_more_sr->("    if (cbflags & $c_v) $c_cb = ${encode}_${name};\n",
                      $setcallbacks);
     }
     $f_more_sr->("        return 1;\n    }\n\n");
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#41 lore raw

RFC PATCH 15/20 libxc/migration: implement the receiver side of postcopy live migration

In reply to Joshua Otto

Add the receive-side logic for a new 'postcopy' phase in the live migration algorithm.

To support this migration phase:
- Augment the main restore record-processing logic to recognize and handle the postcopy-initiation records.
- Add the core logic for the phase, postcopy_restore(), which marks as paged-out all pfns reported by the sender as outstanding at the beginning of the phase, and subsequently serves as a pager for this subset of memory by forwarding paging requests to the migration sender and filling the outstanding domain memory as it is received.

The new restore callbacks required for this migration phase are stubbed in libxl for now, to be replaced in a subsequent patch that adds libxl support for this migration phase.

---
 tools/libxc/include/xenguest.h      |  63 ++-
 tools/libxc/xc_sr_common.h          |  82 +++-
 tools/libxc/xc_sr_restore.c         | 890 +++++++++++++++++++++++++++++++++++-
 tools/libxc/xc_sr_restore_x86_hvm.c |  38 +-
 tools/libxl/libxl_create.c          |  15 +
 tools/libxl/libxl_save_msgs_gen.pl  |   2 +-
 6 files changed, 1049 insertions(+), 41 deletions(-)
tools/libxc/include/xenguest.h +39 -24
index 16441c9..684afc8 100644
@@ -146,35 +146,50 @@ struct restore_callbacks {
      */
     int (*suspend)(void* data);
 
-    /* Called after the secondary vm is ready to resume.
-     * Callback function resumes the guest & the device model,
-     * returns to xc_domain_restore.
-     */
-    int (*aftercopy)(void* data);
+    union {
+        struct {
+            /* Called upon receipt of the POSTCOPY_TRANSITION record in the
+             * stream to yield control of the stream to the higher layer so that
+             * the remaining data needed to resume the domain in the postcopy
+             * phase can be obtained.  Returns as soon as the higher layer is
+             * finished with the stream.
+             *
+             * Returns 1 on success, 0 on failure. */
+            int (*postcopy_transition)(void *data);
+        };
+
+        struct {
+            /* Called after the secondary vm is ready to resume.
+             * Callback function resumes the guest & the device model,
+             * returns to xc_domain_restore.
+             */
+            int (*aftercopy)(void* data);
 
-    /* A checkpoint record has been found in the stream.
-     * returns: */
+            /* A checkpoint record has been found in the stream.
+             * returns: */
 #define XGR_CHECKPOINT_ERROR    0 /* Terminate processing */
 #define XGR_CHECKPOINT_SUCCESS  1 /* Continue reading more data from the stream */
 #define XGR_CHECKPOINT_FAILOVER 2 /* Failover and resume VM */
-    int (*checkpoint)(void* data);
-
-    /*
-     * Called after the checkpoint callback.
-     *
-     * returns:
-     * 0: terminate checkpointing gracefully
-     * 1: take another checkpoint
-     */
-    int (*wait_checkpoint)(void* data);
+            int (*checkpoint)(void* data);
 
-    /*
-     * callback to send store gfn and console gfn to xl
-     * if we want to resume vm before xc_domain_save()
-     * exits.
-     */
-    void (*restore_results)(xen_pfn_t store_gfn, xen_pfn_t console_gfn,
-                            void *data);
+            /*
+             * Called after the checkpoint callback.
+             *
+             * returns:
+             * 0: terminate checkpointing gracefully
+             * 1: take another checkpoint
+             */
+            int (*wait_checkpoint)(void* data);
+
+            /*
+             * callback to send store gfn and console gfn to xl
+             * if we want to resume vm before xc_domain_save()
+             * exits.
+             */
+            void (*restore_results)(xen_pfn_t store_gfn, xen_pfn_t console_gfn,
+                                    void *data);
+        };
+    };
 
     /* to be provided as the last argument to each callback function */
     void* data;
tools/libxc/xc_sr_common.h +81 -1

100 lines not on this page · raw message

tools/libxc/xc_sr_restore.c +878 -12

951 lines not on this page · raw message

tools/libxc/xc_sr_restore_x86_hvm.c +35 -3
index 49d22c7..7be3218 100644
@@ -27,6 +27,27 @@ static int handle_hvm_context(struct xc_sr_context *ctx,
     return 0;
 }
 
+static int handle_hvm_magic_page(struct xc_sr_context *ctx,
+                                 struct xc_sr_rec_hvm_params_entry *entry)
+{
+    int rc;
+    xen_pfn_t pfn = entry->value;
+
+    if ( ctx->restore.postcopy )
+    {
+        rc = populate_pfns(ctx, 1, &pfn, NULL);
+        if ( rc )
+            return rc;
+    }
+
+    if ( entry->index != HVM_PARAM_PAGING_RING_PFN )
+    {
+        xc_clear_domain_page(ctx->xch, ctx->domid, pfn);
+    }
+
+    return 0;
+}
+
 /*
  * Process an HVM_PARAMS record from the stream.
  */
@@ -52,18 +73,29 @@ static int handle_hvm_params(struct xc_sr_context *ctx,
         {
         case HVM_PARAM_CONSOLE_PFN:
             ctx->restore.console_gfn = entry->value;
-            xc_clear_domain_page(xch, ctx->domid, entry->value);
+            rc = handle_hvm_magic_page(ctx, entry);
             break;
         case HVM_PARAM_STORE_PFN:
             ctx->restore.xenstore_gfn = entry->value;
-            xc_clear_domain_page(xch, ctx->domid, entry->value);
+            rc = handle_hvm_magic_page(ctx, entry);
+            break;
+        case HVM_PARAM_PAGING_RING_PFN:
+            ctx->restore.paging_ring_gfn = entry->value;
+            rc = handle_hvm_magic_page(ctx, entry);
             break;
         case HVM_PARAM_IOREQ_PFN:
         case HVM_PARAM_BUFIOREQ_PFN:
-            xc_clear_domain_page(xch, ctx->domid, entry->value);
+            rc = handle_hvm_magic_page(ctx, entry);
             break;
         }
 
+        if ( rc )
+        {
+            PERROR("populate/clear magic HVM page %"PRId64" = 0x%016"PRIx64,
+                   entry->index, entry->value);
+            return rc;
+        }
+
         rc = xc_hvm_param_set(xch, ctx->domid, entry->index, entry->value);
         if ( rc < 0 )
         {
tools/libxl/libxl_create.c +15 -0
index b65c971..8f4af0a 100644
@@ -745,6 +745,8 @@ static void domcreate_bootloader_done(libxl__egc *egc,
                                       libxl__bootloader_state *bl,
                                       int rc);
 
+static void domcreate_postcopy_transition_callback(void *user);
+
 static void domcreate_launch_dm(libxl__egc *egc, libxl__multidev *aodevs,
                                 int ret);
 
@@ -1097,6 +1099,11 @@ static void domcreate_bootloader_done(libxl__egc *egc,
             libxl__remus_restore_setup(egc, dcs);
             /* fall through */
         case LIBXL_CHECKPOINTED_STREAM_NONE:
+            /* When the restore helper initiates the postcopy transition, pick
+             * up in domcreate_postcopy_transition_callback() */
+            callbacks->postcopy_transition =
+                domcreate_postcopy_transition_callback;
+
             libxl__stream_read_start(egc, &dcs->srs);
         }
         return;
@@ -1106,6 +1113,14 @@ static void domcreate_bootloader_done(libxl__egc *egc,
     domcreate_stream_done(egc, &dcs->srs, rc);
 }
 
+/* ----- postcopy live migration ----- */
+
+static void domcreate_postcopy_transition_callback(void *user)
+{
+    /* XXX we're not ready to deal with this yet */
+    assert(0);
+}
+
 void libxl__srm_callout_callback_restore_results(xen_pfn_t store_mfn,
           xen_pfn_t console_mfn, void *user)
 {
tools/libxl/libxl_save_msgs_gen.pl +1 -1
index 5647b97..7f59e03 100755
@@ -34,7 +34,7 @@ our @msgs = (
     [  9, 'srW',    "complete",              [qw(int retval
                                                  int errnoval)] ],
     [ 10, 'scxW',   "precopy_policy", ['struct precopy_stats', 'stats'] ],
-    [ 11, 'scxA',   "postcopy_transition", [] ]
+    [ 11, 'srcxA',  "postcopy_transition", [] ]
 );
 
 #----------------------------------------
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#42 lore raw

RFC PATCH 16/20 libxl/libxl_stream_write.c: track callback chains with an explicit phase

In reply to Joshua Otto

There are three callback chains through libxl_stream_write: the 'normal' straight-through save path initiated by libxl__stream_write_start(), the iterated checkpoint path initiated each time by libxl__stream_write_start_checkpoint(), and the (short) back-channel checkpoint path initiated by libxl__stream_write_checkpoint_state(). These paths share significant common code but handle failure and completion slightly differently, so it is necessary to keep track of the callback chain currently in progress and act accordingly at various points.

Until now, a collection of booleans in the stream write state has been used to indicate the current callback chain. However, the set of callback chains is really better described by an enum, since only one callback chain can actually be active at one time. In anticipation of the addition of a new chain for postcopy live migration, refactor the existing logic to use an enum rather than booleans for callback chain tracking.

No functional change.

---
 tools/libxl/libxl_internal.h     |  7 ++-
 tools/libxl/libxl_stream_write.c | 96 ++++++++++++++++++----------------------
 2 files changed, 48 insertions(+), 55 deletions(-)
tools/libxl/libxl_internal.h +5 -2
index 45d607a..e99d2ef 100644
@@ -3201,9 +3201,12 @@ struct libxl__stream_write_state {
     /* Private */
     int rc;
     bool running;
-    bool in_checkpoint;
+    enum {
+        SWS_PHASE_NORMAL,
+        SWS_PHASE_CHECKPOINT,
+        SWS_PHASE_CHECKPOINT_STATE
+    } phase;
     bool sync_teardown;  /* Only used to coordinate shutdown on error path. */
-    bool in_checkpoint_state;
     libxl__save_helper_state shs;
 
     /* Main stream-writing data. */
tools/libxl/libxl_stream_write.c +43 -53

181 lines not on this page · raw message

Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#43 lore raw

RFC PATCH 17/20 libxl/libxl_stream_read.c: track callback chains with an explicit phase

In reply to Joshua Otto

As the previous patch did for libxl_stream_write, do for libxl_stream_read. libxl_stream_read already has a notion of phase for its record-buffering behaviour - this is combined with the callback chain phase. Again, this is done to support the addition of a new callback chain for postcopy live migration.

No functional change.

---
 tools/libxl/libxl_internal.h    |  7 ++--
 tools/libxl/libxl_stream_read.c | 83 +++++++++++++++++++++--------------------
 2 files changed, 45 insertions(+), 45 deletions(-)
tools/libxl/libxl_internal.h +3 -4
index e99d2ef..c754706 100644
@@ -3123,9 +3123,7 @@ struct libxl__stream_read_state {
     /* Private */
     int rc;
     bool running;
-    bool in_checkpoint;
     bool sync_teardown; /* Only used to coordinate shutdown on error path. */
-    bool in_checkpoint_state;
     libxl__save_helper_state shs;
     libxl__conversion_helper_state chs;
 
@@ -3135,8 +3133,9 @@ struct libxl__stream_read_state {
     LIBXL_STAILQ_HEAD(, libxl__sr_record_buf) record_queue; /* NOGC */
     enum {
         SRS_PHASE_NORMAL,
-        SRS_PHASE_BUFFERING,
-        SRS_PHASE_UNBUFFERING,
+        SRS_PHASE_CHECKPOINT_BUFFERING,
+        SRS_PHASE_CHECKPOINT_UNBUFFERING,
+        SRS_PHASE_CHECKPOINT_STATE
     } phase;
     bool recursion_guard;
 
tools/libxl/libxl_stream_read.c +42 -41

217 lines not on this page · raw message

Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#44 lore raw

RFC PATCH 18/20 libxl/migration: implement the sender side of postcopy live migration

In reply to Joshua Otto

To make the libxl sender capable of supporting postcopy live migration:
- Add a postcopy transition callback chain through the stream writer (this callback chain is nearly identical to the checkpoint callback chain, and differs meaningfully only in its failure/completion behaviour)
- Wire this callback chain up to the xc postcopy callback entries in the domain save logic.
- Add parameters to libxl_domain_live_migrate() to permit bidirectional communication between the sender and receiver and enable the caller to reason about the safety of recovery from a postcopy failure.

No mechanism is introduced yet to enable library clients to induce a postcopy live migration - this will follow after the libxl postcopy receiver logic.

---
 docs/specs/libxl-migration-stream.pandoc | 19 ++++++++-
 tools/libxl/libxl.h                      |  4 +-
 tools/libxl/libxl_dom_save.c             | 25 +++++++++++-
 tools/libxl/libxl_domain.c               | 25 ++++++++----
 tools/libxl/libxl_internal.h             | 21 ++++++++--
 tools/libxl/libxl_sr_stream_format.h     | 13 +++---
 tools/libxl/libxl_stream_write.c         | 69 ++++++++++++++++++++++++++++++--
 tools/xl/xl_migrate.c                    |  5 ++-
 8 files changed, 155 insertions(+), 26 deletions(-)
docs/specs/libxl-migration-stream.pandoc +17 -2
index a1ba1ac..8d00cd7 100644
@@ -2,7 +2,8 @@
 % Andrew Cooper <<[email protected]>>
   Wen Congyang <<[email protected]>>
   Yang Hongyang <<[email protected]>>
-% Revision 2
+  Joshua Otto <<[email protected]>>
+% Revision 3
 
 Introduction
 ============
@@ -123,7 +124,9 @@ type         0x00000000: END
 
              0x00000005: CHECKPOINT_STATE
 
-             0x00000006 - 0x7FFFFFFF: Reserved for future _mandatory_
+             0x00000006: POSTCOPY_TRANSITION_END
+
+             0x00000007 - 0x7FFFFFFF: Reserved for future _mandatory_
              records.
 
              0x80000000 - 0xFFFFFFFF: Reserved for future _optional_
@@ -304,6 +307,18 @@ While Secondary is running in below loop:
     b. Send _CHECKPOINT\_SVM\_SUSPENDED_ to primary
 4. Checkpoint
 
+POSTCOPY\_TRANSITION\_END
+-------------------------
+
+A postcopy transition end record marks the end of a postcopy transition in a
+libxl live migration stream.  It indicates that control of the stream should be
+returned to libxc for the postcopy memory migration phase.
+
+     0     1     2     3     4     5     6     7 octet
+    +-------------------------------------------------+
+
+The postcopy transition end record contains no fields; its body_length is 0.
+
 Future Extensions
 =================
 
tools/libxl/libxl.h +3 -1
index 84ac96a..99d187b 100644
@@ -1375,10 +1375,12 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd,
 #define LIBXL_SUSPEND_DEBUG 1
 #define LIBXL_SUSPEND_LIVE 2
 
-int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int fd,
+int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int send_fd,
                               int flags, /* LIBXL_SUSPEND_* */
                               unsigned int precopy_iterations,
                               unsigned int precopy_dirty_threshold,
+                              int recv_fd,
+                              bool *postcopy_transitioned, /* OUT */
                               const libxl_asyncop_how *ao_how)
                               LIBXL_EXTERNAL_CALLERS_ONLY;
 
tools/libxl/libxl_dom_save.c +23 -2
index 4ef9ca5..9e565ae 100644
@@ -349,10 +349,31 @@ static int libxl__save_live_migration_simple_precopy_policy(
     return XGS_POLICY_CONTINUE_PRECOPY;
 }
 
+static void postcopy_transition_done(libxl__egc *egc,
+                                     libxl__stream_write_state *sws, int rc);
+
 static void libxl__save_live_migration_postcopy_transition_callback(void *user)
 {
-    /* XXX we're not yet ready to deal with this */
-    assert(0);
+    libxl__save_helper_state *shs = user;
+    libxl__stream_write_state *sws = CONTAINER_OF(shs, *sws, shs);
+    sws->postcopy_transition_callback = postcopy_transition_done;
+    libxl__stream_write_start_postcopy_transition(shs->egc, sws);
+}
+
+static void postcopy_transition_done(libxl__egc *egc,
+                                     libxl__stream_write_state *sws,
+                                     int rc)
+{
+    libxl__domain_save_state *dss = sws->dss;
+
+    /* Past here, it's _possible_ that the domain may execute at the
+     * destination, so - unless we're given positive confirmation by the
+     * destination that it failed to resume there - we must assume it has. */
+    assert(dss->postcopy_transitioned);
+    *dss->postcopy_transitioned = !rc;
+
+    /* Return control to libxc. */
+    libxl__xc_domain_saverestore_async_callback_done(egc, &sws->shs, !rc);
 }
 
 /*----- main code for saving, in order of execution -----*/
tools/libxl/libxl_domain.c +18 -7
index b1cf643..ea778a6 100644
@@ -488,7 +488,8 @@ static void domain_suspend_cb(libxl__egc *egc,
 
 static int do_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
                              unsigned int precopy_iterations,
-                             unsigned int precopy_dirty_threshold,
+                             unsigned int precopy_dirty_threshold, int recv_fd,
+                             bool *postcopy_transitioned,
                              const libxl_asyncop_how *ao_how)
 {
     AO_CREATE(ctx, domid, ao_how);
@@ -508,6 +509,8 @@ static int do_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
 
     dss->domid = domid;
     dss->fd = fd;
+    dss->recv_fd = recv_fd;
+    dss->postcopy_transitioned = postcopy_resumed_remotely;
     dss->type = type;
     dss->live = flags & LIBXL_SUSPEND_LIVE;
     dss->debug = flags & LIBXL_SUSPEND_DEBUG;
@@ -532,18 +535,26 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
 {
     return do_domain_suspend(ctx, domid, fd, flags,
                              LIBXL_LM_PRECOPY_ITERATIONS_DEFAULT,
-                             LIBXL_LM_DIRTY_THRESHOLD_DEFAULT, ao_how);
+                             LIBXL_LM_DIRTY_THRESHOLD_DEFAULT, -1,
+                             NULL, ao_how);
 }
 
-int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
-                              unsigned int precopy_iterations,
-                              unsigned int precopy_dirty_threshold,
+int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int send_fd,
+                              int flags, unsigned int precopy_iterations,
+                              unsigned int precopy_dirty_threshold, int recv_fd,
+                              bool *postcopy_transitioned,
                               const libxl_asyncop_how *ao_how)
 {
+    if (!postcopy_transitioned) {
+        errno = EINVAL;
+        return -1;
+    }
+
     flags |= LIBXL_SUSPEND_LIVE;
 
-    return do_domain_suspend(ctx, domid, fd, flags, precopy_iterations,
-                             precopy_dirty_threshold, ao_how);
+    return do_domain_suspend(ctx, domid, send_fd, flags, precopy_iterations,
+                             precopy_dirty_threshold, recv_fd,
+                             postcopy_transitioned, ao_how);
 }
 
 int libxl_domain_pause(libxl_ctx *ctx, uint32_t domid)
tools/libxl/libxl_internal.h +17 -4
index c754706..ae272d7 100644
@@ -3194,17 +3194,25 @@ struct libxl__stream_write_state {
     void (*completion_callback)(libxl__egc *egc,
                                 libxl__stream_write_state *sws,
                                 int rc);
-    void (*checkpoint_callback)(libxl__egc *egc,
-                                libxl__stream_write_state *sws,
-                                int rc);
+    /* Checkpointing and postcopy live migration are mutually exclusive. */
+    union {
+        void (*checkpoint_callback)(libxl__egc *egc,
+                                    libxl__stream_write_state *sws,
+                                    int rc);
+        void (*postcopy_transition_callback)(libxl__egc *egc,
+                                             libxl__stream_write_state *sws,
+                                             int rc);
+    };
     /* Private */
     int rc;
     bool running;
     enum {
         SWS_PHASE_NORMAL,
         SWS_PHASE_CHECKPOINT,
-        SWS_PHASE_CHECKPOINT_STATE
+        SWS_PHASE_CHECKPOINT_STATE,
+        SWS_PHASE_POSTCOPY_TRANSITION
     } phase;
+    bool postcopy_transitioned;
     bool sync_teardown;  /* Only used to coordinate shutdown on error path. */
     libxl__save_helper_state shs;
 
@@ -3227,6 +3235,10 @@ _hidden void libxl__stream_write_init(libxl__stream_write_state *stream);
 _hidden void libxl__stream_write_start(libxl__egc *egc,
                                        libxl__stream_write_state *stream);
 _hidden void
+libxl__stream_write_start_postcopy_transition(
+    libxl__egc *egc,
+    libxl__stream_write_state *stream);
+_hidden void
 libxl__stream_write_start_checkpoint(libxl__egc *egc,
                                      libxl__stream_write_state *stream);
 _hidden void
@@ -3290,6 +3302,7 @@ struct libxl__domain_save_state {
     int fd;
     int fdfl; /* original flags on fd */
     int recv_fd;
+    bool *postcopy_transitioned;
     libxl_domain_type type;
     int live;
     int debug;
tools/libxl/libxl_sr_stream_format.h +7 -6
index 75f5190..a789126 100644
@@ -31,12 +31,13 @@ typedef struct libxl__sr_rec_hdr
 /* All records must be aligned up to an 8 octet boundary */
 #define REC_ALIGN_ORDER              3U
 
-#define REC_TYPE_END                    0x00000000U
-#define REC_TYPE_LIBXC_CONTEXT          0x00000001U
-#define REC_TYPE_EMULATOR_XENSTORE_DATA 0x00000002U
-#define REC_TYPE_EMULATOR_CONTEXT       0x00000003U
-#define REC_TYPE_CHECKPOINT_END         0x00000004U
-#define REC_TYPE_CHECKPOINT_STATE       0x00000005U
+#define REC_TYPE_END                     0x00000000U
+#define REC_TYPE_LIBXC_CONTEXT           0x00000001U
+#define REC_TYPE_EMULATOR_XENSTORE_DATA  0x00000002U
+#define REC_TYPE_EMULATOR_CONTEXT        0x00000003U
+#define REC_TYPE_CHECKPOINT_END          0x00000004U
+#define REC_TYPE_CHECKPOINT_STATE        0x00000005U
+#define REC_TYPE_POSTCOPY_TRANSITION_END 0x00000006U
 
 typedef struct libxl__sr_emulator_hdr
 {
tools/libxl/libxl_stream_write.c +66 -3

136 lines not on this page · raw message

tools/xl/xl_migrate.c +4 -1
index 1bb3fb4..1ffc32b 100644
@@ -188,6 +188,7 @@ static void migrate_domain(uint32_t domid, const char *rune, int debug,
     char rc_buf;
     uint8_t *config_data;
     int config_len, flags = LIBXL_SUSPEND_LIVE;
+    bool postcopy_transitioned;
 
     save_domain_core_begin(domid, override_config_file,
                            &config_data, &config_len);
@@ -209,7 +210,9 @@ static void migrate_domain(uint32_t domid, const char *rune, int debug,
         flags |= LIBXL_SUSPEND_DEBUG;
     rc = libxl_domain_live_migrate(ctx, domid, send_fd, flags,
                                    precopy_iterations, precopy_dirty_threshold,
-                                   NULL);
+                                   recv_fd, &postcopy_transitioned, NULL);
+    assert(!postcopy_transitioned);
+
     if (rc) {
         fprintf(stderr, "migration sender: libxl_domain_suspend failed"
                 " (rc=%d)\n", rc);
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#45 lore raw

RFC PATCH 19/20 libxl/migration: implement the receiver side of postcopy live migration

In reply to Joshua Otto

To make the libxl receiver capable of supporting postcopy live migration:
- As was done for the libxl stream writer, add a symmetric callback chain through the stream reader that reads the sequence of xl records necessary to resume the guest and enter the postcopy phase. This chain is very similar to the checkpoint chain.
- Add a new postcopy path through the domain creation sequence that permits the xc memory postcopy phase to proceed in parallel to the libxl domain creation and resumption sequence.
- Add a out-parameter to libxl_domain_create_restore(), 'postcopy_resumed', that callers can test to determine whether or not further action is required on their-part post-migration to get the guest running.

A subsequent patch will introduce a mechanism by which library clients can _induce_ a postcopy live migration.

---
 tools/libxl/libxl.h                  |  28 ++++++-
 tools/libxl/libxl_create.c           | 156 +++++++++++++++++++++++++++++++++--
 tools/libxl/libxl_internal.h         |  43 +++++++++-
 tools/libxl/libxl_stream_read.c      |  57 +++++++++++++
 tools/ocaml/libs/xl/xenlight_stubs.c |   2 +-
 tools/xl/xl_vmcontrol.c              |   2 +-
 6 files changed, 273 insertions(+), 15 deletions(-)
tools/libxl/libxl.h +25 -3
index 99d187b..51e8760 100644
@@ -1296,6 +1296,7 @@ int libxl_domain_create_new(libxl_ctx *ctx, libxl_domain_config *d_config,
 int libxl_domain_create_restore(libxl_ctx *ctx, libxl_domain_config *d_config,
                                 uint32_t *domid, int restore_fd,
                                 int send_back_fd,
+                                bool *postcopy_resumed, /* OUT */
                                 const libxl_domain_restore_params *params,
                                 const libxl_asyncop_how *ao_how,
                                 const libxl_asyncprogress_how *aop_console_how)
@@ -1315,8 +1316,9 @@ static inline int libxl_domain_create_restore_0x040200(
 
     libxl_domain_restore_params_init(&params);
 
-    ret = libxl_domain_create_restore(
-        ctx, d_config, domid, restore_fd, -1, &params, ao_how, aop_console_how);
+    ret = libxl_domain_create_restore(ctx, d_config, domid, restore_fd,
+                                      -1, NULL, &params, ao_how,
+                                      aop_console_how);
 
     libxl_domain_restore_params_dispose(&params);
     return ret;
@@ -1336,11 +1338,31 @@ static inline int libxl_domain_create_restore_0x040400(
     LIBXL_EXTERNAL_CALLERS_ONLY
 {
     return libxl_domain_create_restore(ctx, d_config, domid, restore_fd,
-                                       -1, params, ao_how, aop_console_how);
+                                       -1, NULL, params, ao_how,
+                                       aop_console_how);
 }
 
 #define libxl_domain_create_restore libxl_domain_create_restore_0x040400
 
+#elif defined(LIBXL_API_VERSION) && LIBXL_API_VERSION >= 0x040700 \
+                                 && LIBXL_API_VERSION < 0x040900
+
+static inline int libxl_domain_create_restore_0x040700(
+    libxl_ctx *ctx, libxl_domain_config *d_config,
+    uint32_t *domid, int restore_fd,
+    int send_back_fd,
+    const libxl_domain_restore_params *params,
+    const libxl_asyncop_how *ao_how,
+    const libxl_asyncprogress_how *aop_console_how)
+    LIBXL_EXTERNAL_CALLERS_ONLY
+{
+    return libxl_domain_create_restore(ctx, d_config, domid, restore_fd,
+                                       -1, NULL, params, ao_how,
+                                       aop_console_how);
+}
+
+#define libxl_domain_create_restore libxl_domain_create_restore_0x040700
+
 #endif
 
 int libxl_domain_soft_reset(libxl_ctx *ctx,
tools/libxl/libxl_create.c +149 -7

229 lines not on this page · raw message

tools/libxl/libxl_internal.h +40 -3

73 lines not on this page · raw message

tools/libxl/libxl_stream_read.c +57 -0

111 lines not on this page · raw message

tools/ocaml/libs/xl/xenlight_stubs.c +1 -1
index 98b52b9..3ef5a1e 100644
@@ -538,7 +538,7 @@ value stub_libxl_domain_create_restore(value ctx, value domain_config, value par
 
 	caml_enter_blocking_section();
 	ret = libxl_domain_create_restore(CTX, &c_dconfig, &c_domid, restore_fd,
-		-1, &c_params, ao_how, NULL);
+		-1, NULL, &c_params, ao_how, NULL);
 	caml_leave_blocking_section();
 
 	free(ao_how);
tools/xl/xl_vmcontrol.c +1 -1
index 89c2b25..47ba9f3 100644
@@ -882,7 +882,7 @@ start:
 
         ret = libxl_domain_create_restore(ctx, &d_config,
                                           &domid, restore_fd,
-                                          send_back_fd, &params,
+                                          send_back_fd, NULL, &params,
                                           0, autoconnect_console_how);
 
         libxl_domain_restore_params_dispose(&params);
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#46 lore raw

RFC PATCH 20/20 tools: expose postcopy live migration support in libxl and xl

In reply to Joshua Otto

- Add a 'memory_strategy' parameter to libxl_domain_live_migrate(), which specifies how the remainder of the memory migration should be approached after the iterative precopy phase is completed.
- Plug this parameter into the libxl migration precopy policy implementation.
- Add --postcopy to xl migrate, and skip the xl-level handshaking at both sides when postcopy migration occurs.

---
 tools/libxl/libxl.h          |  6 ++++-
 tools/libxl/libxl_dom_save.c | 19 ++++++-------
 tools/libxl/libxl_domain.c   |  9 ++++---
 tools/libxl/libxl_internal.h |  1 +
 tools/xl/xl.h                |  7 ++++-
 tools/xl/xl_cmdtable.c       |  5 +++-
 tools/xl/xl_migrate.c        | 63 +++++++++++++++++++++++++++++++++++++++-----
 tools/xl/xl_vmcontrol.c      |  8 ++++--
 8 files changed, 94 insertions(+), 24 deletions(-)
tools/libxl/libxl.h +5 -1
index 51e8760..3a2f7ea 100644
@@ -1401,7 +1401,7 @@ int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int send_fd,
                               int flags, /* LIBXL_SUSPEND_* */
                               unsigned int precopy_iterations,
                               unsigned int precopy_dirty_threshold,
-                              int recv_fd,
+                              int recv_fd, int memory_strategy,
                               bool *postcopy_transitioned, /* OUT */
                               const libxl_asyncop_how *ao_how)
                               LIBXL_EXTERNAL_CALLERS_ONLY;
@@ -1409,6 +1409,10 @@ int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int send_fd,
 #define LIBXL_LM_PRECOPY_ITERATIONS_DEFAULT 5
 #define LIBXL_LM_DIRTY_THRESHOLD_DEFAULT 50
 
+#define LIBXL_LM_MEMORY_STOP_AND_COPY 0
+#define LIBXL_LM_MEMORY_POSTCOPY 1
+#define LIBXL_LM_MEMORY_DEFAULT LIBXL_LM_MEMORY_STOP_AND_COPY
+
 /* @param suspend_cancel [from xenctrl.h:xc_domain_resume( @param fast )]
  *   If this parameter is true, use co-operative resume. The guest
  *   must support this.
tools/libxl/libxl_dom_save.c +10 -9
index 9e565ae..9d5d435 100644
@@ -333,18 +333,19 @@ int libxl__save_emulator_xenstore_data(libxl__domain_save_state *dss,
  * the precopy phase of live migrations, and is responsible for deciding when
  * the precopy phase should terminate and what should be done next.
  */
-static int libxl__save_live_migration_simple_precopy_policy(
-    struct precopy_stats stats, void *user)
+static int libxl__save_live_migration_precopy_policy(struct precopy_stats stats,
+                                                     void *user)
 {
     libxl__save_helper_state *shs = user;
     libxl__domain_save_state *dss = shs->caller_state;
 
-    if (stats.dirty_count >= 0 &&
-        stats.dirty_count <= dss->precopy_dirty_threshold)
-        return XGS_POLICY_STOP_AND_COPY;
-
-    if (stats.iteration >= dss->precopy_iterations)
-        return XGS_POLICY_STOP_AND_COPY;
+    if ((stats.dirty_count >= 0 &&
+         stats.dirty_count <= dss->precopy_dirty_threshold) ||
+        (stats.iteration >= dss->precopy_iterations)) {
+        return (dss->memory_strategy == LIBXL_LM_MEMORY_POSTCOPY)
+            ? XGS_POLICY_POSTCOPY
+            : XGS_POLICY_STOP_AND_COPY;
+    }
 
     return XGS_POLICY_CONTINUE_PRECOPY;
 }
@@ -452,7 +453,7 @@ void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)
             libxl__save_live_migration_postcopy_transition_callback;
     }
 
-    callbacks->precopy_policy = libxl__save_live_migration_simple_precopy_policy;
+    callbacks->precopy_policy = libxl__save_live_migration_precopy_policy;
     callbacks->switch_qemu_logdirty = libxl__domain_suspend_common_switch_qemu_logdirty;
 
     dss->sws.ao  = dss->ao;
tools/libxl/libxl_domain.c +6 -3
index ea778a6..feec293 100644
@@ -489,6 +489,7 @@ static void domain_suspend_cb(libxl__egc *egc,
 static int do_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
                              unsigned int precopy_iterations,
                              unsigned int precopy_dirty_threshold, int recv_fd,
+                             int memory_strategy,
                              bool *postcopy_transitioned,
                              const libxl_asyncop_how *ao_how)
 {
@@ -510,7 +511,8 @@ static int do_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
     dss->domid = domid;
     dss->fd = fd;
     dss->recv_fd = recv_fd;
-    dss->postcopy_transitioned = postcopy_resumed_remotely;
+    dss->memory_strategy = memory_strategy;
+    dss->postcopy_transitioned = postcopy_transitioned;
     dss->type = type;
     dss->live = flags & LIBXL_SUSPEND_LIVE;
     dss->debug = flags & LIBXL_SUSPEND_DEBUG;
@@ -536,12 +538,13 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags,
     return do_domain_suspend(ctx, domid, fd, flags,
                              LIBXL_LM_PRECOPY_ITERATIONS_DEFAULT,
                              LIBXL_LM_DIRTY_THRESHOLD_DEFAULT, -1,
-                             NULL, ao_how);
+                             LIBXL_LM_MEMORY_DEFAULT, NULL, ao_how);
 }
 
 int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int send_fd,
                               int flags, unsigned int precopy_iterations,
                               unsigned int precopy_dirty_threshold, int recv_fd,
+                              int memory_strategy,
                               bool *postcopy_transitioned,
                               const libxl_asyncop_how *ao_how)
 {
@@ -553,7 +556,7 @@ int libxl_domain_live_migrate(libxl_ctx *ctx, uint32_t domid, int send_fd,
     flags |= LIBXL_SUSPEND_LIVE;
 
     return do_domain_suspend(ctx, domid, send_fd, flags, precopy_iterations,
-                             precopy_dirty_threshold, recv_fd,
+                             precopy_dirty_threshold, recv_fd, memory_strategy,
                              postcopy_transitioned, ao_how);
 }
 
tools/libxl/libxl_internal.h +1 -0
index 0a7c0d1..209cee5 100644
@@ -3313,6 +3313,7 @@ struct libxl__domain_save_state {
     int fd;
     int fdfl; /* original flags on fd */
     int recv_fd;
+    int memory_strategy;
     bool *postcopy_transitioned;
     libxl_domain_type type;
     int live;
tools/xl/xl.h +6 -1
index aa95b77..279c716 100644
@@ -48,6 +48,7 @@ struct domain_create {
     bool userspace_colo_proxy;
     int migrate_fd; /* -1 means none */
     int send_back_fd; /* -1 means none */
+    bool *postcopy_resumed;
     char **migration_domname_r; /* from malloc */
 };
 
@@ -66,7 +67,6 @@ static const char migrate_permission_to_go[]=
     "domain is yours, you are cleared to unpause";
 static const char migrate_report[]=
     "my copy unpause results are as follows";
-#endif
 
   /* followed by one byte:
    *     0: everything went well, domain is running
@@ -76,6 +76,11 @@ static const char migrate_report[]=
    *            from target to source
    */
 
+static const char migrate_postcopy_sync[]=
+    "postcopy migration completed successfully";
+
+#endif
+
 #define XL_MANDATORY_FLAG_JSON (1U << 0) /* config data is in JSON format */
 #define XL_MANDATORY_FLAG_STREAMv2 (1U << 1) /* stream is v2 */
 #define XL_MANDATORY_FLAG_ALL  (XL_MANDATORY_FLAG_JSON |        \
tools/xl/xl_cmdtable.c +4 -1
index 6df66fb..7bd2d1b 100644
@@ -169,7 +169,10 @@ struct cmd_spec cmd_table[] = {
       "--precopy-iterations Perform at most this many iterations of the precopy\n"
       "                     memory migration loop before suspending the domain.\n"
       "--precopy-threshold  If fewer than this many pages are dirty at the end of a\n"
-      "                     copy round, exit the precopy loop and suspend the domain."
+      "                     copy round, exit the precopy loop and suspend the domain.\n"
+      "--postcopy           At the end of the iterative precopy phase, transition to a\n"
+      "                     postcopy memory migration rather than performing a stop-and-copy\n"
+      "                     migration of the outstanding dirty pages.\n"
     },
     { "restore",
       &main_restore, 0, 1,
tools/xl/xl_migrate.c +56 -7

130 lines not on this page · raw message

tools/xl/xl_vmcontrol.c +6 -2
index 47ba9f3..62e09c1 100644
@@ -655,6 +655,7 @@ int create_domain(struct domain_create *dom_info)
     const char *config_source = NULL;
     const char *restore_source = NULL;
     int migrate_fd = dom_info->migrate_fd;
+    bool *postcopy_resumed = dom_info->postcopy_resumed;
     bool config_in_json;
 
     int i;
@@ -675,6 +676,9 @@ int create_domain(struct domain_create *dom_info)
 
     int restoring = (restore_file || (migrate_fd >= 0));
 
+    if (postcopy_resumed)
+        *postcopy_resumed = false;
+
     libxl_domain_config_init(&d_config);
 
     if (restoring) {
@@ -882,8 +886,8 @@ start:
 
         ret = libxl_domain_create_restore(ctx, &d_config,
                                           &domid, restore_fd,
-                                          send_back_fd, NULL, &params,
-                                          0, autoconnect_console_how);
+                                          send_back_fd, postcopy_resumed,
+                                          &params, 0, autoconnect_console_how);
 
         libxl_domain_restore_params_dispose(&params);
 
Signature · 7 lines
2.7.4


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xen.org/xen-devel
#47 lore raw
In reply to Joshua Otto

Hi Harley, Chester and Joshua

This is really nice work. I took a brief look at all the patches, they look really high quality.

We're currently approaching freeze for a Xen release. We've got a lot on our plate. I think maintainers will get to this series at some point.

From the look of things some patches can go in because they're general useful.

Quoted 30 lines · Joshua Otto

Hi,

We're a team of three fourth-year undergraduate software engineering students at the University of Waterloo in Canada. In late 2015 we posted on the list [1] to ask for a project to undertake for our program's capstone design project, and Andrew Cooper pointed us in the direction of the live migration implementation as an area that could use some attention. We were particularly interested in post-copy live migration (as evaluated by [2] and discussed on the list at [3]), and have been working on an implementation of this on-and-off since then.

We now have a working implementation of this scheme, and are submitting it for comment. The changes are also available as the 'postcopy' branch of the GitHub repository at [4]

As a brief overview of our approach:
- We introduce a mechanism by which libxl can indicate to the libxc stream helper process that the iterative migration precopy loop should be terminated and postcopy should begin.
- At this point, we suspend the domain, collect the final set of dirty pfns and write these pfns (and _not_ their contents) into the stream.
- At the destination, the xc restore logic registers itself as a pager for the migrating domain, 'evicts' all of the pfns indicated by the sender as outstanding, and then resumes the domain at the destination.
- As the domain executes, the migration sender continues to push the remaining oustanding pages to the receiver in the background. The receiver monitors both the stream for incoming page data and the paging ring event channel for page faults triggered by the guest. Page faults are forwarded on the back-channel migration stream to the migration sender, which prioritizes these pages for transmission.

Quoted 5 lines

By leveraging the existing paging API, we are able to implement the postcopy scheme without any hypervisor modifications - all of our changes are confined to the userspace toolstack. However, we inherit from the paging API the requirement that the domains be HVM and that the host have HAP/EPT support.

Please consider writing a design document for this feature and stick it at the beginning of your series in the future. You can find examples under docs/designs.

The restriction is a bit unfortunate, but we shouldn't block useful work because it's incomplete. We just need to make sure should someone decide to implement similar functionality for PV guest, they should be able to do so.

You might want to check if shadow paging can be used with paging API, such that you can widen the requirement to HVM guest support.

Quoted 12 lines

We haven't yet had the opportunity to perform a quantitative evaluation of the performance trade-offs between the traditional pre-copy and our post-copy strategies, but intend to. Informally, we've been testing our implementation by migrating a domain running the x86 memtest program (which is obviously a tremendously write-heavy workload), and have observed a substantial reduction in total time required for migration completion (at the expense of a visually obvious 'slowdown' in the execution of the program). We've also noticed that, when performing a postcopy without any leading precopy iterations, the time required at the destination to 'evict' all of the outstanding pages is substantial - possibly because there is no batching mechanism by which pages can be evicted - so this area in particular might require further attention.

Please do post numbers when you have them. For now, please be patient and wait for people to comment.

Wei.

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

#48 lore raw
Quoted 4 lines · Wei Liu

Hi Harley, Chester and Joshua

This is really nice work. I took a brief look at all the patches, they look really high quality.

Thank you!

Quoted 3 lines

We're currently approaching freeze for a Xen release. We've got a lot on our plate. I think maintainers will get to this series at some point.

Understood. We're currently approaching our final exams so that's probably for the best :)

Quoted 41 lines

From the look of things some patches can go in because they're general useful.

Quoted 30 lines · Joshua Otto

Hi,

We're a team of three fourth-year undergraduate software engineering students at the University of Waterloo in Canada. In late 2015 we posted on the list [1] to ask for a project to undertake for our program's capstone design project, and Andrew Cooper pointed us in the direction of the live migration implementation as an area that could use some attention. We were particularly interested in post-copy live migration (as evaluated by [2] and discussed on the list at [3]), and have been working on an implementation of this on-and-off since then.

We now have a working implementation of this scheme, and are submitting it for comment. The changes are also available as the 'postcopy' branch of the GitHub repository at [4]

As a brief overview of our approach:
- We introduce a mechanism by which libxl can indicate to the libxc stream helper process that the iterative migration precopy loop should be terminated and postcopy should begin.
- At this point, we suspend the domain, collect the final set of dirty pfns and write these pfns (and _not_ their contents) into the stream.
- At the destination, the xc restore logic registers itself as a pager for the migrating domain, 'evicts' all of the pfns indicated by the sender as outstanding, and then resumes the domain at the destination.
- As the domain executes, the migration sender continues to push the remaining oustanding pages to the receiver in the background. The receiver monitors both the stream for incoming page data and the paging ring event channel for page faults triggered by the guest. Page faults are forwarded on the back-channel migration stream to the migration sender, which prioritizes these pages for transmission.

Quoted 5 lines

By leveraging the existing paging API, we are able to implement the postcopy scheme without any hypervisor modifications - all of our changes are confined to the userspace toolstack. However, we inherit from the paging API the requirement that the domains be HVM and that the host have HAP/EPT support.

Quoted 3 lines

Please consider writing a design document for this feature and stick it at the beginning of your series in the future. You can find examples under docs/designs.

Absolutely, I'll submit one with v2.

Quoted 22 lines

The restriction is a bit unfortunate, but we shouldn't block useful work because it's incomplete. We just need to make sure should someone decide to implement similar functionality for PV guest, they should be able to do so.

You might want to check if shadow paging can be used with paging API, such that you can widen the requirement to HVM guest support.

Quoted 12 lines

We haven't yet had the opportunity to perform a quantitative evaluation of the performance trade-offs between the traditional pre-copy and our post-copy strategies, but intend to. Informally, we've been testing our implementation by migrating a domain running the x86 memtest program (which is obviously a tremendously write-heavy workload), and have observed a substantial reduction in total time required for migration completion (at the expense of a visually obvious 'slowdown' in the execution of the program). We've also noticed that, when performing a postcopy without any leading precopy iterations, the time required at the destination to 'evict' all of the outstanding pages is substantial - possibly because there is no batching mechanism by which pages can be evicted - so this area in particular might require further attention.

Quoted 2 lines

Please do post numbers when you have them. For now, please be patient and wait for people to comment.

Will do. As a general question for those following the thread, are there any application workloads/benchmarks that people would find particularly interesting?

The experiment that we've planned but haven't had the time to follow through fully is to mount a ramdisk inside the guest and use Axboe's fio to test all of the entries in the (read/write mix) x (working set size) x (access pattern) matrix.

Thank you again for your feedback!

Josh

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

#49 lore raw

On Thu, Mar 30, 2017 at 12:13:51AM -0400, Joshua Otto wrote:
[...]

Quoted 4 lines

Will do. As a general question for those following the thread, are there any application workloads/benchmarks that people would find particularly interesting?

I think any memory intense workload will do. Others might have their preferences.

Quoted 4 lines

The experiment that we've planned but haven't had the time to follow through fully is to mount a ramdisk inside the guest and use Axboe's fio to test all of the entries in the (read/write mix) x (working set size) x (access pattern) matrix.

This sounds reasonable.

Quoted 4 lines

Thank you again for your feedback!

Josh

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

#50 lore raw
In reply to Joshua Otto
Quoted 30 lines · Joshua Otto

Hi,

We're a team of three fourth-year undergraduate software engineering students at the University of Waterloo in Canada. In late 2015 we posted on the list [1] to ask for a project to undertake for our program's capstone design project, and Andrew Cooper pointed us in the direction of the live migration implementation as an area that could use some attention. We were particularly interested in post-copy live migration (as evaluated by [2] and discussed on the list at [3]), and have been working on an implementation of this on-and-off since then.

We now have a working implementation of this scheme, and are submitting it for comment. The changes are also available as the 'postcopy' branch of the GitHub repository at [4]

As a brief overview of our approach:
- We introduce a mechanism by which libxl can indicate to the libxc stream helper process that the iterative migration precopy loop should be terminated and postcopy should begin.
- At this point, we suspend the domain, collect the final set of dirty pfns and write these pfns (and _not_ their contents) into the stream.
- At the destination, the xc restore logic registers itself as a pager for the migrating domain, 'evicts' all of the pfns indicated by the sender as outstanding, and then resumes the domain at the destination.
- As the domain executes, the migration sender continues to push the remaining oustanding pages to the receiver in the background. The receiver monitors both the stream for incoming page data and the paging ring event channel for page faults triggered by the guest. Page faults are forwarded on the back-channel migration stream to the migration sender, which prioritizes these pages for transmission.

Quoted 4 lines

By leveraging the existing paging API, we are able to implement the postcopy scheme without any hypervisor modifications - all of our changes are confined to the userspace toolstack. However, we inherit from the paging API the requirement that the domains be HVM and that the host have HAP/EPT support.

Wow. Considering that the paging API has had no in-tree consumers (and its out-of-tree consumer folded), I am astounded that it hasn't bitrotten.

Quoted 8 lines

We haven't yet had the opportunity to perform a quantitative evaluation of the performance trade-offs between the traditional pre-copy and our post-copy strategies, but intend to. Informally, we've been testing our implementation by migrating a domain running the x86 memtest program (which is obviously a tremendously write-heavy workload), and have observed a substantial reduction in total time required for migration completion (at the expense of a visually obvious 'slowdown' in the execution of the program).

Do you have any numbers, even for this informal testing?

Quoted 7 lines

We've also noticed that,
when performing a postcopy without any leading precopy iterations, the time required at the destination to 'evict' all of the outstanding pages is substantial - possibly because there is no batching mechanism by which pages can be evicted - so this area in particular might require further attention.

We're really interested in any feedback you might have!

Do you have a design document for this? The spec modifications and code comments are great, but there is no substitute (as far as understanding goes) for a description in terms of the algorithm and design choices.

~Andrew

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

#51 lore raw
Quoted 31 lines · Andrew Cooper
Quoted 30 lines · Joshua Otto

Hi,

We're a team of three fourth-year undergraduate software engineering students at the University of Waterloo in Canada. In late 2015 we posted on the list [1] to ask for a project to undertake for our program's capstone design project, and Andrew Cooper pointed us in the direction of the live migration implementation as an area that could use some attention. We were particularly interested in post-copy live migration (as evaluated by [2] and discussed on the list at [3]), and have been working on an implementation of this on-and-off since then.

We now have a working implementation of this scheme, and are submitting it for comment. The changes are also available as the 'postcopy' branch of the GitHub repository at [4]

As a brief overview of our approach:
- We introduce a mechanism by which libxl can indicate to the libxc stream helper process that the iterative migration precopy loop should be terminated and postcopy should begin.
- At this point, we suspend the domain, collect the final set of dirty pfns and write these pfns (and _not_ their contents) into the stream.
- At the destination, the xc restore logic registers itself as a pager for the migrating domain, 'evicts' all of the pfns indicated by the sender as outstanding, and then resumes the domain at the destination.
- As the domain executes, the migration sender continues to push the remaining oustanding pages to the receiver in the background. The receiver monitors both the stream for incoming page data and the paging ring event channel for page faults triggered by the guest. Page faults are forwarded on the back-channel migration stream to the migration sender, which prioritizes these pages for transmission.

Quoted 7 lines
Quoted 4 lines

By leveraging the existing paging API, we are able to implement the postcopy scheme without any hypervisor modifications - all of our changes are confined to the userspace toolstack. However, we inherit from the paging API the requirement that the domains be HVM and that the host have HAP/EPT support.

Wow. Considering that the paging API has had no in-tree consumers (and its out-of-tree consumer folded), I am astounded that it hasn't bitrotten.

Well, there's tools/xenpaging, which was a helpful reference when putting this together. The user-space pager actually has rotted a bit (I'm fairly certain the VM event ring protocol has changed subtly under its feet), so I also needed to consult tools/xen-access to get things right.

Quoted 11 lines
Quoted 9 lines

We haven't yet had the opportunity to perform a quantitative evaluation of the performance trade-offs between the traditional pre-copy and our post-copy strategies, but intend to. Informally, we've been testing our implementation by migrating a domain running the x86 memtest program (which is obviously a tremendously write-heavy workload), and have observed a substantial reduction in total time required for migration completion (at the expense of a visually obvious 'slowdown' in the execution of the program).

Do you have any numbers, even for this informal testing?

We have a much more ambitious test matrix planned, but sure, here's an early encouraging set of measurements - for a domain with 2GB of memory and a 256MB writable working set (the application driving the writes being fio submitting writes against a ramdisk), we measured these times:

Pre-copy + Stop-and-copy | 1 precopy iteration +
(s) | postcopy (s)
--------------------------+-------------------------

 Precopy Duration:           66.97           |         44.44
 Suspend Duration:            6.807          |          3.23
Postcopy Duration:            N/A            |          4.83

However...

That 3.23s suspend for the hybrid migration seems too high, doesn't it?

There's currently a serious performance bug that we're still trying to work out in the case of pure-postcopy migrations, with no leading precopy. Attempting a pure postcopy migration when running the experiment above yields:

Pure postcopy (s)
----------------------
Precopy Duration: 0
Suspend Duration: 21.93
Postcopy Duration: 44.22

Although the postcopy scheme clearly works, it takes 21.93s (!) to unpause the guest at the destination. The eviction of the unmigrated pages completes in a second or two because of the lack of batching support (still bad, but not this bad) - the holdup is somewhere on the domain creation sequence between domcreate_stream_done() and domcreate_complete().

I suspect that this is the result of a bad interaction between QEMU's startup sequence (its foreign memory mapping behaviour in particular) and the postcopy paging. Specifically: the paging ring has room only for 8 requests at a time. When QEMU attempts to map a large range, the range gets postcopy-faulted over synchronously in batches of 8 pages at a time, and each such batch implies a synchronous copy of its pages over the network (and the 100us xenforeignmemory_map() retry timer) before the next batch can begin.

If I am able to confirm that this is the case, a sensible solution would seem to be supporting paging range-population requests (i.e. a new paging ring request type for a _range_ of gfns). In the mean time, you should expect to observe this effect as well in experiments. It appears to be largely (but not completely) mitigated by performing a single pre-copy iteration first.

Quoted 7 lines
Quoted 7 lines

We've also noticed that,
when performing a postcopy without any leading precopy iterations, the time required at the destination to 'evict' all of the outstanding pages is substantial - possibly because there is no batching mechanism by which pages can be evicted - so this area in particular might require further attention.

Quoted 5 lines
Quoted 1 line

We're really interested in any feedback you might have!

Do you have a design document for this? The spec modifications and code comments are great, but there is no substitute (as far as understanding goes) for a description in terms of the algorithm and design choices.

As I replied to Wei, not yet, but we'd happily prepare one for v2.

Thanks!

Josh

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

#52 lore raw
Quoted 7 lines · Joshua Otto
Quoted 7 lines
Quoted 7 lines

We've also noticed that,
when performing a postcopy without any leading precopy iterations, the time required at the destination to 'evict' all of the outstanding pages is substantial - possibly because there is no batching mechanism by which pages can be evicted - so this area in particular might require further attention.

Quoted 8 lines
Quoted 5 lines
Quoted 1 line

We're really interested in any feedback you might have!

Do you have a design document for this? The spec modifications and code comments are great, but there is no substitute (as far as understanding goes) for a description in terms of the algorithm and design choices.

As I replied to Wei, not yet, but we'd happily prepare one for v2.

I've gone through most refactoring patches. They look fine to me. I stopped before the actual implementations because I would like to read your design doc first.

Wei.

Quoted 3 lines

Thanks!

Josh

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