Skip to contentSkip to conversation

Postcopy implementation

PATCH Superseded Dr. David Alan Gilbert (git) 5 participants 181 messages Feb 25, 2015 – Jun 16, 2015 Page 2 of 2

v5 of 9 Superseded Latest is v9 →

lore
Share & tools
lore
#118 lore raw

Re: [Qemu-devel] [PATCH v5 23/45] migrate_start_postcopy: Command to trigger transition to postcopy

In reply to Paolo Bonzini
Quoted 8 lines · Paolo Bonzini
Quoted 5 lines · Dr. David Alan Gilbert
Quoted 5 lines
Quoted 5 lines

But still pointless. Atomicity isn't magic pixie dust; it only makes sense if you're making atomic specific operations that need to be. Simple integer loads and stores are already atomic. Unless at least some of the atomic operations are something more complex, there's really no point to atomically marked operations.

Quoted 5 lines
Quoted 1 line

OK, I'll kill it off.

No, don't.

And both of you, read docs/atomics.txt.

*reads*

Quoted 9 lines

"atomic_read() and atomic_set() prevents the compiler from using optimizations that might otherwise optimize accesses out of existence on the one hand, or that might create unsolicited accesses on the other. [...] it tells readers which variables are shared with
other threads, and which are local to the current thread or protected by other, more mundane means."

atomic_read() and atomic_set() provide the same guarantees as ACCESS_ONCE in the Linux kernel.

Ok, having better understood the semantics and intentions of the atomic_* functions in qemu, I withdraw my objection. They do seem like the right primitives for this situation.

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#119 lore raw

PATCH v5 24/45 MIG_STATE_POSTCOPY_ACTIVE: Add new migration state

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

'MIG_STATE_POSTCOPY_ACTIVE' is entered after migrate_start_postcopy

'migration_postcopy_phase' is provided for other sections to know if they're in postcopy.

---
 include/migration/migration.h |  2 ++
 migration/migration.c         | 58 ++++++++++++++++++++++++++++++++++++++-----
 trace-events                  |  1 +
 3 files changed, 55 insertions(+), 6 deletions(-)
include/migration/migration.h +2 -0
index 293c83e..b44b9b2 100644
@@ -151,6 +151,8 @@ MigrationState *migrate_init(const MigrationParams *params);
 bool migration_in_setup(MigrationState *);
 bool migration_has_finished(MigrationState *);
 bool migration_has_failed(MigrationState *);
+/* True if outgoing migration has entered postcopy phase */
+bool migration_postcopy_phase(MigrationState *);
 MigrationState *migrate_get_current(void);
 
 uint64_t ram_bytes_remaining(void);
migration/migration.c +52 -6

118 lines not on this page · raw message

trace-events +1 -0
index 83312b6..941976a 100644
@@ -1402,6 +1402,7 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
+migration_thread_setup_complete(void) ""
 open_outgoing_return_path(void) ""
 open_outgoing_return_path_continue(void) ""
 source_return_path_thread_bad_end(void) ""
Signature · 1 line
2.1.0
Reviewed-by on v5 24/45
#120 lore raw

Re: [Qemu-devel] [PATCH v5 24/45] MIG_STATE_POSTCOPY_ACTIVE: Add new migration state

Quoted 8 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

'MIG_STATE_POSTCOPY_ACTIVE' is entered after migrate_start_postcopy

'migration_postcopy_phase' is provided for other sections to know if they're in postcopy.

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#121 lore raw

PATCH v5 25/45 qemu_savevm_state_complete: Postcopy changes

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

When postcopy calls qemu_savevm_state_complete it's not really the end of migration, so skip:
a) Finishing postcopiable iterative devices - they'll carry on
b) The termination byte on the end of the stream.

We then also add:
qemu_savevm_state_postcopy_complete
which is called at the end of a postcopy migration to call the complete methods on devices skipped in the _complete call.

---
 include/sysemu/sysemu.h |  1 +
 savevm.c                | 61 ++++++++++++++++++++++++++++++++++++++++++++-----
 trace-events            |  1 +
 3 files changed, 57 insertions(+), 6 deletions(-)
include/sysemu/sysemu.h +1 -0
index 5f518b3..0f2e4ed 100644
@@ -114,6 +114,7 @@ void qemu_savevm_state_cancel(void);
 void qemu_savevm_state_pending(QEMUFile *f, uint64_t max_size,
                                uint64_t *res_non_postcopiable,
                                uint64_t *res_postcopiable);
+void qemu_savevm_state_postcopy_complete(QEMUFile *f);
 void qemu_savevm_command_send(QEMUFile *f, enum qemu_vm_cmd command,
                               uint16_t len, uint8_t *data);
 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value);
savevm.c +55 -6

88 lines not on this page · raw message

trace-events +1 -0
index 941976a..a555b56 100644
@@ -1185,6 +1185,7 @@ loadvm_process_command(uint16_t com, uint16_t len) "com=0x%x len=%d"
 loadvm_process_command_ping(uint32_t val) "%x"
 qemu_savevm_send_postcopy_advise(void) ""
 qemu_savevm_send_postcopy_ram_discard(void) ""
+qemu_savevm_state_complete_skip_for_postcopy(const char *section) "skipping: %s"
 savevm_section_start(const char *id, unsigned int section_id) "%s, section_id %u"
 savevm_section_end(const char *id, unsigned int section_id, int ret) "%s, section_id %u -> %d"
 savevm_send_ping(uint32_t val) "%x"
Signature · 1 line
2.1.0
Reviewed-by on v5 25/45
#122 lore raw

Re: [Qemu-devel] [PATCH v5 25/45] qemu_savevm_state_complete: Postcopy changes

Quoted 4 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

When postcopy calls qemu_savevm_state_complete it's not really the end of migration, so skip:

Given that, maybe the name should change..

Quoted 9 lines

a) Finishing postcopiable iterative devices - they'll carry on
b) The termination byte on the end of the stream.

We then also add:
qemu_savevm_state_postcopy_complete
which is called at the end of a postcopy migration to call the complete methods on devices skipped in the _complete call.

Otherwise,

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#123 lore raw

Re: [Qemu-devel] [PATCH v5 25/45] qemu_savevm_state_complete: Postcopy changes

Quoted 7 lines · * David Gibson ([email protected]) wrote:
Quoted 4 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

When postcopy calls qemu_savevm_state_complete it's not really the end of migration, so skip:

Given that, maybe the name should change..

The name reflects that it calls the save_live_complete method on each device, so if we wanted to remove the 'complete' from the name we'd
probably want to change the method name everywhere; and anyway
it does complete most devices; the only exception are devices that are postcopiable.

Quoted 8 lines
Quoted 8 lines

a) Finishing postcopiable iterative devices - they'll carry on
b) The termination byte on the end of the stream.

We then also add:
qemu_savevm_state_postcopy_complete
which is called at the end of a postcopy migration to call the complete methods on devices skipped in the _complete call.

Quoted 5 lines
Quoted 1 line

Otherwise,

Thanks.

Dave

Quoted 6 lines
Signature · 5 lines
-- 
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#124 lore raw

PATCH v5 26/45 Postcopy page-map-incoming (PMI) structure

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

The PMI holds the state of each page on the incoming side, so that we can tell if the page is missing, already received or there is a request outstanding for it.

---
 include/migration/migration.h    |  18 ++++
 include/migration/postcopy-ram.h |  12 +++
 include/qemu/typedefs.h          |   1 +
 migration/postcopy-ram.c         | 223 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 254 insertions(+)
include/migration/migration.h +18 -0
index b44b9b2..86200b9 100644
@@ -48,6 +48,23 @@ enum mig_rpcomm_cmd {
     MIG_RP_CMD_PONG,         /* Response to a PING; data (seq: be32 ) */
 };
 
+/* Postcopy page-map-incoming - data about each page on the inbound side */
+typedef enum {
+   POSTCOPY_PMI_MISSING    = 0, /* page hasn't yet been received */
+   POSTCOPY_PMI_REQUESTED  = 1, /* Kernel asked for a page, not yet got it */
+   POSTCOPY_PMI_RECEIVED   = 2, /* We've got the page */
+} PostcopyPMIState;
+
+struct PostcopyPMI {
+    QemuMutex      mutex;
+    unsigned long *state0;        /* Together with state1 form a */
+    unsigned long *state1;        /* PostcopyPMIState */
+    unsigned long  host_mask;     /* A mask with enough bits set to cover one
+                                     host page in the PMI */
+    unsigned long  host_bits;     /* The number of bits in the map representing
+                                     one host page */
+};
+
 typedef QLIST_HEAD(, LoadStateEntry) LoadStateEntry_Head;
 
 typedef enum {
@@ -69,6 +86,7 @@ struct MigrationIncomingState {
 
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
+    PostcopyPMI    postcopy_pmi;
 };
 
 MigrationIncomingState *migration_incoming_get_current(void);
include/migration/postcopy-ram.h +12 -0
index d81934f..e93ee8a 100644
@@ -13,7 +13,19 @@
 #ifndef QEMU_POSTCOPY_RAM_H
 #define QEMU_POSTCOPY_RAM_H
 
+#include "migration/migration.h"
+
 /* Return true if the host supports everything we need to do postcopy-ram */
 bool postcopy_ram_supported_by_host(void);
 
+/*
+ * In 'advise' mode record that a page has been received.
+ */
+void postcopy_hook_early_receive(MigrationIncomingState *mis,
+                                 size_t bitmap_index);
+
+void postcopy_pmi_destroy(MigrationIncomingState *mis);
+void postcopy_pmi_discard_range(MigrationIncomingState *mis,
+                                size_t start, size_t npages);
+void postcopy_pmi_dump(MigrationIncomingState *mis);
 #endif
include/qemu/typedefs.h +1 -0
index 611db46..924eeb6 100644
@@ -61,6 +61,7 @@ typedef struct PCIExpressHost PCIExpressHost;
 typedef struct PCIHostState PCIHostState;
 typedef struct PCMCIACardState PCMCIACardState;
 typedef struct PixelFormat PixelFormat;
+typedef struct PostcopyPMI PostcopyPMI;
 typedef struct PropertyInfo PropertyInfo;
 typedef struct Property Property;
 typedef struct QEMUBH QEMUBH;
migration/postcopy-ram.c +223 -0

246 lines not on this page · raw message

Signature · 1 line
2.1.0
#125 lore raw

Re: [Qemu-devel] [PATCH v5 26/45] Postcopy page-map-incoming (PMI) structure

Quoted 19 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

The PMI holds the state of each page on the incoming side, so that we can tell if the page is missing, already received or there is a request outstanding for it.

---
 include/migration/migration.h    |  18 ++++
 include/migration/postcopy-ram.h |  12 +++
 include/qemu/typedefs.h          |   1 +
 migration/postcopy-ram.c         | 223 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 254 insertions(+)
include/migration/migration.h +0 -0
index b44b9b2..86200b9 100644

include/migration/migration.h enum mig_rpcomm_cmd { · line 53

Quoted 6 lines
include/migration/migration.h +3 -0
@@ -48,6 +48,23 @@ enum mig_rpcomm_cmd {
     MIG_RP_CMD_PONG,         /* Response to a PING; data (seq: be32 ) */
 };
 
+/* Postcopy page-map-incoming - data about each page on the inbound side */
+typedef enum {
+   POSTCOPY_PMI_MISSING    = 0, /* page hasn't yet been received */

This appears to be a 3 space indent instead of the usual 4.

include/migration/migration.h enum mig_rpcomm_cmd { · line 56

Quoted 3 lines
include/migration/migration.h +3 -0
+   POSTCOPY_PMI_REQUESTED  = 1, /* Kernel asked for a page, not yet got it */
+   POSTCOPY_PMI_RECEIVED   = 2, /* We've got the page */
+} PostcopyPMIState;

TBH, I'm not sure this enum actually helps anything. I wonder if things might actually be cleared if you simply treat the received and requested bitmaps separately.

include/migration/migration.h enum mig_rpcomm_cmd { · line 61

Quoted 4 lines
include/migration/migration.h +4 -0
+struct PostcopyPMI {
+    QemuMutex      mutex;
+    unsigned long *state0;        /* Together with state1 form a */
+    unsigned long *state1;        /* PostcopyPMIState */

The comments on the lines above don't appear to shed any light on anything.

include/migration/migration.h enum mig_rpcomm_cmd { · line 65

Quoted 4 lines
include/migration/migration.h +4 -0
+    unsigned long  host_mask;     /* A mask with enough bits set to cover one
+                                     host page in the PMI */
+    unsigned long  host_bits;     /* The number of bits in the map representing
+                                     one host page */

I find the host_bits name fairly confusing. Maybe "tp_per_hp"?

Quoted 88 lines
include/migration/migration.h +3 -0
+};
+
 typedef QLIST_HEAD(, LoadStateEntry) LoadStateEntry_Head;
 
 typedef enum {
@@ -69,6 +86,7 @@ struct MigrationIncomingState {
 
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
+    PostcopyPMI    postcopy_pmi;
 };
 
 MigrationIncomingState *migration_incoming_get_current(void);
include/migration/postcopy-ram.h +12 -0
index d81934f..e93ee8a 100644
@@ -13,7 +13,19 @@
 #ifndef QEMU_POSTCOPY_RAM_H
 #define QEMU_POSTCOPY_RAM_H
 
+#include "migration/migration.h"
+
 /* Return true if the host supports everything we need to do postcopy-ram */
 bool postcopy_ram_supported_by_host(void);
 
+/*
+ * In 'advise' mode record that a page has been received.
+ */
+void postcopy_hook_early_receive(MigrationIncomingState *mis,
+                                 size_t bitmap_index);
+
+void postcopy_pmi_destroy(MigrationIncomingState *mis);
+void postcopy_pmi_discard_range(MigrationIncomingState *mis,
+                                size_t start, size_t npages);
+void postcopy_pmi_dump(MigrationIncomingState *mis);
 #endif
include/qemu/typedefs.h +1 -0
index 611db46..924eeb6 100644
@@ -61,6 +61,7 @@ typedef struct PCIExpressHost PCIExpressHost;
 typedef struct PCIHostState PCIHostState;
 typedef struct PCMCIACardState PCMCIACardState;
 typedef struct PixelFormat PixelFormat;
+typedef struct PostcopyPMI PostcopyPMI;
 typedef struct PropertyInfo PropertyInfo;
 typedef struct Property Property;
 typedef struct QEMUBH QEMUBH;
migration/postcopy-ram.c +24 -0
index a0e20b2..4f29055 100644
@@ -24,6 +24,7 @@
 #include "migration/migration.h"
 #include "migration/postcopy-ram.h"
 #include "sysemu/sysemu.h"
+#include "qemu/bitmap.h"
 #include "qemu/error-report.h"
 #include "trace.h"
 
@@ -49,6 +50,220 @@
 
 #if defined(__linux__) && defined(__NR_userfaultfd)
 
+/* ---------------------------------------------------------------------- */
+/* Postcopy pagemap-inbound (pmi) - data structures that record the       */
+/* state of each page used by the inbound postcopy                        */
+/* It's a pair of bitmaps (of the same structure as the migration bitmaps)*/
+/* holding one bit per target-page, although most operations work on host */
+/* pages, the exception being a hook that receives incoming pages off the */
+/* migration stream which come in a TP at a time, although the source     */
+/* _should_ guarantee it sends a sequence of TPs representing HPs during  */
+/* the postcopy phase, there is no such guarantee during precopy.  We     */
+/* could boil this down to only holding one bit per-host page, but we lose*/
+/* sanity checking that we really do get whole host-pages from the source.*/
+__attribute__ (( unused )) /* Until later in patch series */
+static void postcopy_pmi_init(MigrationIncomingState *mis, size_t ram_pages)
+{
+    unsigned int tpb = qemu_target_page_bits();
+    unsigned long host_bits;
+
+    qemu_mutex_init(&mis->postcopy_pmi.mutex);
+    mis->postcopy_pmi.state0 = bitmap_new(ram_pages);
+    mis->postcopy_pmi.state1 = bitmap_new(ram_pages);
+    bitmap_clear(mis->postcopy_pmi.state0, 0, ram_pages);
+    bitmap_clear(mis->postcopy_pmi.state1, 0, ram_pages);
+    /*

migration/postcopy-ram.c line 85

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+     * Each bit in the map represents one 'target page' which is no bigger
+     * than a host page but can be smaller.  It's useful to have some
+     * convenience masks for later
+     */
+
+    /*
+     * The number of bits one host page takes up in the bitmap
+     * e.g. on a 64k host page, 4k Target page, host_bits=64/4=16
+     */
+    host_bits = getpagesize() / (1ul << tpb);

That's equivalent to getpagesize() >> tpb, isn't it?

Quoted 62 lines
migration/postcopy-ram.c +62 -0
+    assert(is_power_of_2(host_bits));
+
+    mis->postcopy_pmi.host_bits = host_bits;
+
+    if (host_bits < BITS_PER_LONG) {
+        /* A mask starting at bit 0 containing host_bits continuous set bits */
+        mis->postcopy_pmi.host_mask =  (1ul << host_bits) - 1;
+    } else {
+        /*
+         * This is a host where the ratio between host and target pages is
+         * bigger than the size of our longs, so we can't make a mask
+         * but we are only losing sanity checking if we just check one long's
+         * worth of bits.
+         */
+        mis->postcopy_pmi.host_mask = ~0l;
+    }
+
+
+    assert((ram_pages % host_bits) == 0);
+}
+
+void postcopy_pmi_destroy(MigrationIncomingState *mis)
+{
+    g_free(mis->postcopy_pmi.state0);
+    mis->postcopy_pmi.state0 = NULL;
+    g_free(mis->postcopy_pmi.state1);
+    mis->postcopy_pmi.state1 = NULL;
+    qemu_mutex_destroy(&mis->postcopy_pmi.mutex);
+}
+
+/*
+ * Mark a set of pages in the PMI as being clear; this is used by the discard
+ * at the start of postcopy, and before the postcopy stream starts.
+ */
+void postcopy_pmi_discard_range(MigrationIncomingState *mis,
+                                size_t start, size_t npages)
+{
+    /* Clear to state 0 = missing */
+    bitmap_clear(mis->postcopy_pmi.state0, start, npages);
+    bitmap_clear(mis->postcopy_pmi.state1, start, npages);
+}
+
+/*
+ * Test a host-page worth of bits in the map starting at bitmap_index
+ * The bits should all be consistent
+ */
+static bool test_hpbits(MigrationIncomingState *mis,
+                        size_t bitmap_index, unsigned long *map)
+{
+    long masked;
+
+    assert((bitmap_index & (mis->postcopy_pmi.host_bits-1)) == 0);
+
+    masked = (map[BIT_WORD(bitmap_index)] >>
+               (bitmap_index % BITS_PER_LONG)) &
+             mis->postcopy_pmi.host_mask;
+
+    assert((masked == 0) || (masked == mis->postcopy_pmi.host_mask));
+    return !!masked;
+}
+
+/*

migration/postcopy-ram.c line 157

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+ * Set host-page worth of bits in the map starting at bitmap_index
+ * to the given state
+ */
+static void set_hp(MigrationIncomingState *mis,
+                   size_t bitmap_index, PostcopyPMIState state)
+{
+    long shifted_mask = mis->postcopy_pmi.host_mask <<
+                        (bitmap_index % BITS_PER_LONG);
+
+    assert((bitmap_index & (mis->postcopy_pmi.host_bits-1)) == 0);

assert(state != 0)?

migration/postcopy-ram.c line 159

Quoted 2 lines
migration/postcopy-ram.c +2 -0
+
+    if (state & 1) {

Using the symbolic constants for PostcopyPMIState values here might be better.

Quoted 15 lines
migration/postcopy-ram.c +15 -0
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+    if (state & 2) {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+}
+
+/*
+ * Retrieve the state of the given page
+ * Note: This version for use by callers already holding the lock
+ */

migration/postcopy-ram.c line 184

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+static PostcopyPMIState postcopy_pmi_get_state_nolock(
+                            MigrationIncomingState *mis,
+                            size_t bitmap_index)
+{
+    bool b0, b1;
+
+    b0 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state0);
+    b1 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state1);
+
+    return (b0 ? 1 : 0) + (b1 ? 2 : 0);

Ugh.. this is a hidden dependency on the PostcopyPMIState enum elements never changing value. Safer to code it as:

      if (!b0 && !b1) {
          return POSTCOPY_PMI_MISSING;
      } else if (...)
           ...

and let gcc sort it out.

Quoted 69 lines
migration/postcopy-ram.c +69 -0
+}
+
+/* Retrieve the state of the given page */
+__attribute__ (( unused )) /* Until later in patch series */
+static PostcopyPMIState postcopy_pmi_get_state(MigrationIncomingState *mis,
+                                               size_t bitmap_index)
+{
+    PostcopyPMIState ret;
+    qemu_mutex_lock(&mis->postcopy_pmi.mutex);
+    ret = postcopy_pmi_get_state_nolock(mis, bitmap_index);
+    qemu_mutex_unlock(&mis->postcopy_pmi.mutex);
+
+    return ret;
+}
+
+/*
+ * Set the page state to the given state if the previous state was as expected
+ * Return the actual previous state.
+ */
+__attribute__ (( unused )) /* Until later in patch series */
+static PostcopyPMIState postcopy_pmi_change_state(MigrationIncomingState *mis,
+                                           size_t bitmap_index,
+                                           PostcopyPMIState expected_state,
+                                           PostcopyPMIState new_state)
+{
+    PostcopyPMIState old_state;
+
+    qemu_mutex_lock(&mis->postcopy_pmi.mutex);
+    old_state = postcopy_pmi_get_state_nolock(mis, bitmap_index);
+
+    if (old_state == expected_state) {
+        switch (new_state) {
+        case POSTCOPY_PMI_MISSING:
+            assert(0); /* This shouldn't happen - use discard_range */
+            break;
+
+        case POSTCOPY_PMI_REQUESTED:
+            assert(old_state == POSTCOPY_PMI_MISSING);
+            /* missing -> requested */
+            set_hp(mis, bitmap_index, POSTCOPY_PMI_REQUESTED);
+            break;
+
+        case POSTCOPY_PMI_RECEIVED:
+            assert(old_state == POSTCOPY_PMI_MISSING ||
+                   old_state == POSTCOPY_PMI_REQUESTED);
+            /* -> received */
+            set_hp(mis, bitmap_index, POSTCOPY_PMI_RECEIVED);
+            break;
+        }
+    }
+
+    qemu_mutex_unlock(&mis->postcopy_pmi.mutex);
+    return old_state;
+}
+
+/*
+ * Useful when debugging postcopy, although if it failed early the
+ * received map can be quite sparse and thus big when dumped.
+ */
+void postcopy_pmi_dump(MigrationIncomingState *mis)
+{
+    fprintf(stderr, "postcopy_pmi_dump: bit 0\n");
+    ram_debug_dump_bitmap(mis->postcopy_pmi.state0, false);
+    fprintf(stderr, "postcopy_pmi_dump: bit 1\n");
+    ram_debug_dump_bitmap(mis->postcopy_pmi.state1, true);
+    fprintf(stderr, "postcopy_pmi_dump: end\n");
+}
+
+/* Called by ram_load prior to mapping the page */

migration/postcopy-ram.c line 263

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+void postcopy_hook_early_receive(MigrationIncomingState *mis,
+                                 size_t bitmap_index)
+{
+    if (mis->postcopy_state == POSTCOPY_INCOMING_ADVISE) {
+        /*
+         * If we're in precopy-advise mode we need to track received pages even
+         * though we don't need to place pages atomically yet.
+         * In advise mode there's only a single thread, so don't need locks
+         */
+        set_bit(bitmap_index, mis->postcopy_pmi.state1); /* 2=received */

Yeah.. so this bypasses postcopy_pmi_{get,change}_state, which again makes me wonder whether the enum serves any purpose.

migration/postcopy-ram.c static bool ufd_version_check(int ufd) · line 289

Quoted 11 lines
migration/postcopy-ram.c +4 -0
+    }
+}
+
 static bool ufd_version_check(int ufd)
 {
     struct uffdio_api api_struct;
@@ -71,6 +286,7 @@ static bool ufd_version_check(int ufd)
     return true;
 }
 
+

Extraneous whitespace change.

Quoted 16 lines
migration/postcopy-ram.c +7 -0
 bool postcopy_ram_supported_by_host(void)
 {
     long pagesize = getpagesize();
@@ -157,5 +373,12 @@ bool postcopy_ram_supported_by_host(void)
     return false;
 }
 
+/* Called by ram_load prior to mapping the page */
+void postcopy_hook_early_receive(MigrationIncomingState *mis,
+                                 size_t bitmap_index)
+{
+    /* We don't support postcopy so don't care */
+}
+
 #endif
 
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#126 lore raw

Re: [Qemu-devel] [PATCH v5 26/45] Postcopy page-map-incoming (PMI) structure

Quoted 23 lines · * David Gibson ([email protected]) wrote:
Quoted 22 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

The PMI holds the state of each page on the incoming side, so that we can tell if the page is missing, already received or there is a request outstanding for it.

---
 include/migration/migration.h    |  18 ++++
 include/migration/postcopy-ram.h |  12 +++
 include/qemu/typedefs.h          |   1 +
 migration/postcopy-ram.c         | 223 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 254 insertions(+)
include/migration/migration.h +0 -0
index b44b9b2..86200b9 100644
@@ -48,6 +48,23 @@ enum mig_rpcomm_cmd {
     MIG_RP_CMD_PONG,         /* Response to a PING; data (seq: be32 ) */
 };
 
Quoted 5 lines

include/migration/migration.h enum mig_rpcomm_cmd { · line 53

Quoted 3 lines
include/migration/migration.h +3 -0
+/* Postcopy page-map-incoming - data about each page on the inbound side */
+typedef enum {
+   POSTCOPY_PMI_MISSING    = 0, /* page hasn't yet been received */

This appears to be a 3 space indent instead of the usual 4.

Thanks; (wth didn't scripts/checkpatch spot that?)

Quoted 8 lines

include/migration/migration.h enum mig_rpcomm_cmd { · line 56

Quoted 3 lines
include/migration/migration.h +3 -0
+   POSTCOPY_PMI_REQUESTED  = 1, /* Kernel asked for a page, not yet got it */
+   POSTCOPY_PMI_RECEIVED   = 2, /* We've got the page */
+} PostcopyPMIState;

TBH, I'm not sure this enum actually helps anything. I wonder if things might actually be cleared if you simply treat the received and requested bitmaps separately.

Quoted 6 lines

include/migration/migration.h enum mig_rpcomm_cmd { · line 61

Quoted 4 lines
include/migration/migration.h +4 -0
+struct PostcopyPMI {
+    QemuMutex      mutex;
+    unsigned long *state0;        /* Together with state1 form a */
+    unsigned long *state1;        /* PostcopyPMIState */

The comments on the lines above don't appear to shed any light on anything.

Hmm; so most of the comments here come down to how this pair are represented. I'd previously had a 'received' and 'requested' array pair, and only used !received, !requested
received, !requested
!received, requested

but one of the intermediate changes (that never survived) I needed a 4th state, and well I did have the 4th state it ended up encoded as received && requested; but that wasn't actually what my 4th state meant, and so I thought it best to try and get away from each of the bits meaning something and try and move more towards just treating it as a state with the encoding to the two state bits done in as few places as possible.
Really what I want is a nice dense efficient array of PostcopyPMIState's.

Quoted 6 lines

include/migration/migration.h enum mig_rpcomm_cmd { · line 65

Quoted 4 lines
include/migration/migration.h +4 -0
+    unsigned long  host_mask;     /* A mask with enough bits set to cover one
+                                     host page in the PMI */
+    unsigned long  host_bits;     /* The number of bits in the map representing
+                                     one host page */

I find the host_bits name fairly confusing. Maybe "tp_per_hp"?

Done.

Quoted 92 lines
Quoted 92 lines
include/migration/migration.h +3 -0
+};
+
 typedef QLIST_HEAD(, LoadStateEntry) LoadStateEntry_Head;
 
 typedef enum {
@@ -69,6 +86,7 @@ struct MigrationIncomingState {
 
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
+    PostcopyPMI    postcopy_pmi;
 };
 
 MigrationIncomingState *migration_incoming_get_current(void);
include/migration/postcopy-ram.h +12 -0
index d81934f..e93ee8a 100644
@@ -13,7 +13,19 @@
 #ifndef QEMU_POSTCOPY_RAM_H
 #define QEMU_POSTCOPY_RAM_H
 
+#include "migration/migration.h"
+
 /* Return true if the host supports everything we need to do postcopy-ram */
 bool postcopy_ram_supported_by_host(void);
 
+/*
+ * In 'advise' mode record that a page has been received.
+ */
+void postcopy_hook_early_receive(MigrationIncomingState *mis,
+                                 size_t bitmap_index);
+
+void postcopy_pmi_destroy(MigrationIncomingState *mis);
+void postcopy_pmi_discard_range(MigrationIncomingState *mis,
+                                size_t start, size_t npages);
+void postcopy_pmi_dump(MigrationIncomingState *mis);
 #endif
include/qemu/typedefs.h +1 -0
index 611db46..924eeb6 100644
@@ -61,6 +61,7 @@ typedef struct PCIExpressHost PCIExpressHost;
 typedef struct PCIHostState PCIHostState;
 typedef struct PCMCIACardState PCMCIACardState;
 typedef struct PixelFormat PixelFormat;
+typedef struct PostcopyPMI PostcopyPMI;
 typedef struct PropertyInfo PropertyInfo;
 typedef struct Property Property;
 typedef struct QEMUBH QEMUBH;
migration/postcopy-ram.c +28 -0
index a0e20b2..4f29055 100644
@@ -24,6 +24,7 @@
 #include "migration/migration.h"
 #include "migration/postcopy-ram.h"
 #include "sysemu/sysemu.h"
+#include "qemu/bitmap.h"
 #include "qemu/error-report.h"
 #include "trace.h"
 
@@ -49,6 +50,220 @@
 
 #if defined(__linux__) && defined(__NR_userfaultfd)
 
+/* ---------------------------------------------------------------------- */
+/* Postcopy pagemap-inbound (pmi) - data structures that record the       */
+/* state of each page used by the inbound postcopy                        */
+/* It's a pair of bitmaps (of the same structure as the migration bitmaps)*/
+/* holding one bit per target-page, although most operations work on host */
+/* pages, the exception being a hook that receives incoming pages off the */
+/* migration stream which come in a TP at a time, although the source     */
+/* _should_ guarantee it sends a sequence of TPs representing HPs during  */
+/* the postcopy phase, there is no such guarantee during precopy.  We     */
+/* could boil this down to only holding one bit per-host page, but we lose*/
+/* sanity checking that we really do get whole host-pages from the source.*/
+__attribute__ (( unused )) /* Until later in patch series */
+static void postcopy_pmi_init(MigrationIncomingState *mis, size_t ram_pages)
+{
+    unsigned int tpb = qemu_target_page_bits();
+    unsigned long host_bits;
+
+    qemu_mutex_init(&mis->postcopy_pmi.mutex);
+    mis->postcopy_pmi.state0 = bitmap_new(ram_pages);
+    mis->postcopy_pmi.state1 = bitmap_new(ram_pages);
+    bitmap_clear(mis->postcopy_pmi.state0, 0, ram_pages);
+    bitmap_clear(mis->postcopy_pmi.state1, 0, ram_pages);
+    /*
+     * Each bit in the map represents one 'target page' which is no bigger
+     * than a host page but can be smaller.  It's useful to have some
+     * convenience masks for later
+     */
Quoted 8 lines

migration/postcopy-ram.c line 85

Quoted 6 lines
migration/postcopy-ram.c +6 -0
+
+    /*
+     * The number of bits one host page takes up in the bitmap
+     * e.g. on a 64k host page, 4k Target page, host_bits=64/4=16
+     */
+    host_bits = getpagesize() / (1ul << tpb);

That's equivalent to getpagesize() >> tpb, isn't it?

Yes, fixed.

Quoted 66 lines
Quoted 66 lines
migration/postcopy-ram.c +66 -0
+    assert(is_power_of_2(host_bits));
+
+    mis->postcopy_pmi.host_bits = host_bits;
+
+    if (host_bits < BITS_PER_LONG) {
+        /* A mask starting at bit 0 containing host_bits continuous set bits */
+        mis->postcopy_pmi.host_mask =  (1ul << host_bits) - 1;
+    } else {
+        /*
+         * This is a host where the ratio between host and target pages is
+         * bigger than the size of our longs, so we can't make a mask
+         * but we are only losing sanity checking if we just check one long's
+         * worth of bits.
+         */
+        mis->postcopy_pmi.host_mask = ~0l;
+    }
+
+
+    assert((ram_pages % host_bits) == 0);
+}
+
+void postcopy_pmi_destroy(MigrationIncomingState *mis)
+{
+    g_free(mis->postcopy_pmi.state0);
+    mis->postcopy_pmi.state0 = NULL;
+    g_free(mis->postcopy_pmi.state1);
+    mis->postcopy_pmi.state1 = NULL;
+    qemu_mutex_destroy(&mis->postcopy_pmi.mutex);
+}
+
+/*
+ * Mark a set of pages in the PMI as being clear; this is used by the discard
+ * at the start of postcopy, and before the postcopy stream starts.
+ */
+void postcopy_pmi_discard_range(MigrationIncomingState *mis,
+                                size_t start, size_t npages)
+{
+    /* Clear to state 0 = missing */
+    bitmap_clear(mis->postcopy_pmi.state0, start, npages);
+    bitmap_clear(mis->postcopy_pmi.state1, start, npages);
+}
+
+/*
+ * Test a host-page worth of bits in the map starting at bitmap_index
+ * The bits should all be consistent
+ */
+static bool test_hpbits(MigrationIncomingState *mis,
+                        size_t bitmap_index, unsigned long *map)
+{
+    long masked;
+
+    assert((bitmap_index & (mis->postcopy_pmi.host_bits-1)) == 0);
+
+    masked = (map[BIT_WORD(bitmap_index)] >>
+               (bitmap_index % BITS_PER_LONG)) &
+             mis->postcopy_pmi.host_mask;
+
+    assert((masked == 0) || (masked == mis->postcopy_pmi.host_mask));
+    return !!masked;
+}
+
+/*
+ * Set host-page worth of bits in the map starting at bitmap_index
+ * to the given state
+ */
+static void set_hp(MigrationIncomingState *mis,
Quoted 8 lines

migration/postcopy-ram.c line 157

Quoted 6 lines
migration/postcopy-ram.c +6 -0
+                   size_t bitmap_index, PostcopyPMIState state)
+{
+    long shifted_mask = mis->postcopy_pmi.host_mask <<
+                        (bitmap_index % BITS_PER_LONG);
+
+    assert((bitmap_index & (mis->postcopy_pmi.host_bits-1)) == 0);

assert(state != 0)?

It could do, although again I'm just trying to make this encode things.

Quoted 5 lines

migration/postcopy-ram.c line 159

Quoted 2 lines
migration/postcopy-ram.c +2 -0
+
+    if (state & 1) {

Using the symbolic constants for PostcopyPMIState values here might be better.

I was treating this as the thing that encoded/decoded the enum; it doesn't need to know the meanings of the bits.

Quoted 29 lines
Quoted 16 lines
migration/postcopy-ram.c +15 -0
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+    if (state & 2) {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+}
+
+/*
+ * Retrieve the state of the given page
+ * Note: This version for use by callers already holding the lock
+ */

migration/postcopy-ram.c line 184

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+static PostcopyPMIState postcopy_pmi_get_state_nolock(
+                            MigrationIncomingState *mis,
+                            size_t bitmap_index)
+{
+    bool b0, b1;
+
+    b0 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state0);
+    b1 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state1);
+
+    return (b0 ? 1 : 0) + (b1 ? 2 : 0);

Ugh.. this is a hidden dependency on the PostcopyPMIState enum elements never changing value. Safer to code it as:

Quoted 6 lines
      if (!b0 && !b1) {
          return POSTCOPY_PMI_MISSING;
      } else if (...)
           ...

and let gcc sort it out.

Again, I was trying to make this just the interface; so it doesn't know or care about the enum mapping; we can change the enum mapping to the bits without changing this function (or the callers) at all.

Quoted 74 lines
Quoted 74 lines
migration/postcopy-ram.c +74 -0
+}
+
+/* Retrieve the state of the given page */
+__attribute__ (( unused )) /* Until later in patch series */
+static PostcopyPMIState postcopy_pmi_get_state(MigrationIncomingState *mis,
+                                               size_t bitmap_index)
+{
+    PostcopyPMIState ret;
+    qemu_mutex_lock(&mis->postcopy_pmi.mutex);
+    ret = postcopy_pmi_get_state_nolock(mis, bitmap_index);
+    qemu_mutex_unlock(&mis->postcopy_pmi.mutex);
+
+    return ret;
+}
+
+/*
+ * Set the page state to the given state if the previous state was as expected
+ * Return the actual previous state.
+ */
+__attribute__ (( unused )) /* Until later in patch series */
+static PostcopyPMIState postcopy_pmi_change_state(MigrationIncomingState *mis,
+                                           size_t bitmap_index,
+                                           PostcopyPMIState expected_state,
+                                           PostcopyPMIState new_state)
+{
+    PostcopyPMIState old_state;
+
+    qemu_mutex_lock(&mis->postcopy_pmi.mutex);
+    old_state = postcopy_pmi_get_state_nolock(mis, bitmap_index);
+
+    if (old_state == expected_state) {
+        switch (new_state) {
+        case POSTCOPY_PMI_MISSING:
+            assert(0); /* This shouldn't happen - use discard_range */
+            break;
+
+        case POSTCOPY_PMI_REQUESTED:
+            assert(old_state == POSTCOPY_PMI_MISSING);
+            /* missing -> requested */
+            set_hp(mis, bitmap_index, POSTCOPY_PMI_REQUESTED);
+            break;
+
+        case POSTCOPY_PMI_RECEIVED:
+            assert(old_state == POSTCOPY_PMI_MISSING ||
+                   old_state == POSTCOPY_PMI_REQUESTED);
+            /* -> received */
+            set_hp(mis, bitmap_index, POSTCOPY_PMI_RECEIVED);
+            break;
+        }
+    }
+
+    qemu_mutex_unlock(&mis->postcopy_pmi.mutex);
+    return old_state;
+}
+
+/*
+ * Useful when debugging postcopy, although if it failed early the
+ * received map can be quite sparse and thus big when dumped.
+ */
+void postcopy_pmi_dump(MigrationIncomingState *mis)
+{
+    fprintf(stderr, "postcopy_pmi_dump: bit 0\n");
+    ram_debug_dump_bitmap(mis->postcopy_pmi.state0, false);
+    fprintf(stderr, "postcopy_pmi_dump: bit 1\n");
+    ram_debug_dump_bitmap(mis->postcopy_pmi.state1, true);
+    fprintf(stderr, "postcopy_pmi_dump: end\n");
+}
+
+/* Called by ram_load prior to mapping the page */
+void postcopy_hook_early_receive(MigrationIncomingState *mis,
+                                 size_t bitmap_index)
+{
+    if (mis->postcopy_state == POSTCOPY_INCOMING_ADVISE) {
+        /*
Quoted 8 lines

migration/postcopy-ram.c line 263

Quoted 5 lines
migration/postcopy-ram.c +5 -0
+         * If we're in precopy-advise mode we need to track received pages even
+         * though we don't need to place pages atomically yet.
+         * In advise mode there's only a single thread, so don't need locks
+         */
+        set_bit(bitmap_index, mis->postcopy_pmi.state1); /* 2=received */

Yeah.. so this bypasses postcopy_pmi_{get,change}_state, which again makes me wonder whether the enum serves any purpose.

Yes, let me see how to fix that; this is the one place that deals in things other than host-pages.

Quoted 10 lines
Quoted 10 lines
migration/postcopy-ram.c +3 -0
+    }
+}
+
 static bool ufd_version_check(int ufd)
 {
     struct uffdio_api api_struct;
@@ -71,6 +286,7 @@ static bool ufd_version_check(int ufd)
     return true;
 }
 
Quoted 3 lines

migration/postcopy-ram.c static bool ufd_version_check(int ufd) · line 289

Quoted 1 line
migration/postcopy-ram.c +1 -0
+

Extraneous whitespace change.

Oops; gone.

Quoted 8 lines
Quoted 8 lines
migration/postcopy-ram.c +0 -0
 bool postcopy_ram_supported_by_host(void)
 {
     long pagesize = getpagesize();
@@ -157,5 +373,12 @@ bool postcopy_ram_supported_by_host(void)
     return false;
 }
 
Quoted 9 lines

migration/postcopy-ram.c bool postcopy_ram_supported_by_host(void) · line 384

Quoted 9 lines
migration/postcopy-ram.c +7 -0
+/* Called by ram_load prior to mapping the page */
+void postcopy_hook_early_receive(MigrationIncomingState *mis,
+                                 size_t bitmap_index)
+{
+    /* We don't support postcopy so don't care */
+}
+
 #endif
 

Thanks,

Dave

Quoted 6 lines
Signature · 5 lines
-- 
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#127 lore raw

Re: [Qemu-devel] [PATCH v5 26/45] Postcopy page-map-incoming (PMI) structure

Quoted 3 lines · Dr. David Alan Gilbert
Quoted 2 lines · * David Gibson ([email protected]) wrote:
Quoted 1 line · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

[snip]

Quoted 33 lines
Quoted 33 lines
Quoted 15 lines
migration/postcopy-ram.c +15 -0
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+    if (state & 2) {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+}
+
+/*
+ * Retrieve the state of the given page
+ * Note: This version for use by callers already holding the lock
+ */

migration/postcopy-ram.c line 184

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+static PostcopyPMIState postcopy_pmi_get_state_nolock(
+                            MigrationIncomingState *mis,
+                            size_t bitmap_index)
+{
+    bool b0, b1;
+
+    b0 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state0);
+    b1 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state1);
+
+    return (b0 ? 1 : 0) + (b1 ? 2 : 0);

Ugh.. this is a hidden dependency on the PostcopyPMIState enum elements never changing value. Safer to code it as:

      if (!b0 && !b1) {
          return POSTCOPY_PMI_MISSING;
      } else if (...)
           ...
Quoted 5 lines
Quoted 1 line

and let gcc sort it out.

Again, I was trying to make this just the interface; so it doesn't know or care about the enum mapping; we can change the enum mapping to the bits without changing this function (or the callers) at all.

So.. I'm not entirely clear what you mean by that. I think what you're saying is that this function basically returns an arbitrary bit pattern derived from the state maps, and the enum provides the mapping from those bit patterns to meaningful states?

That's.. subtle :/.

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#128 lore raw

Re: [Qemu-devel] [PATCH v5 26/45] Postcopy page-map-incoming (PMI) structure

Quoted 44 lines · * David Gibson ([email protected]) wrote:
Quoted 3 lines · Dr. David Alan Gilbert
Quoted 2 lines · * David Gibson ([email protected]) wrote:
Quoted 1 line · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

[snip]

Quoted 33 lines
Quoted 33 lines
Quoted 15 lines
migration/postcopy-ram.c +15 -0
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+    if (state & 2) {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+}
+
+/*
+ * Retrieve the state of the given page
+ * Note: This version for use by callers already holding the lock
+ */

migration/postcopy-ram.c line 184

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+static PostcopyPMIState postcopy_pmi_get_state_nolock(
+                            MigrationIncomingState *mis,
+                            size_t bitmap_index)
+{
+    bool b0, b1;
+
+    b0 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state0);
+    b1 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state1);
+
+    return (b0 ? 1 : 0) + (b1 ? 2 : 0);

Ugh.. this is a hidden dependency on the PostcopyPMIState enum elements never changing value. Safer to code it as:

      if (!b0 && !b1) {
          return POSTCOPY_PMI_MISSING;
      } else if (...)
           ...
Quoted 5 lines
Quoted 1 line

and let gcc sort it out.

Again, I was trying to make this just the interface; so it doesn't know or care about the enum mapping; we can change the enum mapping to the bits without changing this function (or the callers) at all.

Quoted 6 lines

So.. I'm not entirely clear what you mean by that. I think what you're saying is that this function basically returns an arbitrary bit pattern derived from the state maps, and the enum provides the mapping from those bit patterns to meaningful states?

That's.. subtle :/.

I'm saying that I'd like everywhere to work in terms of the enum; but since I can't store the array of enums I need to convert somewhere; if I can keep the conversion to only being a couple of functions that know about the bit layout and everything else uses those functions, then it feels safe/clean.

Dave

Quoted 6 lines
Signature · 5 lines
-- 
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#129 lore raw

Re: [Qemu-devel] [PATCH v5 26/45] Postcopy page-map-incoming (PMI) structure

Quoted 50 lines · Dr. David Alan Gilbert
Quoted 49 lines · * David Gibson ([email protected]) wrote:
Quoted 3 lines · Dr. David Alan Gilbert
Quoted 2 lines · * David Gibson ([email protected]) wrote:
Quoted 1 line · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

[snip]

Quoted 33 lines
Quoted 33 lines
Quoted 15 lines
migration/postcopy-ram.c +15 -0
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state0[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+    if (state & 2) {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] |= shifted_mask;
+    } else {
+        mis->postcopy_pmi.state1[BIT_WORD(bitmap_index)] &= ~shifted_mask;
+    }
+}
+
+/*
+ * Retrieve the state of the given page
+ * Note: This version for use by callers already holding the lock
+ */

migration/postcopy-ram.c line 184

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+static PostcopyPMIState postcopy_pmi_get_state_nolock(
+                            MigrationIncomingState *mis,
+                            size_t bitmap_index)
+{
+    bool b0, b1;
+
+    b0 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state0);
+    b1 = test_hpbits(mis, bitmap_index, mis->postcopy_pmi.state1);
+
+    return (b0 ? 1 : 0) + (b1 ? 2 : 0);

Ugh.. this is a hidden dependency on the PostcopyPMIState enum elements never changing value. Safer to code it as:

      if (!b0 && !b1) {
          return POSTCOPY_PMI_MISSING;
      } else if (...)
           ...
Quoted 5 lines
Quoted 1 line

and let gcc sort it out.

Again, I was trying to make this just the interface; so it doesn't know or care about the enum mapping; we can change the enum mapping to the bits without changing this function (or the callers) at all.

So.. I'm not entirely clear what you mean by that. I think what you're saying is that this function basically returns an arbitrary bit pattern derived from the state maps, and the enum provides the mapping from those bit patterns to meaningful states?

Quoted 7 lines
Quoted 1 line

That's.. subtle :/.

I'm saying that I'd like everywhere to work in terms of the enum; but since I can't store the array of enums I need to convert somewhere; if I can keep the conversion to only being a couple of functions that know about the bit layout and everything else uses those functions, then it feels safe/clean.

Hm, yeah, I guess. It's all a bit confusing, but I see the internal sense in your scheme.

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#130 lore raw

PATCH v5 27/45 Postcopy: Maintain sentmap and calculate discard

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Where postcopy is preceeded by a period of precopy, the destination will have received pages that may have been dirtied on the source after the page was sent. The destination must throw these pages away before starting it's CPUs.

Maintain a 'sentmap' of pages that have already been sent. Calculate list of sent & dirty pages
Provide helpers on the destination side to discard these.

---
 arch_init.c                      | 275 ++++++++++++++++++++++++++++++++++++++-
 include/migration/migration.h    |  12 ++
 include/migration/postcopy-ram.h |  34 +++++
 include/qemu/typedefs.h          |   1 +
 migration/migration.c            |   1 +
 migration/postcopy-ram.c         | 111 ++++++++++++++++
 savevm.c                         |   3 -
 trace-events                     |   4 +
 8 files changed, 435 insertions(+), 6 deletions(-)
arch_init.c +272 -3
index 7bc5fa6..21e7ebe 100644
@@ -40,6 +40,7 @@
 #include "hw/audio/audio.h"
 #include "sysemu/kvm.h"
 #include "migration/migration.h"
+#include "migration/postcopy-ram.h"
 #include "hw/i386/smbios.h"
 #include "exec/address-spaces.h"
 #include "hw/audio/pcspk.h"
@@ -414,9 +415,17 @@ static int save_xbzrle_page(QEMUFile *f, uint8_t **current_data,
     return bytes_sent;
 }
 
+/* mr: The region to search for dirty pages in
+ * start: Start address (typically so we can continue from previous page)
+ * ram_addr_abs: Pointer into which to store the address of the dirty page
+ *               within the global ram_addr space
+ *
+ * Returns: byte offset within memory region of the start of a dirty page
+ */
 static inline
 ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
-                                                 ram_addr_t start)
+                                                 ram_addr_t start,
+                                                 ram_addr_t *ram_addr_abs)
 {
     unsigned long base = mr->ram_addr >> TARGET_PAGE_BITS;
     unsigned long nr = base + (start >> TARGET_PAGE_BITS);
@@ -435,6 +444,7 @@ ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
         clear_bit(next, migration_bitmap);
         migration_dirty_pages--;
     }
+    *ram_addr_abs = next << TARGET_PAGE_BITS;
     return (next - base) << TARGET_PAGE_BITS;
 }
 
@@ -571,6 +581,19 @@ static void migration_bitmap_sync(void)
     }
 }
 
+static RAMBlock *ram_find_block(const char *id)
+{
+    RAMBlock *block;
+
+    QTAILQ_FOREACH(block, &ram_list.blocks, next) {
+        if (!strcmp(id, block->idstr)) {
+            return block;
+        }
+    }
+
+    return NULL;
+}
+
 /*
  * ram_save_page: Send the given page to the stream
  *
@@ -659,13 +682,16 @@ static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
     bool complete_round = false;
     int bytes_sent = 0;
     MemoryRegion *mr;
+    ram_addr_t dirty_ram_abs; /* Address of the start of the dirty page in
+                                 ram_addr_t space */
 
     if (!block)
         block = QTAILQ_FIRST(&ram_list.blocks);
 
     while (true) {
         mr = block->mr;
-        offset = migration_bitmap_find_and_reset_dirty(mr, offset);
+        offset = migration_bitmap_find_and_reset_dirty(mr, offset,
+                                                       &dirty_ram_abs);
         if (complete_round && block == last_seen_block &&
             offset >= last_offset) {
             break;
@@ -683,6 +709,11 @@ static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
 
             /* if page is unmodified, continue to the next */
             if (bytes_sent > 0) {
+                MigrationState *ms = migrate_get_current();
+                if (ms->sentmap) {
+                    set_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap);
+                }
+
                 last_sent_block = block;
                 break;
             }
@@ -742,12 +773,19 @@ void free_xbzrle_decoded_buf(void)
 
 static void migration_end(void)
 {
+    MigrationState *s = migrate_get_current();
+
     if (migration_bitmap) {
         memory_global_dirty_log_stop();
         g_free(migration_bitmap);
         migration_bitmap = NULL;
     }
 
+    if (s->sentmap) {
+        g_free(s->sentmap);
+        s->sentmap = NULL;
+    }
+
     XBZRLE_cache_lock();
     if (XBZRLE.cache) {
         cache_fini(XBZRLE.cache);
@@ -815,6 +853,232 @@ void ram_debug_dump_bitmap(unsigned long *todump, bool expected)
     }
 }
 
+/* **** functions for postcopy ***** */
+
+/*
+ * A helper to get 32 bits from a bit map; trivial for HOST_LONG_BITS=32
+ * messier for 64; the bitmaps are actually long's that are 32 or 64bit
+ */
+static uint32_t get_32bits_map(unsigned long *map, int64_t start)
+{
+#if HOST_LONG_BITS == 64
+    uint64_t tmp64;
+
+    tmp64 = map[start / 64];
+    return (start & 32) ? (tmp64 >> 32) : (tmp64 & 0xffffffffu);
+#elif HOST_LONG_BITS == 32
+    /*
+     * Irrespective of host endianness, sentmap[n] is for pages earlier
+     * than sentmap[n+1] so we can't just cast up
+     */
+    return map[start / 32];
+#else
+#error "Host long other than 64/32 not supported"
+#endif
+}
+
+/*
+ * A helper to put 32 bits into a bit map; trivial for HOST_LONG_BITS=32
+ * messier for 64; the bitmaps are actually long's that are 32 or 64bit
+ */
+__attribute__ (( unused )) /* Until later in patch series */
+static void put_32bits_map(unsigned long *map, int64_t start,
+                           uint32_t v)
+{
+#if HOST_LONG_BITS == 64
+    uint64_t tmp64 = v;
+    uint64_t mask = 0xffffffffu;
+
+    if (start & 32) {
+        tmp64 = tmp64 << 32;
+        mask =  mask << 32;
+    }
+
+    map[start / 64] = (map[start / 64] & ~mask) | tmp64;
+#elif HOST_LONG_BITS == 32
+    /*
+     * Irrespective of host endianness, sentmap[n] is for pages earlier
+     * than sentmap[n+1] so we can't just cast up
+     */
+    map[start / 32] = v;
+#else
+#error "Host long other than 64/32 not supported"
+#endif
+}
+
+/*
+ * When working on 32bit chunks of a bitmap where the only valid section
+ * is between start..end (inclusive), generate a mask with only those
+ * valid bits set for the current 32bit word within that bitmask.
+ */
+static int make_32bit_mask(unsigned long start, unsigned long end,
+                           unsigned long cur32)
+{
+    unsigned long first32, last32;
+    uint32_t mask = ~(uint32_t)0;
+    first32 = start / 32;
+    last32 = end / 32;
+
+    if ((cur32 == first32) && (start & 31)) {
+        /* e.g. (start & 31) = 3
+         *         1 << .    -> 2^3
+         *         . - 1     -> 2^3 - 1 i.e. mask 2..0
+         *         ~.        -> mask 31..3
+         */
+        mask &= ~((((uint32_t)1) << (start & 31)) - 1);
+    }
+
+    if ((cur32 == last32) && ((end & 31) != 31)) {
+        /* e.g. (end & 31) = 3
+         *            .   +1 -> 4
+         *         1 << .    -> 2^4
+         *         . -1      -> 2^4 - 1
+         *                   = mask set 3..0
+         */
+        mask &= (((uint32_t)1) << ((end & 31) + 1)) - 1;
+    }
+
+    return mask;
+}
+
+/*
+ * Callback from ram_postcopy_each_ram_discard for each RAMBlock
+ * start,end: Indexes into the bitmap for the first and last bit
+ *            representing the named block
+ */
+static int pc_send_discard_bm_ram(MigrationState *ms,
+                                  PostcopyDiscardState *pds,
+                                  unsigned long start, unsigned long end)
+{
+    /*
+     * There is no guarantee that start, end are on convenient 32bit multiples
+     * (We always send 32bit chunks over the wire, irrespective of long size)
+     */
+    unsigned long first32, last32, cur32;
+    first32 = start / 32;
+    last32 = end / 32;
+
+    for (cur32 = first32; cur32 <= last32; cur32++) {
+        /* Deal with start/end not on alignment */
+        uint32_t mask = make_32bit_mask(start, end, cur32);
+
+        uint32_t data = get_32bits_map(ms->sentmap, cur32 * 32);
+        data &= mask;
+
+        if (data) {
+            postcopy_discard_send_chunk(ms, pds, (cur32-first32) * 32, data);
+        }
+    }
+
+    return 0;
+}
+
+/*
+ * Utility for the outgoing postcopy code.
+ *   Calls postcopy_send_discard_bm_ram for each RAMBlock
+ *   passing it bitmap indexes and name.
+ * Returns: 0 on success
+ * (qemu_ram_foreach_block ends up passing unscaled lengths
+ *  which would mean postcopy code would have to deal with target page)
+ */
+static int pc_each_ram_discard(MigrationState *ms)
+{
+    struct RAMBlock *block;
+    int ret;
+
+    QTAILQ_FOREACH(block, &ram_list.blocks, next) {
+        unsigned long first = block->offset >> TARGET_PAGE_BITS;
+        unsigned long last = (block->offset + (block->max_length-1))
+                                >> TARGET_PAGE_BITS;
+        PostcopyDiscardState *pds = postcopy_discard_send_init(ms,
+                                                               first & 31,
+                                                               block->idstr);
+
+        /*
+         * Postcopy sends chunks of bitmap over the wire, but it
+         * just needs indexes at this point, avoids it having
+         * target page specific code.
+         */
+        ret = pc_send_discard_bm_ram(ms, pds, first, last);
+        postcopy_discard_send_finish(ms, pds);
+        if (ret) {
+            return ret;
+        }
+    }
+
+    return 0;
+}
+
+/*
+ * Transmit the set of pages to be discarded after precopy to the target
+ * these are pages that have been sent previously but have been dirtied
+ * Hopefully this is pretty sparse
+ */
+int ram_postcopy_send_discard_bitmap(MigrationState *ms)
+{
+    /* This should be our last sync, the src is now paused */
+    migration_bitmap_sync();
+
+    /*
+     * Update the sentmap to be  sentmap&=dirty
+     */
+    bitmap_and(ms->sentmap, ms->sentmap, migration_bitmap,
+               last_ram_offset() >> TARGET_PAGE_BITS);
+
+
+    trace_ram_postcopy_send_discard_bitmap();
+#ifdef DEBUG_POSTCOPY
+    ram_debug_dump_bitmap(ms->sentmap, false);
+#endif
+
+    return pc_each_ram_discard(ms);
+}
+
+/*
+ * At the start of the postcopy phase of migration, any now-dirty
+ * precopied pages are discarded.
+ *
+ * start..end is an inclusive range of bits indexed in the source
+ *    VMs bitmap for this RAMBlock, source_target_page_bits tells
+ *    us what one of those bits represents.
+ *
+ * start/end are offsets from the start of the bitmap for RAMBlock 'block_name'
+ *
+ * Returns 0 on success.
+ */
+int ram_discard_range(MigrationIncomingState *mis,
+                      const char *block_name,
+                      uint64_t start, uint64_t end)
+{
+    assert(end >= start);
+
+    RAMBlock *rb = ram_find_block(block_name);
+
+    if (!rb) {
+        error_report("ram_discard_range: Failed to find block '%s'",
+                     block_name);
+        return -1;
+    }
+
+    uint64_t index_offset = rb->offset >> TARGET_PAGE_BITS;
+    postcopy_pmi_discard_range(mis, start + index_offset, (end - start) + 1);
+
+    /* +1 gives the byte after the end of the last page to be discarded */
+    ram_addr_t end_offset = (end+1) << TARGET_PAGE_BITS;
+    uint8_t *host_startaddr = rb->host + (start << TARGET_PAGE_BITS);
+    uint8_t *host_endaddr;
+
+    if (end_offset <= rb->used_length) {
+        host_endaddr   = rb->host + (end_offset-1);
+        return postcopy_ram_discard_range(mis, host_startaddr, host_endaddr);
+    } else {
+        error_report("ram_discard_range: Overrun block '%s' (%" PRIu64
+                     "/%" PRIu64 "/%zu)",
+                     block_name, start, end, rb->used_length);
+        return -1;
+    }
+}
+
 static int ram_save_setup(QEMUFile *f, void *opaque)
 {
     RAMBlock *block;
@@ -854,7 +1118,6 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
 
         acct_clear();
     }
-
     qemu_mutex_lock_iothread();
     qemu_mutex_lock_ramlist();
     bytes_transferred = 0;
@@ -864,6 +1127,12 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
     migration_bitmap = bitmap_new(ram_bitmap_pages);
     bitmap_set(migration_bitmap, 0, ram_bitmap_pages);
 
+    if (migrate_postcopy_ram()) {
+        MigrationState *s = migrate_get_current();
+        s->sentmap = bitmap_new(ram_bitmap_pages);
+        bitmap_clear(s->sentmap, 0, ram_bitmap_pages);
+    }
+
     /*
      * Count the total number of pages used by ram blocks not including any
      * gaps due to alignment or unplugs.
include/migration/migration.h +12 -0
index 86200b9..e749f4c 100644
@@ -125,6 +125,13 @@ struct MigrationState
 
     /* Flag set once the migration has been asked to enter postcopy */
     bool start_postcopy;
+
+    /* bitmap of pages that have been sent at least once
+     * only maintained and used in postcopy at the moment
+     * where it's used to send the dirtymap at the start
+     * of the postcopy phase
+     */
+    unsigned long *sentmap;
 };
 
 void process_incoming_migration(QEMUFile *f);
@@ -194,6 +201,11 @@ double xbzrle_mig_cache_miss_rate(void);
 
 void ram_handle_compressed(void *host, uint8_t ch, uint64_t size);
 void ram_debug_dump_bitmap(unsigned long *todump, bool expected);
+/* For outgoing discard bitmap */
+int ram_postcopy_send_discard_bitmap(MigrationState *ms);
+/* For incoming postcopy discard */
+int ram_discard_range(MigrationIncomingState *mis, const char *block_name,
+                      uint64_t start, uint64_t end);
 
 /**
  * @migrate_add_blocker - prevent migration from proceeding
include/migration/postcopy-ram.h +34 -0
index e93ee8a..1fec1c1 100644
@@ -28,4 +28,38 @@ void postcopy_pmi_destroy(MigrationIncomingState *mis);
 void postcopy_pmi_discard_range(MigrationIncomingState *mis,
                                 size_t start, size_t npages);
 void postcopy_pmi_dump(MigrationIncomingState *mis);
+
+/*
+ * Discard the contents of memory start..end inclusive.
+ * We can assume that if we've been called postcopy_ram_hosttest returned true
+ */
+int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
+                               uint8_t *end);
+
+
+/*
+ * Called at the start of each RAMBlock by the bitmap code
+ * offset is the bit within the first 32bit chunk of mask
+ * that represents the first page of the RAM Block
+ * Returns a new PDS
+ */
+PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
+                                                 uint8_t offset,
+                                                 const char *name);
+
+/*
+ * Called by the bitmap code for each chunk to discard
+ * May send a discard message, may just leave it queued to
+ * be sent later
+ */
+void postcopy_discard_send_chunk(MigrationState *ms, PostcopyDiscardState *pds,
+                                unsigned long pos, uint32_t bitmap);
+
+/*
+ * Called at the end of each RAMBlock by the bitmap code
+ * Sends any outstanding discard messages, frees the PDS
+ */
+void postcopy_discard_send_finish(MigrationState *ms,
+                                  PostcopyDiscardState *pds);
+
 #endif
include/qemu/typedefs.h +1 -0
index 924eeb6..0651275 100644
@@ -61,6 +61,7 @@ typedef struct PCIExpressHost PCIExpressHost;
 typedef struct PCIHostState PCIHostState;
 typedef struct PCMCIACardState PCMCIACardState;
 typedef struct PixelFormat PixelFormat;
+typedef struct PostcopyDiscardState PostcopyDiscardState;
 typedef struct PostcopyPMI PostcopyPMI;
 typedef struct PropertyInfo PropertyInfo;
 typedef struct Property Property;
migration/migration.c +1 -0
index 6b20b56..850fe1a 100644
@@ -22,6 +22,7 @@
 #include "block/block.h"
 #include "qemu/sockets.h"
 #include "migration/block.h"
+#include "migration/postcopy-ram.h"
 #include "qemu/thread.h"
 #include "qmp-commands.h"
 #include "trace.h"
migration/postcopy-ram.c +111 -0

128 lines not on this page · raw message

savevm.c +0 -3
index 1e8d289..2589b8c 100644
@@ -1282,15 +1282,12 @@ static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
              * we know there must be at least 1 bit set due to the loop entry
              * If there is no 0 firstzero will be 32
              */
-            /* TODO - ram_discard_range gets added in a later patch
             int ret = ram_discard_range(mis, ramid,
                                 startaddr + firstset - first_bit_offset,
                                 startaddr + (firstzero - 1) - first_bit_offset);
-            ret = -1;
             if (ret) {
                 return ret;
             }
-            */
 
             /* mask= .?0000000000 */
             /*         ^fz ^fs    */
trace-events +4 -0
index a555b56..f985117 100644
@@ -1217,6 +1217,7 @@ qemu_file_fclose(void) ""
 migration_bitmap_sync_start(void) ""
 migration_bitmap_sync_end(uint64_t dirty_pages) "dirty_pages %" PRIu64""
 migration_throttle(void) ""
+ram_postcopy_send_discard_bitmap(void) ""
 
 # hw/display/qxl.c
 disable qxl_interface_set_mm_time(int qid, uint32_t mm_time) "%d %d"
@@ -1478,6 +1479,9 @@ rdma_start_incoming_migration_after_rdma_listen(void) ""
 rdma_start_outgoing_migration_after_rdma_connect(void) ""
 rdma_start_outgoing_migration_after_rdma_source_init(void) ""
 
+# migration/postcopy-ram.c
+postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s mask words sent=%d in %d commands"
+
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
 kvm_vm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 1 line
2.1.0
#131 lore raw

Re: [Qemu-devel] [PATCH v5 27/45] Postcopy: Maintain sentmap and calculate discard

Quoted 213 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Where postcopy is preceeded by a period of precopy, the destination will have received pages that may have been dirtied on the source after the page was sent. The destination must throw these pages away before starting it's CPUs.

Maintain a 'sentmap' of pages that have already been sent. Calculate list of sent & dirty pages
Provide helpers on the destination side to discard these.

---
 arch_init.c                      | 275 ++++++++++++++++++++++++++++++++++++++-
 include/migration/migration.h    |  12 ++
 include/migration/postcopy-ram.h |  34 +++++
 include/qemu/typedefs.h          |   1 +
 migration/migration.c            |   1 +
 migration/postcopy-ram.c         | 111 ++++++++++++++++
 savevm.c                         |   3 -
 trace-events                     |   4 +
 8 files changed, 435 insertions(+), 6 deletions(-)
arch_init.c +117 -2
index 7bc5fa6..21e7ebe 100644
@@ -40,6 +40,7 @@
 #include "hw/audio/audio.h"
 #include "sysemu/kvm.h"
 #include "migration/migration.h"
+#include "migration/postcopy-ram.h"
 #include "hw/i386/smbios.h"
 #include "exec/address-spaces.h"
 #include "hw/audio/pcspk.h"
@@ -414,9 +415,17 @@ static int save_xbzrle_page(QEMUFile *f, uint8_t **current_data,
     return bytes_sent;
 }
 
+/* mr: The region to search for dirty pages in
+ * start: Start address (typically so we can continue from previous page)
+ * ram_addr_abs: Pointer into which to store the address of the dirty page
+ *               within the global ram_addr space
+ *
+ * Returns: byte offset within memory region of the start of a dirty page
+ */
 static inline
 ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
-                                                 ram_addr_t start)
+                                                 ram_addr_t start,
+                                                 ram_addr_t *ram_addr_abs)
 {
     unsigned long base = mr->ram_addr >> TARGET_PAGE_BITS;
     unsigned long nr = base + (start >> TARGET_PAGE_BITS);
@@ -435,6 +444,7 @@ ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
         clear_bit(next, migration_bitmap);
         migration_dirty_pages--;
     }
+    *ram_addr_abs = next << TARGET_PAGE_BITS;
     return (next - base) << TARGET_PAGE_BITS;
 }
 
@@ -571,6 +581,19 @@ static void migration_bitmap_sync(void)
     }
 }
 
+static RAMBlock *ram_find_block(const char *id)
+{
+    RAMBlock *block;
+
+    QTAILQ_FOREACH(block, &ram_list.blocks, next) {
+        if (!strcmp(id, block->idstr)) {
+            return block;
+        }
+    }
+
+    return NULL;
+}
+
 /*
  * ram_save_page: Send the given page to the stream
  *
@@ -659,13 +682,16 @@ static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
     bool complete_round = false;
     int bytes_sent = 0;
     MemoryRegion *mr;
+    ram_addr_t dirty_ram_abs; /* Address of the start of the dirty page in
+                                 ram_addr_t space */
 
     if (!block)
         block = QTAILQ_FIRST(&ram_list.blocks);
 
     while (true) {
         mr = block->mr;
-        offset = migration_bitmap_find_and_reset_dirty(mr, offset);
+        offset = migration_bitmap_find_and_reset_dirty(mr, offset,
+                                                       &dirty_ram_abs);
         if (complete_round && block == last_seen_block &&
             offset >= last_offset) {
             break;
@@ -683,6 +709,11 @@ static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
 
             /* if page is unmodified, continue to the next */
             if (bytes_sent > 0) {
+                MigrationState *ms = migrate_get_current();
+                if (ms->sentmap) {
+                    set_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap);
+                }
+
                 last_sent_block = block;
                 break;
             }
@@ -742,12 +773,19 @@ void free_xbzrle_decoded_buf(void)
 
 static void migration_end(void)
 {
+    MigrationState *s = migrate_get_current();
+
     if (migration_bitmap) {
         memory_global_dirty_log_stop();
         g_free(migration_bitmap);
         migration_bitmap = NULL;
     }
 
+    if (s->sentmap) {
+        g_free(s->sentmap);
+        s->sentmap = NULL;
+    }
+
     XBZRLE_cache_lock();
     if (XBZRLE.cache) {
         cache_fini(XBZRLE.cache);
@@ -815,6 +853,232 @@ void ram_debug_dump_bitmap(unsigned long *todump, bool expected)
     }
 }
 
+/* **** functions for postcopy ***** */
+
+/*
+ * A helper to get 32 bits from a bit map; trivial for HOST_LONG_BITS=32
+ * messier for 64; the bitmaps are actually long's that are 32 or 64bit
+ */
+static uint32_t get_32bits_map(unsigned long *map, int64_t start)
+{
+#if HOST_LONG_BITS == 64
+    uint64_t tmp64;
+
+    tmp64 = map[start / 64];
+    return (start & 32) ? (tmp64 >> 32) : (tmp64 & 0xffffffffu);
+#elif HOST_LONG_BITS == 32
+    /*
+     * Irrespective of host endianness, sentmap[n] is for pages earlier
+     * than sentmap[n+1] so we can't just cast up
+     */
+    return map[start / 32];
+#else
+#error "Host long other than 64/32 not supported"
+#endif
+}
+
+/*
+ * A helper to put 32 bits into a bit map; trivial for HOST_LONG_BITS=32
+ * messier for 64; the bitmaps are actually long's that are 32 or 64bit
+ */
+__attribute__ (( unused )) /* Until later in patch series */
+static void put_32bits_map(unsigned long *map, int64_t start,
+                           uint32_t v)
+{
+#if HOST_LONG_BITS == 64
+    uint64_t tmp64 = v;
+    uint64_t mask = 0xffffffffu;
+
+    if (start & 32) {
+        tmp64 = tmp64 << 32;
+        mask =  mask << 32;
+    }
+
+    map[start / 64] = (map[start / 64] & ~mask) | tmp64;
+#elif HOST_LONG_BITS == 32
+    /*
+     * Irrespective of host endianness, sentmap[n] is for pages earlier
+     * than sentmap[n+1] so we can't just cast up
+     */
+    map[start / 32] = v;
+#else
+#error "Host long other than 64/32 not supported"
+#endif
+}
+
+/*
+ * When working on 32bit chunks of a bitmap where the only valid section
+ * is between start..end (inclusive), generate a mask with only those
+ * valid bits set for the current 32bit word within that bitmask.
+ */
+static int make_32bit_mask(unsigned long start, unsigned long end,
+                           unsigned long cur32)
+{
+    unsigned long first32, last32;
+    uint32_t mask = ~(uint32_t)0;
+    first32 = start / 32;
+    last32 = end / 32;
+
+    if ((cur32 == first32) && (start & 31)) {
+        /* e.g. (start & 31) = 3
+         *         1 << .    -> 2^3
+         *         . - 1     -> 2^3 - 1 i.e. mask 2..0
+         *         ~.        -> mask 31..3
+         */
+        mask &= ~((((uint32_t)1) << (start & 31)) - 1);
+    }
+
+    if ((cur32 == last32) && ((end & 31) != 31)) {
+        /* e.g. (end & 31) = 3

arch_init.c void ram_debug_dump_bitmap(unsigned long *todump, bool expected) · line 942

Quoted 10 lines
arch_init.c +10 -0
+         *            .   +1 -> 4
+         *         1 << .    -> 2^4
+         *         . -1      -> 2^4 - 1
+         *                   = mask set 3..0
+         */
+        mask &= (((uint32_t)1) << ((end & 31) + 1)) - 1;
+    }
+
+    return mask;
+}

Urgh.. looks correct, but continue to makes me question if this is a sensible wire encoding of the discard map.

arch_init.c void ram_debug_dump_bitmap(unsigned long *todump, bool expected) · line 951

Quoted 9 lines
arch_init.c +9 -0
+
+/*
+ * Callback from ram_postcopy_each_ram_discard for each RAMBlock
+ * start,end: Indexes into the bitmap for the first and last bit
+ *            representing the named block
+ */
+static int pc_send_discard_bm_ram(MigrationState *ms,
+                                  PostcopyDiscardState *pds,
+                                  unsigned long start, unsigned long end)

I know it's a long name, but I'd prefer to see this called "postcopy_". I have to keep reminding myself that "pc" means "postcopy" here, not that it's a PC machine type specific function.

Quoted 24 lines
arch_init.c +23 -0
+{
+    /*
+     * There is no guarantee that start, end are on convenient 32bit multiples
+     * (We always send 32bit chunks over the wire, irrespective of long size)
+     */
+    unsigned long first32, last32, cur32;
+    first32 = start / 32;
+    last32 = end / 32;
+
+    for (cur32 = first32; cur32 <= last32; cur32++) {
+        /* Deal with start/end not on alignment */
+        uint32_t mask = make_32bit_mask(start, end, cur32);
+
+        uint32_t data = get_32bits_map(ms->sentmap, cur32 * 32);
+        data &= mask;
+
+        if (data) {
+            postcopy_discard_send_chunk(ms, pds, (cur32-first32) * 32, data);
+        }
+    }
+
+    return 0;
+}
 

arch_init.c void ram_debug_dump_bitmap(unsigned long *todump, bool expected) · line 984

Quoted 10 lines
arch_init.c +9 -0
 
+/*
+ * Utility for the outgoing postcopy code.
+ *   Calls postcopy_send_discard_bm_ram for each RAMBlock
+ *   passing it bitmap indexes and name.
+ * Returns: 0 on success
+ * (qemu_ram_foreach_block ends up passing unscaled lengths
+ *  which would mean postcopy code would have to deal with target page)
+ */
+static int pc_each_ram_discard(MigrationState *ms)

s/discard/send_discard/

Quoted 395 lines
arch_init.c +103 -1
+{
+    struct RAMBlock *block;
+    int ret;
+
+    QTAILQ_FOREACH(block, &ram_list.blocks, next) {
+        unsigned long first = block->offset >> TARGET_PAGE_BITS;
+        unsigned long last = (block->offset + (block->max_length-1))
+                                >> TARGET_PAGE_BITS;
+        PostcopyDiscardState *pds = postcopy_discard_send_init(ms,
+                                                               first & 31,
+                                                               block->idstr);
+
+        /*
+         * Postcopy sends chunks of bitmap over the wire, but it
+         * just needs indexes at this point, avoids it having
+         * target page specific code.
+         */
+        ret = pc_send_discard_bm_ram(ms, pds, first, last);
+        postcopy_discard_send_finish(ms, pds);
+        if (ret) {
+            return ret;
+        }
+    }
+
+    return 0;
+}
+
+/*
+ * Transmit the set of pages to be discarded after precopy to the target
+ * these are pages that have been sent previously but have been dirtied
+ * Hopefully this is pretty sparse
+ */
+int ram_postcopy_send_discard_bitmap(MigrationState *ms)
+{
+    /* This should be our last sync, the src is now paused */
+    migration_bitmap_sync();
+
+    /*
+     * Update the sentmap to be  sentmap&=dirty
+     */
+    bitmap_and(ms->sentmap, ms->sentmap, migration_bitmap,
+               last_ram_offset() >> TARGET_PAGE_BITS);
+
+
+    trace_ram_postcopy_send_discard_bitmap();
+#ifdef DEBUG_POSTCOPY
+    ram_debug_dump_bitmap(ms->sentmap, false);
+#endif
+
+    return pc_each_ram_discard(ms);
+}
+
+/*
+ * At the start of the postcopy phase of migration, any now-dirty
+ * precopied pages are discarded.
+ *
+ * start..end is an inclusive range of bits indexed in the source
+ *    VMs bitmap for this RAMBlock, source_target_page_bits tells
+ *    us what one of those bits represents.
+ *
+ * start/end are offsets from the start of the bitmap for RAMBlock 'block_name'
+ *
+ * Returns 0 on success.
+ */
+int ram_discard_range(MigrationIncomingState *mis,
+                      const char *block_name,
+                      uint64_t start, uint64_t end)
+{
+    assert(end >= start);
+
+    RAMBlock *rb = ram_find_block(block_name);
+
+    if (!rb) {
+        error_report("ram_discard_range: Failed to find block '%s'",
+                     block_name);
+        return -1;
+    }
+
+    uint64_t index_offset = rb->offset >> TARGET_PAGE_BITS;
+    postcopy_pmi_discard_range(mis, start + index_offset, (end - start) + 1);
+
+    /* +1 gives the byte after the end of the last page to be discarded */
+    ram_addr_t end_offset = (end+1) << TARGET_PAGE_BITS;
+    uint8_t *host_startaddr = rb->host + (start << TARGET_PAGE_BITS);
+    uint8_t *host_endaddr;
+
+    if (end_offset <= rb->used_length) {
+        host_endaddr   = rb->host + (end_offset-1);
+        return postcopy_ram_discard_range(mis, host_startaddr, host_endaddr);
+    } else {
+        error_report("ram_discard_range: Overrun block '%s' (%" PRIu64
+                     "/%" PRIu64 "/%zu)",
+                     block_name, start, end, rb->used_length);
+        return -1;
+    }
+}
+
 static int ram_save_setup(QEMUFile *f, void *opaque)
 {
     RAMBlock *block;
@@ -854,7 +1118,6 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
 
         acct_clear();
     }
-
     qemu_mutex_lock_iothread();
     qemu_mutex_lock_ramlist();
     bytes_transferred = 0;
@@ -864,6 +1127,12 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
     migration_bitmap = bitmap_new(ram_bitmap_pages);
     bitmap_set(migration_bitmap, 0, ram_bitmap_pages);
 
+    if (migrate_postcopy_ram()) {
+        MigrationState *s = migrate_get_current();
+        s->sentmap = bitmap_new(ram_bitmap_pages);
+        bitmap_clear(s->sentmap, 0, ram_bitmap_pages);
+    }
+
     /*
      * Count the total number of pages used by ram blocks not including any
      * gaps due to alignment or unplugs.
include/migration/migration.h +12 -0
index 86200b9..e749f4c 100644
@@ -125,6 +125,13 @@ struct MigrationState
 
     /* Flag set once the migration has been asked to enter postcopy */
     bool start_postcopy;
+
+    /* bitmap of pages that have been sent at least once
+     * only maintained and used in postcopy at the moment
+     * where it's used to send the dirtymap at the start
+     * of the postcopy phase
+     */
+    unsigned long *sentmap;
 };
 
 void process_incoming_migration(QEMUFile *f);
@@ -194,6 +201,11 @@ double xbzrle_mig_cache_miss_rate(void);
 
 void ram_handle_compressed(void *host, uint8_t ch, uint64_t size);
 void ram_debug_dump_bitmap(unsigned long *todump, bool expected);
+/* For outgoing discard bitmap */
+int ram_postcopy_send_discard_bitmap(MigrationState *ms);
+/* For incoming postcopy discard */
+int ram_discard_range(MigrationIncomingState *mis, const char *block_name,
+                      uint64_t start, uint64_t end);
 
 /**
  * @migrate_add_blocker - prevent migration from proceeding
include/migration/postcopy-ram.h +34 -0
index e93ee8a..1fec1c1 100644
@@ -28,4 +28,38 @@ void postcopy_pmi_destroy(MigrationIncomingState *mis);
 void postcopy_pmi_discard_range(MigrationIncomingState *mis,
                                 size_t start, size_t npages);
 void postcopy_pmi_dump(MigrationIncomingState *mis);
+
+/*
+ * Discard the contents of memory start..end inclusive.
+ * We can assume that if we've been called postcopy_ram_hosttest returned true
+ */
+int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
+                               uint8_t *end);
+
+
+/*
+ * Called at the start of each RAMBlock by the bitmap code
+ * offset is the bit within the first 32bit chunk of mask
+ * that represents the first page of the RAM Block
+ * Returns a new PDS
+ */
+PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
+                                                 uint8_t offset,
+                                                 const char *name);
+
+/*
+ * Called by the bitmap code for each chunk to discard
+ * May send a discard message, may just leave it queued to
+ * be sent later
+ */
+void postcopy_discard_send_chunk(MigrationState *ms, PostcopyDiscardState *pds,
+                                unsigned long pos, uint32_t bitmap);
+
+/*
+ * Called at the end of each RAMBlock by the bitmap code
+ * Sends any outstanding discard messages, frees the PDS
+ */
+void postcopy_discard_send_finish(MigrationState *ms,
+                                  PostcopyDiscardState *pds);
+
 #endif
include/qemu/typedefs.h +1 -0
index 924eeb6..0651275 100644
@@ -61,6 +61,7 @@ typedef struct PCIExpressHost PCIExpressHost;
 typedef struct PCIHostState PCIHostState;
 typedef struct PCMCIACardState PCMCIACardState;
 typedef struct PixelFormat PixelFormat;
+typedef struct PostcopyDiscardState PostcopyDiscardState;
 typedef struct PostcopyPMI PostcopyPMI;
 typedef struct PropertyInfo PropertyInfo;
 typedef struct Property Property;
migration/migration.c +1 -0
index 6b20b56..850fe1a 100644
@@ -22,6 +22,7 @@
 #include "block/block.h"
 #include "qemu/sockets.h"
 #include "migration/block.h"
+#include "migration/postcopy-ram.h"
 #include "qemu/thread.h"
 #include "qmp-commands.h"
 #include "trace.h"
migration/postcopy-ram.c +111 -0
index 4f29055..391e9c6 100644
@@ -28,6 +28,19 @@
 #include "qemu/error-report.h"
 #include "trace.h"
 
+#define MAX_DISCARDS_PER_COMMAND 12
+
+struct PostcopyDiscardState {
+    const char *name;
+    uint16_t cur_entry;
+    uint64_t addrlist[MAX_DISCARDS_PER_COMMAND];
+    uint32_t masklist[MAX_DISCARDS_PER_COMMAND];
+    uint8_t  offset;  /* Offset within 32bit mask at addr0 representing 1st
+                         page of block */
+    unsigned int nsentwords;
+    unsigned int nsentcmds;
+};
+
 /* Postcopy needs to detect accesses to pages that haven't yet been copied
  * across, and efficiently map new pages in, the techniques for doing this
  * are target OS specific.
@@ -364,6 +377,21 @@ out:
     return ret;
 }
 
+/*
+ * Discard the contents of memory start..end inclusive.
+ * We can assume that if we've been called postcopy_ram_hosttest returned true
+ */
+int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
+                               uint8_t *end)
+{
+    if (madvise(start, (end-start)+1, MADV_DONTNEED)) {
+        perror("postcopy_ram_discard_range MADV_DONTNEED");
+        return -1;
+    }
+
+    return 0;
+}
+
 #else
 /* No target OS support, stubs just fail */
 
@@ -380,5 +408,88 @@ void postcopy_hook_early_receive(MigrationIncomingState *mis,
     /* We don't support postcopy so don't care */
 }
 
+void postcopy_pmi_destroy(MigrationIncomingState *mis)
+{
+    /* Called in normal cleanup path - so it's OK */
+}
+
+void postcopy_pmi_discard_range(MigrationIncomingState *mis,
+                                size_t start, size_t npages)
+{
+    assert(0);
+}
+
+int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
+                               uint8_t *end)
+{
+    assert(0);
+}
 #endif
 
+/* ------------------------------------------------------------------------- */
+
+/*
+ * Called at the start of each RAMBlock by the bitmap code
+ * offset is the bit within the first 64bit chunk of mask
+ * that represents the first page of the RAM Block
+ * Returns a new PDS
+ */
+PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
+                                                 uint8_t offset,
+                                                 const char *name)
+{
+    PostcopyDiscardState *res = g_try_malloc(sizeof(PostcopyDiscardState));
+
+    if (res) {
+        res->name = name;
+        res->cur_entry = 0;
+        res->nsentwords = 0;
+        res->nsentcmds = 0;
+        res->offset = offset;
+    }
+
+    return res;
+}
+
+/*
+ * Called by the bitmap code for each chunk to discard
+ * May send a discard message, may just leave it queued to
+ * be sent later
+ */
+void postcopy_discard_send_chunk(MigrationState *ms, PostcopyDiscardState *pds,
+                                unsigned long pos, uint32_t bitmap)
+{
+    pds->addrlist[pds->cur_entry] = pos;
+    pds->masklist[pds->cur_entry] = bitmap;
+    pds->cur_entry++;
+    pds->nsentwords++;
+
+    if (pds->cur_entry == MAX_DISCARDS_PER_COMMAND) {
+        /* Full set, ship it! */
+        qemu_savevm_send_postcopy_ram_discard(ms->file, pds->name,
+                                              pds->cur_entry, pds->offset,
+                                              pds->addrlist, pds->masklist);
+        pds->nsentcmds++;
+        pds->cur_entry = 0;
+    }
+}
+
+/*
+ * Called at the end of each RAMBlock by the bitmap code
+ * Sends any outstanding discard messages, frees the PDS
+ */
+void postcopy_discard_send_finish(MigrationState *ms, PostcopyDiscardState *pds)
+{
+    /* Anything unsent? */
+    if (pds->cur_entry) {
+        qemu_savevm_send_postcopy_ram_discard(ms->file, pds->name,
+                                              pds->cur_entry, pds->offset,
+                                              pds->addrlist, pds->masklist);
+        pds->nsentcmds++;
+    }
+
+    trace_postcopy_discard_send_finish(pds->name, pds->nsentwords,
+                                       pds->nsentcmds);
+
+    g_free(pds);
+}
savevm.c +0 -3
index 1e8d289..2589b8c 100644
@@ -1282,15 +1282,12 @@ static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
              * we know there must be at least 1 bit set due to the loop entry
              * If there is no 0 firstzero will be 32
              */
-            /* TODO - ram_discard_range gets added in a later patch
             int ret = ram_discard_range(mis, ramid,
                                 startaddr + firstset - first_bit_offset,
                                 startaddr + (firstzero - 1) - first_bit_offset);
-            ret = -1;
             if (ret) {
                 return ret;
             }
-            */
 
             /* mask= .?0000000000 */
             /*         ^fz ^fs    */
trace-events +4 -0
index a555b56..f985117 100644
@@ -1217,6 +1217,7 @@ qemu_file_fclose(void) ""
 migration_bitmap_sync_start(void) ""
 migration_bitmap_sync_end(uint64_t dirty_pages) "dirty_pages %" PRIu64""
 migration_throttle(void) ""
+ram_postcopy_send_discard_bitmap(void) ""
 
 # hw/display/qxl.c
 disable qxl_interface_set_mm_time(int qid, uint32_t mm_time) "%d %d"
@@ -1478,6 +1479,9 @@ rdma_start_incoming_migration_after_rdma_listen(void) ""
 rdma_start_outgoing_migration_after_rdma_connect(void) ""
 rdma_start_outgoing_migration_after_rdma_source_init(void) ""
 
+# migration/postcopy-ram.c
+postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s mask words sent=%d in %d commands"
+
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
 kvm_vm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#132 lore raw

Re: [Qemu-devel] [PATCH v5 27/45] Postcopy: Maintain sentmap and calculate discard

Quoted 228 lines · * David Gibson ([email protected]) wrote:
Quoted 213 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Where postcopy is preceeded by a period of precopy, the destination will have received pages that may have been dirtied on the source after the page was sent. The destination must throw these pages away before starting it's CPUs.

Maintain a 'sentmap' of pages that have already been sent. Calculate list of sent & dirty pages
Provide helpers on the destination side to discard these.

---
 arch_init.c                      | 275 ++++++++++++++++++++++++++++++++++++++-
 include/migration/migration.h    |  12 ++
 include/migration/postcopy-ram.h |  34 +++++
 include/qemu/typedefs.h          |   1 +
 migration/migration.c            |   1 +
 migration/postcopy-ram.c         | 111 ++++++++++++++++
 savevm.c                         |   3 -
 trace-events                     |   4 +
 8 files changed, 435 insertions(+), 6 deletions(-)
arch_init.c +117 -2
index 7bc5fa6..21e7ebe 100644
@@ -40,6 +40,7 @@
 #include "hw/audio/audio.h"
 #include "sysemu/kvm.h"
 #include "migration/migration.h"
+#include "migration/postcopy-ram.h"
 #include "hw/i386/smbios.h"
 #include "exec/address-spaces.h"
 #include "hw/audio/pcspk.h"
@@ -414,9 +415,17 @@ static int save_xbzrle_page(QEMUFile *f, uint8_t **current_data,
     return bytes_sent;
 }
 
+/* mr: The region to search for dirty pages in
+ * start: Start address (typically so we can continue from previous page)
+ * ram_addr_abs: Pointer into which to store the address of the dirty page
+ *               within the global ram_addr space
+ *
+ * Returns: byte offset within memory region of the start of a dirty page
+ */
 static inline
 ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
-                                                 ram_addr_t start)
+                                                 ram_addr_t start,
+                                                 ram_addr_t *ram_addr_abs)
 {
     unsigned long base = mr->ram_addr >> TARGET_PAGE_BITS;
     unsigned long nr = base + (start >> TARGET_PAGE_BITS);
@@ -435,6 +444,7 @@ ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
         clear_bit(next, migration_bitmap);
         migration_dirty_pages--;
     }
+    *ram_addr_abs = next << TARGET_PAGE_BITS;
     return (next - base) << TARGET_PAGE_BITS;
 }
 
@@ -571,6 +581,19 @@ static void migration_bitmap_sync(void)
     }
 }
 
+static RAMBlock *ram_find_block(const char *id)
+{
+    RAMBlock *block;
+
+    QTAILQ_FOREACH(block, &ram_list.blocks, next) {
+        if (!strcmp(id, block->idstr)) {
+            return block;
+        }
+    }
+
+    return NULL;
+}
+
 /*
  * ram_save_page: Send the given page to the stream
  *
@@ -659,13 +682,16 @@ static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
     bool complete_round = false;
     int bytes_sent = 0;
     MemoryRegion *mr;
+    ram_addr_t dirty_ram_abs; /* Address of the start of the dirty page in
+                                 ram_addr_t space */
 
     if (!block)
         block = QTAILQ_FIRST(&ram_list.blocks);
 
     while (true) {
         mr = block->mr;
-        offset = migration_bitmap_find_and_reset_dirty(mr, offset);
+        offset = migration_bitmap_find_and_reset_dirty(mr, offset,
+                                                       &dirty_ram_abs);
         if (complete_round && block == last_seen_block &&
             offset >= last_offset) {
             break;
@@ -683,6 +709,11 @@ static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
 
             /* if page is unmodified, continue to the next */
             if (bytes_sent > 0) {
+                MigrationState *ms = migrate_get_current();
+                if (ms->sentmap) {
+                    set_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap);
+                }
+
                 last_sent_block = block;
                 break;
             }
@@ -742,12 +773,19 @@ void free_xbzrle_decoded_buf(void)
 
 static void migration_end(void)
 {
+    MigrationState *s = migrate_get_current();
+
     if (migration_bitmap) {
         memory_global_dirty_log_stop();
         g_free(migration_bitmap);
         migration_bitmap = NULL;
     }
 
+    if (s->sentmap) {
+        g_free(s->sentmap);
+        s->sentmap = NULL;
+    }
+
     XBZRLE_cache_lock();
     if (XBZRLE.cache) {
         cache_fini(XBZRLE.cache);
@@ -815,6 +853,232 @@ void ram_debug_dump_bitmap(unsigned long *todump, bool expected)
     }
 }
 
+/* **** functions for postcopy ***** */
+
+/*
+ * A helper to get 32 bits from a bit map; trivial for HOST_LONG_BITS=32
+ * messier for 64; the bitmaps are actually long's that are 32 or 64bit
+ */
+static uint32_t get_32bits_map(unsigned long *map, int64_t start)
+{
+#if HOST_LONG_BITS == 64
+    uint64_t tmp64;
+
+    tmp64 = map[start / 64];
+    return (start & 32) ? (tmp64 >> 32) : (tmp64 & 0xffffffffu);
+#elif HOST_LONG_BITS == 32
+    /*
+     * Irrespective of host endianness, sentmap[n] is for pages earlier
+     * than sentmap[n+1] so we can't just cast up
+     */
+    return map[start / 32];
+#else
+#error "Host long other than 64/32 not supported"
+#endif
+}
+
+/*
+ * A helper to put 32 bits into a bit map; trivial for HOST_LONG_BITS=32
+ * messier for 64; the bitmaps are actually long's that are 32 or 64bit
+ */
+__attribute__ (( unused )) /* Until later in patch series */
+static void put_32bits_map(unsigned long *map, int64_t start,
+                           uint32_t v)
+{
+#if HOST_LONG_BITS == 64
+    uint64_t tmp64 = v;
+    uint64_t mask = 0xffffffffu;
+
+    if (start & 32) {
+        tmp64 = tmp64 << 32;
+        mask =  mask << 32;
+    }
+
+    map[start / 64] = (map[start / 64] & ~mask) | tmp64;
+#elif HOST_LONG_BITS == 32
+    /*
+     * Irrespective of host endianness, sentmap[n] is for pages earlier
+     * than sentmap[n+1] so we can't just cast up
+     */
+    map[start / 32] = v;
+#else
+#error "Host long other than 64/32 not supported"
+#endif
+}
+
+/*
+ * When working on 32bit chunks of a bitmap where the only valid section
+ * is between start..end (inclusive), generate a mask with only those
+ * valid bits set for the current 32bit word within that bitmask.
+ */
+static int make_32bit_mask(unsigned long start, unsigned long end,
+                           unsigned long cur32)
+{
+    unsigned long first32, last32;
+    uint32_t mask = ~(uint32_t)0;
+    first32 = start / 32;
+    last32 = end / 32;
+
+    if ((cur32 == first32) && (start & 31)) {
+        /* e.g. (start & 31) = 3
+         *         1 << .    -> 2^3
+         *         . - 1     -> 2^3 - 1 i.e. mask 2..0
+         *         ~.        -> mask 31..3
+         */
+        mask &= ~((((uint32_t)1) << (start & 31)) - 1);
+    }
+
+    if ((cur32 == last32) && ((end & 31) != 31)) {
+        /* e.g. (end & 31) = 3

arch_init.c void ram_debug_dump_bitmap(unsigned long *todump, bool expected) · line 942

Quoted 10 lines
arch_init.c +10 -0
+         *            .   +1 -> 4
+         *         1 << .    -> 2^4
+         *         . -1      -> 2^4 - 1
+         *                   = mask set 3..0
+         */
+        mask &= (((uint32_t)1) << ((end & 31) + 1)) - 1;
+    }
+
+    return mask;
+}

Urgh.. looks correct, but continue to makes me question if this is a sensible wire encoding of the discard map.

Quoted 13 lines

arch_init.c void ram_debug_dump_bitmap(unsigned long *todump, bool expected) · line 951

Quoted 9 lines
arch_init.c +9 -0
+
+/*
+ * Callback from ram_postcopy_each_ram_discard for each RAMBlock
+ * start,end: Indexes into the bitmap for the first and last bit
+ *            representing the named block
+ */
+static int pc_send_discard_bm_ram(MigrationState *ms,
+                                  PostcopyDiscardState *pds,
+                                  unsigned long start, unsigned long end)

I know it's a long name, but I'd prefer to see this called "postcopy_". I have to keep reminding myself that "pc" means "postcopy" here, not that it's a PC machine type specific function.

OK, yeh I see that's a clash; done.

Quoted 26 lines
Quoted 24 lines
arch_init.c +23 -0
+{
+    /*
+     * There is no guarantee that start, end are on convenient 32bit multiples
+     * (We always send 32bit chunks over the wire, irrespective of long size)
+     */
+    unsigned long first32, last32, cur32;
+    first32 = start / 32;
+    last32 = end / 32;
+
+    for (cur32 = first32; cur32 <= last32; cur32++) {
+        /* Deal with start/end not on alignment */
+        uint32_t mask = make_32bit_mask(start, end, cur32);
+
+        uint32_t data = get_32bits_map(ms->sentmap, cur32 * 32);
+        data &= mask;
+
+        if (data) {
+            postcopy_discard_send_chunk(ms, pds, (cur32-first32) * 32, data);
+        }
+    }
+
+    return 0;
+}
Quoted 11 lines

arch_init.c void ram_debug_dump_bitmap(unsigned long *todump, bool expected) · line 984

Quoted 9 lines
arch_init.c +9 -0
+/*
+ * Utility for the outgoing postcopy code.
+ *   Calls postcopy_send_discard_bm_ram for each RAMBlock
+ *   passing it bitmap indexes and name.
+ * Returns: 0 on success
+ * (qemu_ram_foreach_block ends up passing unscaled lengths
+ *  which would mean postcopy code would have to deal with target page)
+ */
+static int pc_each_ram_discard(MigrationState *ms)

s/discard/send_discard/

Done.

Quoted 390 lines
Quoted 390 lines
arch_init.c +103 -1
+{
+    struct RAMBlock *block;
+    int ret;
+
+    QTAILQ_FOREACH(block, &ram_list.blocks, next) {
+        unsigned long first = block->offset >> TARGET_PAGE_BITS;
+        unsigned long last = (block->offset + (block->max_length-1))
+                                >> TARGET_PAGE_BITS;
+        PostcopyDiscardState *pds = postcopy_discard_send_init(ms,
+                                                               first & 31,
+                                                               block->idstr);
+
+        /*
+         * Postcopy sends chunks of bitmap over the wire, but it
+         * just needs indexes at this point, avoids it having
+         * target page specific code.
+         */
+        ret = pc_send_discard_bm_ram(ms, pds, first, last);
+        postcopy_discard_send_finish(ms, pds);
+        if (ret) {
+            return ret;
+        }
+    }
+
+    return 0;
+}
+
+/*
+ * Transmit the set of pages to be discarded after precopy to the target
+ * these are pages that have been sent previously but have been dirtied
+ * Hopefully this is pretty sparse
+ */
+int ram_postcopy_send_discard_bitmap(MigrationState *ms)
+{
+    /* This should be our last sync, the src is now paused */
+    migration_bitmap_sync();
+
+    /*
+     * Update the sentmap to be  sentmap&=dirty
+     */
+    bitmap_and(ms->sentmap, ms->sentmap, migration_bitmap,
+               last_ram_offset() >> TARGET_PAGE_BITS);
+
+
+    trace_ram_postcopy_send_discard_bitmap();
+#ifdef DEBUG_POSTCOPY
+    ram_debug_dump_bitmap(ms->sentmap, false);
+#endif
+
+    return pc_each_ram_discard(ms);
+}
+
+/*
+ * At the start of the postcopy phase of migration, any now-dirty
+ * precopied pages are discarded.
+ *
+ * start..end is an inclusive range of bits indexed in the source
+ *    VMs bitmap for this RAMBlock, source_target_page_bits tells
+ *    us what one of those bits represents.
+ *
+ * start/end are offsets from the start of the bitmap for RAMBlock 'block_name'
+ *
+ * Returns 0 on success.
+ */
+int ram_discard_range(MigrationIncomingState *mis,
+                      const char *block_name,
+                      uint64_t start, uint64_t end)
+{
+    assert(end >= start);
+
+    RAMBlock *rb = ram_find_block(block_name);
+
+    if (!rb) {
+        error_report("ram_discard_range: Failed to find block '%s'",
+                     block_name);
+        return -1;
+    }
+
+    uint64_t index_offset = rb->offset >> TARGET_PAGE_BITS;
+    postcopy_pmi_discard_range(mis, start + index_offset, (end - start) + 1);
+
+    /* +1 gives the byte after the end of the last page to be discarded */
+    ram_addr_t end_offset = (end+1) << TARGET_PAGE_BITS;
+    uint8_t *host_startaddr = rb->host + (start << TARGET_PAGE_BITS);
+    uint8_t *host_endaddr;
+
+    if (end_offset <= rb->used_length) {
+        host_endaddr   = rb->host + (end_offset-1);
+        return postcopy_ram_discard_range(mis, host_startaddr, host_endaddr);
+    } else {
+        error_report("ram_discard_range: Overrun block '%s' (%" PRIu64
+                     "/%" PRIu64 "/%zu)",
+                     block_name, start, end, rb->used_length);
+        return -1;
+    }
+}
+
 static int ram_save_setup(QEMUFile *f, void *opaque)
 {
     RAMBlock *block;
@@ -854,7 +1118,6 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
 
         acct_clear();
     }
-
     qemu_mutex_lock_iothread();
     qemu_mutex_lock_ramlist();
     bytes_transferred = 0;
@@ -864,6 +1127,12 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
     migration_bitmap = bitmap_new(ram_bitmap_pages);
     bitmap_set(migration_bitmap, 0, ram_bitmap_pages);
 
+    if (migrate_postcopy_ram()) {
+        MigrationState *s = migrate_get_current();
+        s->sentmap = bitmap_new(ram_bitmap_pages);
+        bitmap_clear(s->sentmap, 0, ram_bitmap_pages);
+    }
+
     /*
      * Count the total number of pages used by ram blocks not including any
      * gaps due to alignment or unplugs.
include/migration/migration.h +12 -0
index 86200b9..e749f4c 100644
@@ -125,6 +125,13 @@ struct MigrationState
 
     /* Flag set once the migration has been asked to enter postcopy */
     bool start_postcopy;
+
+    /* bitmap of pages that have been sent at least once
+     * only maintained and used in postcopy at the moment
+     * where it's used to send the dirtymap at the start
+     * of the postcopy phase
+     */
+    unsigned long *sentmap;
 };
 
 void process_incoming_migration(QEMUFile *f);
@@ -194,6 +201,11 @@ double xbzrle_mig_cache_miss_rate(void);
 
 void ram_handle_compressed(void *host, uint8_t ch, uint64_t size);
 void ram_debug_dump_bitmap(unsigned long *todump, bool expected);
+/* For outgoing discard bitmap */
+int ram_postcopy_send_discard_bitmap(MigrationState *ms);
+/* For incoming postcopy discard */
+int ram_discard_range(MigrationIncomingState *mis, const char *block_name,
+                      uint64_t start, uint64_t end);
 
 /**
  * @migrate_add_blocker - prevent migration from proceeding
include/migration/postcopy-ram.h +34 -0
index e93ee8a..1fec1c1 100644
@@ -28,4 +28,38 @@ void postcopy_pmi_destroy(MigrationIncomingState *mis);
 void postcopy_pmi_discard_range(MigrationIncomingState *mis,
                                 size_t start, size_t npages);
 void postcopy_pmi_dump(MigrationIncomingState *mis);
+
+/*
+ * Discard the contents of memory start..end inclusive.
+ * We can assume that if we've been called postcopy_ram_hosttest returned true
+ */
+int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
+                               uint8_t *end);
+
+
+/*
+ * Called at the start of each RAMBlock by the bitmap code
+ * offset is the bit within the first 32bit chunk of mask
+ * that represents the first page of the RAM Block
+ * Returns a new PDS
+ */
+PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
+                                                 uint8_t offset,
+                                                 const char *name);
+
+/*
+ * Called by the bitmap code for each chunk to discard
+ * May send a discard message, may just leave it queued to
+ * be sent later
+ */
+void postcopy_discard_send_chunk(MigrationState *ms, PostcopyDiscardState *pds,
+                                unsigned long pos, uint32_t bitmap);
+
+/*
+ * Called at the end of each RAMBlock by the bitmap code
+ * Sends any outstanding discard messages, frees the PDS
+ */
+void postcopy_discard_send_finish(MigrationState *ms,
+                                  PostcopyDiscardState *pds);
+
 #endif
include/qemu/typedefs.h +1 -0
index 924eeb6..0651275 100644
@@ -61,6 +61,7 @@ typedef struct PCIExpressHost PCIExpressHost;
 typedef struct PCIHostState PCIHostState;
 typedef struct PCMCIACardState PCMCIACardState;
 typedef struct PixelFormat PixelFormat;
+typedef struct PostcopyDiscardState PostcopyDiscardState;
 typedef struct PostcopyPMI PostcopyPMI;
 typedef struct PropertyInfo PropertyInfo;
 typedef struct Property Property;
migration/migration.c +1 -0
index 6b20b56..850fe1a 100644
@@ -22,6 +22,7 @@
 #include "block/block.h"
 #include "qemu/sockets.h"
 #include "migration/block.h"
+#include "migration/postcopy-ram.h"
 #include "qemu/thread.h"
 #include "qmp-commands.h"
 #include "trace.h"
migration/postcopy-ram.c +111 -0
index 4f29055..391e9c6 100644
@@ -28,6 +28,19 @@
 #include "qemu/error-report.h"
 #include "trace.h"
 
+#define MAX_DISCARDS_PER_COMMAND 12
+
+struct PostcopyDiscardState {
+    const char *name;
+    uint16_t cur_entry;
+    uint64_t addrlist[MAX_DISCARDS_PER_COMMAND];
+    uint32_t masklist[MAX_DISCARDS_PER_COMMAND];
+    uint8_t  offset;  /* Offset within 32bit mask at addr0 representing 1st
+                         page of block */
+    unsigned int nsentwords;
+    unsigned int nsentcmds;
+};
+
 /* Postcopy needs to detect accesses to pages that haven't yet been copied
  * across, and efficiently map new pages in, the techniques for doing this
  * are target OS specific.
@@ -364,6 +377,21 @@ out:
     return ret;
 }
 
+/*
+ * Discard the contents of memory start..end inclusive.
+ * We can assume that if we've been called postcopy_ram_hosttest returned true
+ */
+int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
+                               uint8_t *end)
+{
+    if (madvise(start, (end-start)+1, MADV_DONTNEED)) {
+        perror("postcopy_ram_discard_range MADV_DONTNEED");
+        return -1;
+    }
+
+    return 0;
+}
+
 #else
 /* No target OS support, stubs just fail */
 
@@ -380,5 +408,88 @@ void postcopy_hook_early_receive(MigrationIncomingState *mis,
     /* We don't support postcopy so don't care */
 }
 
+void postcopy_pmi_destroy(MigrationIncomingState *mis)
+{
+    /* Called in normal cleanup path - so it's OK */
+}
+
+void postcopy_pmi_discard_range(MigrationIncomingState *mis,
+                                size_t start, size_t npages)
+{
+    assert(0);
+}
+
+int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
+                               uint8_t *end)
+{
+    assert(0);
+}
 #endif
 
+/* ------------------------------------------------------------------------- */
+
+/*
+ * Called at the start of each RAMBlock by the bitmap code
+ * offset is the bit within the first 64bit chunk of mask
+ * that represents the first page of the RAM Block
+ * Returns a new PDS
+ */
+PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
+                                                 uint8_t offset,
+                                                 const char *name)
+{
+    PostcopyDiscardState *res = g_try_malloc(sizeof(PostcopyDiscardState));
+
+    if (res) {
+        res->name = name;
+        res->cur_entry = 0;
+        res->nsentwords = 0;
+        res->nsentcmds = 0;
+        res->offset = offset;
+    }
+
+    return res;
+}
+
+/*
+ * Called by the bitmap code for each chunk to discard
+ * May send a discard message, may just leave it queued to
+ * be sent later
+ */
+void postcopy_discard_send_chunk(MigrationState *ms, PostcopyDiscardState *pds,
+                                unsigned long pos, uint32_t bitmap)
+{
+    pds->addrlist[pds->cur_entry] = pos;
+    pds->masklist[pds->cur_entry] = bitmap;
+    pds->cur_entry++;
+    pds->nsentwords++;
+
+    if (pds->cur_entry == MAX_DISCARDS_PER_COMMAND) {
+        /* Full set, ship it! */
+        qemu_savevm_send_postcopy_ram_discard(ms->file, pds->name,
+                                              pds->cur_entry, pds->offset,
+                                              pds->addrlist, pds->masklist);
+        pds->nsentcmds++;
+        pds->cur_entry = 0;
+    }
+}
+
+/*
+ * Called at the end of each RAMBlock by the bitmap code
+ * Sends any outstanding discard messages, frees the PDS
+ */
+void postcopy_discard_send_finish(MigrationState *ms, PostcopyDiscardState *pds)
+{
+    /* Anything unsent? */
+    if (pds->cur_entry) {
+        qemu_savevm_send_postcopy_ram_discard(ms->file, pds->name,
+                                              pds->cur_entry, pds->offset,
+                                              pds->addrlist, pds->masklist);
+        pds->nsentcmds++;
+    }
+
+    trace_postcopy_discard_send_finish(pds->name, pds->nsentwords,
+                                       pds->nsentcmds);
+
+    g_free(pds);
+}
savevm.c +0 -3
index 1e8d289..2589b8c 100644
@@ -1282,15 +1282,12 @@ static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
              * we know there must be at least 1 bit set due to the loop entry
              * If there is no 0 firstzero will be 32
              */
-            /* TODO - ram_discard_range gets added in a later patch
             int ret = ram_discard_range(mis, ramid,
                                 startaddr + firstset - first_bit_offset,
                                 startaddr + (firstzero - 1) - first_bit_offset);
-            ret = -1;
             if (ret) {
                 return ret;
             }
-            */
 
             /* mask= .?0000000000 */
             /*         ^fz ^fs    */
trace-events +1 -0
index a555b56..f985117 100644
@@ -1217,6 +1217,7 @@ qemu_file_fclose(void) ""
 migration_bitmap_sync_start(void) ""
 migration_bitmap_sync_end(uint64_t dirty_pages) "dirty_pages %" PRIu64""
 migration_throttle(void) ""
+ram_postcopy_send_discard_bitmap(void) ""
 
 # hw/display/qxl.c
 disable qxl_interface_set_mm_time(int qid, uint32_t mm_time) "%d %d"
@@ -1478,6 +1479,9 @@ rdma_start_incoming_migration_after_rdma_listen(void) ""
 rdma_start_outgoing_migration_after_rdma_connect(void) ""
 rdma_start_outgoing_migration_after_rdma_source_init(void) ""
 
Quoted 12 lines
Quoted 6 lines
trace-events +3 -0
+# migration/postcopy-ram.c
+postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s mask words sent=%d in %d commands"
+
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
 kvm_vm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#133 lore raw

PATCH v5 28/45 postcopy: Incoming initialisation

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

---
 arch_init.c                      |  11 ++++
 include/migration/migration.h    |   3 +
 include/migration/postcopy-ram.h |  12 ++++
 migration/migration.c            |   1 +
 migration/postcopy-ram.c         | 119 ++++++++++++++++++++++++++++++++++++++-
 savevm.c                         |   4 ++
 trace-events                     |   2 +
 7 files changed, 151 insertions(+), 1 deletion(-)
arch_init.c +11 -0
index 21e7ebe..d2c4457 100644
@@ -1363,6 +1363,17 @@ void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
     }
 }
 
+/*
+ * Allocate data structures etc needed by incoming migration with postcopy-ram
+ * postcopy-ram's similarly names postcopy_ram_incoming_init does the work
+ */
+int ram_postcopy_incoming_init(MigrationIncomingState *mis)
+{
+    size_t ram_pages = last_ram_offset() >> TARGET_PAGE_BITS;
+
+    return postcopy_ram_incoming_init(mis, ram_pages);
+}
+
 static int ram_load(QEMUFile *f, void *opaque, int version_id)
 {
     int flags = 0, ret = 0;
include/migration/migration.h +3 -0
index e749f4c..d09561e 100644
@@ -84,6 +84,8 @@ struct MigrationIncomingState {
 
     PostcopyState postcopy_state;
 
+    /* For the kernel to send us notifications */
+    int            userfault_fd;
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
     PostcopyPMI    postcopy_pmi;
@@ -206,6 +208,7 @@ int ram_postcopy_send_discard_bitmap(MigrationState *ms);
 /* For incoming postcopy discard */
 int ram_discard_range(MigrationIncomingState *mis, const char *block_name,
                       uint64_t start, uint64_t end);
+int ram_postcopy_incoming_init(MigrationIncomingState *mis);
 
 /**
  * @migrate_add_blocker - prevent migration from proceeding
include/migration/postcopy-ram.h +12 -0
index 1fec1c1..305c26b 100644
@@ -19,6 +19,18 @@
 bool postcopy_ram_supported_by_host(void);
 
 /*
+ * Initialise postcopy-ram, setting the RAM to a state where we can go into
+ * postcopy later; must be called prior to any precopy.
+ * called from arch_init's similarly named ram_postcopy_incoming_init
+ */
+int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages);
+
+/*
+ * At the end of a migration where postcopy_ram_incoming_init was called.
+ */
+int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis);
+
+/*
  * In 'advise' mode record that a page has been received.
  */
 void postcopy_hook_early_receive(MigrationIncomingState *mis,
migration/migration.c +1 -0
index 850fe1a..b1ad7b1 100644
@@ -88,6 +88,7 @@ MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
 
 void migration_incoming_state_destroy(void)
 {
+    postcopy_pmi_destroy(mis_current);
     loadvm_free_handlers(mis_current);
     g_free(mis_current);
     mis_current = NULL;
migration/postcopy-ram.c +118 -1

137 lines not on this page · raw message

savevm.c +4 -0
index 2589b8c..6857660 100644
@@ -1186,6 +1186,10 @@ static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
         return -1;
     }
 
+    if (ram_postcopy_incoming_init(mis)) {
+        return -1;
+    }
+
     postcopy_state_set(mis, POSTCOPY_INCOMING_ADVISE);
 
     return 0;
trace-events +2 -0
index f985117..59dea4c 100644
@@ -1481,6 +1481,8 @@ rdma_start_outgoing_migration_after_rdma_source_init(void) ""
 
 # migration/postcopy-ram.c
 postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s mask words sent=%d in %d commands"
+postcopy_cleanup_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
+postcopy_init_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 1 line
2.1.0
Reviewed-by on v5 28/45
#134 lore raw

Re: [Qemu-devel] [PATCH v5 28/45] postcopy: Incoming initialisation

Quoted 3 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Looks ok, apart from a misspelled comment:

[snip]

migration/postcopy-ram.c int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start, · line 418

Quoted 13 lines
migration/postcopy-ram.c +13 -0
+    /*
+     * We need the whole of RAM to be truly empty for postcopy, so things
+     * like ROMs and any data tables built during init must be zero'd
+     * - we're going to get the copy from the source anyway.
+     * (Precopy will just overwrite this data, so doesn't need the discard)
+     */
+    if (postcopy_ram_discard_range(mis, host_addr, (host_addr + length - 1))) {
+        return -1;
+    }
+
+    /*
+     * We also need the area to be normal 4k pages, not huge pages
+     * (otherwise we can't be sure we can atopically place the

s/atopically/atomically/

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#135 lore raw

Re: [Qemu-devel] [PATCH v5 28/45] postcopy: Incoming initialisation

Quoted 24 lines · * David Gibson ([email protected]) wrote:
Quoted 3 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Looks ok, apart from a misspelled comment:

[snip]

migration/postcopy-ram.c int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start, · line 418

Quoted 13 lines
migration/postcopy-ram.c +13 -0
+    /*
+     * We need the whole of RAM to be truly empty for postcopy, so things
+     * like ROMs and any data tables built during init must be zero'd
+     * - we're going to get the copy from the source anyway.
+     * (Precopy will just overwrite this data, so doesn't need the discard)
+     */
+    if (postcopy_ram_discard_range(mis, host_addr, (host_addr + length - 1))) {
+        return -1;
+    }
+
+    /*
+     * We also need the area to be normal 4k pages, not huge pages
+     * (otherwise we can't be sure we can atopically place the
Quoted 1 line

s/atopically/atomically/

Thanks!

Dave

Quoted 7 lines
Signature · 5 lines
-- 
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#136 lore raw

PATCH v5 29/45 postcopy: ram_enable_notify to switch on userfault

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Mark the area of RAM as 'userfault'
Start up a fault-thread to handle any userfaults we might receive from it (to be filled in later)

---
 include/migration/migration.h    |  3 ++
 include/migration/postcopy-ram.h |  6 ++++
 migration/postcopy-ram.c         | 69 +++++++++++++++++++++++++++++++++++++++-
 savevm.c                         |  9 ++++++
 4 files changed, 86 insertions(+), 1 deletion(-)
include/migration/migration.h +3 -0
index d09561e..821d561 100644
@@ -84,6 +84,9 @@ struct MigrationIncomingState {
 
     PostcopyState postcopy_state;
 
+    QemuThread     fault_thread;
+    QemuSemaphore  fault_thread_sem;
+
     /* For the kernel to send us notifications */
     int            userfault_fd;
     QEMUFile *return_path;
include/migration/postcopy-ram.h +6 -0
index 305c26b..fbb2a93 100644
@@ -19,6 +19,12 @@
 bool postcopy_ram_supported_by_host(void);
 
 /*
+ * Make all of RAM sensitive to accesses to areas that haven't yet been written
+ * and wire up anything necessary to deal with it.
+ */
+int postcopy_ram_enable_notify(MigrationIncomingState *mis);
+
+/*
  * Initialise postcopy-ram, setting the RAM to a state where we can go into
  * postcopy later; must be called prior to any precopy.
  * called from arch_init's similarly named ram_postcopy_incoming_init
migration/postcopy-ram.c +68 -1

83 lines not on this page · raw message

savevm.c +9 -0
index 6857660..014ba08 100644
@@ -1317,6 +1317,15 @@ static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
         return -1;
     }
 
+    /*
+     * Sensitise RAM - can now generate requests for blocks that don't exist
+     * However, at this point the CPU shouldn't be running, and the IO
+     * shouldn't be doing anything yet so don't actually expect requests
+     */
+    if (postcopy_ram_enable_notify(mis)) {
+        return -1;
+    }
+
     /* TODO start up the postcopy listening thread */
     return 0;
 }
Signature · 1 line
2.1.0
Reviewed-by on v5 29/45
#137 lore raw

Re: [Qemu-devel] [PATCH v5 29/45] postcopy: ram_enable_notify to switch on userfault

Quoted 7 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Mark the area of RAM as 'userfault'
Start up a fault-thread to handle any userfaults we might receive from it (to be filled in later)

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#138 lore raw

PATCH v5 30/45 Postcopy: Postcopy startup in migration thread

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Rework the migration thread to setup and start postcopy.

---
 include/migration/migration.h |   3 +
 migration/migration.c         | 161 ++++++++++++++++++++++++++++++++++++++++--
 trace-events                  |   4 ++
 3 files changed, 164 insertions(+), 4 deletions(-)
include/migration/migration.h +3 -0
index 821d561..2c607e7 100644
@@ -131,6 +131,9 @@ struct MigrationState
     /* Flag set once the migration has been asked to enter postcopy */
     bool start_postcopy;
 
+    /* Flag set once the migration thread is running (and needs joining) */
+    bool started_migration_thread;
+
     /* bitmap of pages that have been sent at least once
      * only maintained and used in postcopy at the moment
      * where it's used to send the dirtymap at the start
migration/migration.c +157 -4

227 lines not on this page · raw message

trace-events +4 -0
index 59dea4c..ed8bbe2 100644
@@ -1404,9 +1404,13 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
+migration_thread_after_loop(void) ""
+migration_thread_file_err(void) ""
 migration_thread_setup_complete(void) ""
 open_outgoing_return_path(void) ""
 open_outgoing_return_path_continue(void) ""
+postcopy_start(void) ""
+postcopy_start_set_run(void) ""
 source_return_path_thread_bad_end(void) ""
 source_return_path_bad_header_com(void) ""
 source_return_path_thread_end(void) ""
Signature · 1 line
2.1.0
#139 lore raw

Re: [Qemu-devel] [PATCH v5 30/45] Postcopy: Postcopy startup in migration thread

Quoted 59 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Rework the migration thread to setup and start postcopy.

---
 include/migration/migration.h |   3 +
 migration/migration.c         | 161 ++++++++++++++++++++++++++++++++++++++++--
 trace-events                  |   4 ++
 3 files changed, 164 insertions(+), 4 deletions(-)
include/migration/migration.h +3 -0
index 821d561..2c607e7 100644
@@ -131,6 +131,9 @@ struct MigrationState
     /* Flag set once the migration has been asked to enter postcopy */
     bool start_postcopy;
 
+    /* Flag set once the migration thread is running (and needs joining) */
+    bool started_migration_thread;
+
     /* bitmap of pages that have been sent at least once
      * only maintained and used in postcopy at the moment
      * where it's used to send the dirtymap at the start
migration/migration.c +10 -2
index b1ad7b1..6bf9c8d 100644
@@ -468,7 +468,10 @@ static void migrate_fd_cleanup(void *opaque)
     if (s->file) {
         trace_migrate_fd_cleanup();
         qemu_mutex_unlock_iothread();
-        qemu_thread_join(&s->thread);
+        if (s->started_migration_thread) {
+            qemu_thread_join(&s->thread);
+            s->started_migration_thread = false;
+        }
         qemu_mutex_lock_iothread();
 
         qemu_fclose(s->file);
@@ -874,7 +877,6 @@ out:
     return NULL;
 }
 
-__attribute__ (( unused )) /* Until later in patch series */
 static int open_outgoing_return_path(MigrationState *ms)
 {
 
@@ -911,23 +913,141 @@ static void await_outgoing_return_path_close(MigrationState *ms)
 }
 
 /*
+ * Switch from normal iteration to postcopy
+ * Returns non-0 on error
+ */
+static int postcopy_start(MigrationState *ms, bool *old_vm_running)
+{
+    int ret;

migration/migration.c static void await_outgoing_return_path_close(MigrationState *ms) · line 931

Quoted 10 lines
migration/migration.c +10 -0
+    const QEMUSizedBuffer *qsb;
+    int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
+    migrate_set_state(ms, MIG_STATE_ACTIVE, MIG_STATE_POSTCOPY_ACTIVE);
+
+    trace_postcopy_start();
+    qemu_mutex_lock_iothread();
+    trace_postcopy_start_set_run();
+
+    qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
+    *old_vm_running = runstate_is_running();

I think that needs some explanation. Why are you doing a wakeup on the source host?

Quoted 126 lines
migration/migration.c +102 -0
+    ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
+
+    if (ret < 0) {
+        goto fail;
+    }
+
+    /*
+     * in Finish migrate and with the io-lock held everything should
+     * be quiet, but we've potentially still got dirty pages and we
+     * need to tell the destination to throw any pages it's already received
+     * that are dirty
+     */
+    if (ram_postcopy_send_discard_bitmap(ms)) {
+        error_report("postcopy send discard bitmap failed");
+        goto fail;
+    }
+
+    /*
+     * send rest of state - note things that are doing postcopy
+     * will notice we're in MIG_STATE_POSTCOPY_ACTIVE and not actually
+     * wrap their state up here
+     */
+    qemu_file_set_rate_limit(ms->file, INT64_MAX);
+    /* Ping just for debugging, helps line traces up */
+    qemu_savevm_send_ping(ms->file, 2);
+
+    /*
+     * We need to leave the fd free for page transfers during the
+     * loading of the device state, so wrap all the remaining
+     * commands and state into a package that gets sent in one go
+     */
+    QEMUFile *fb = qemu_bufopen("w", NULL);
+    if (!fb) {
+        error_report("Failed to create buffered file");
+        goto fail;
+    }
+
+    qemu_savevm_state_complete(fb);
+    qemu_savevm_send_ping(fb, 3);
+
+    qemu_savevm_send_postcopy_run(fb);
+
+    /* <><> end of stuff going into the package */
+    qsb = qemu_buf_get(fb);
+
+    /* Now send that blob */
+    if (qsb_get_length(qsb) > MAX_VM_CMD_PACKAGED_SIZE) {
+        error_report("postcopy_start: Unreasonably large packaged state: %lu",
+                     (unsigned long)(qsb_get_length(qsb)));
+        goto fail_closefb;
+    }
+    qemu_savevm_send_packaged(ms->file, qsb);
+    qemu_fclose(fb);
+    ms->downtime =  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
+
+    qemu_mutex_unlock_iothread();
+
+    /*
+     * Although this ping is just for debug, it could potentially be
+     * used for getting a better measurement of downtime at the source.
+     */
+    qemu_savevm_send_ping(ms->file, 4);
+
+    ret = qemu_file_get_error(ms->file);
+    if (ret) {
+        error_report("postcopy_start: Migration stream errored");
+        migrate_set_state(ms, MIG_STATE_POSTCOPY_ACTIVE, MIG_STATE_ERROR);
+    }
+
+    return ret;
+
+fail_closefb:
+    qemu_fclose(fb);
+fail:
+    migrate_set_state(ms, MIG_STATE_POSTCOPY_ACTIVE, MIG_STATE_ERROR);
+    qemu_mutex_unlock_iothread();
+    return -1;
+}
+
+/*
  * Master migration thread on the source VM.
  * It drives the migration and pumps the data down the outgoing channel.
  */
 static void *migration_thread(void *opaque)
 {
     MigrationState *s = opaque;
+    /* Used by the bandwidth calcs, updated later */
     int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
     int64_t initial_bytes = 0;
     int64_t max_size = 0;
     int64_t start_time = initial_time;
     bool old_vm_running = false;
+    bool entered_postcopy = false;
+    /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
+    enum MigrationPhase current_active_type = MIG_STATE_ACTIVE;
 
     qemu_savevm_state_header(s->file);
+
+    if (migrate_postcopy_ram()) {
+        /* Now tell the dest that it should open its end so it can reply */
+        qemu_savevm_send_open_return_path(s->file);
+
+        /* And do a ping that will make stuff easier to debug */
+        qemu_savevm_send_ping(s->file, 1);
+
+        /*
+         * Tell the destination that we *might* want to do postcopy later;
+         * if the other end can't do postcopy it should fail now, nice and
+         * early.
+         */
+        qemu_savevm_send_postcopy_advise(s->file);
+    }
+
     qemu_savevm_state_begin(s->file, &s->params);
 
     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
+    current_active_type = MIG_STATE_ACTIVE;
     migrate_set_state(s, MIG_STATE_SETUP, MIG_STATE_ACTIVE);
 
     trace_migration_thread_setup_complete();
@@ -946,6 +1066,22 @@ static void *migration_thread(void *opaque)
             trace_migrate_pending(pending_size, max_size,
                                   pend_post, pend_nonpost);
             if (pending_size && pending_size >= max_size) {
+                /* Still a significant amount to transfer */

migration/migration.c static void *migration_thread(void *opaque) · line 1079

Quoted 10 lines
migration/migration.c +10 -0
+
+                current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
+                if (migrate_postcopy_ram() &&
+                    s->state != MIG_STATE_POSTCOPY_ACTIVE &&
+                    pend_nonpost <= max_size &&
+                    atomic_read(&s->start_postcopy)) {
+
+                    if (!postcopy_start(s, &old_vm_running)) {
+                        current_active_type = MIG_STATE_POSTCOPY_ACTIVE;
+                        entered_postcopy = true;

Do you need entered_postcopy, or could you just use the existing MIG_STATE variable?

Quoted 75 lines
migration/migration.c +24 -2
+                    }
+
+                    continue;
+                }
+                /* Just another iteration step */
                 qemu_savevm_state_iterate(s->file);
             } else {
                 int ret;
@@ -975,7 +1111,8 @@ static void *migration_thread(void *opaque)
         }
 
         if (qemu_file_get_error(s->file)) {
-            migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
+            migrate_set_state(s, current_active_type, MIG_STATE_ERROR);
+            trace_migration_thread_file_err();
             break;
         }
         current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
@@ -1006,12 +1143,15 @@ static void *migration_thread(void *opaque)
         }
     }
 
+    trace_migration_thread_after_loop();
     qemu_mutex_lock_iothread();
     if (s->state == MIG_STATE_COMPLETED) {
         int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
         uint64_t transferred_bytes = qemu_ftell(s->file);
         s->total_time = end_time - s->total_time;
-        s->downtime = end_time - start_time;
+        if (!entered_postcopy) {
+            s->downtime = end_time - start_time;
+        }
         if (s->total_time) {
             s->mbps = (((double) transferred_bytes * 8.0) /
                        ((double) s->total_time)) / 1000;
@@ -1043,8 +1183,21 @@ void migrate_fd_connect(MigrationState *s)
     /* Notify before starting migration thread */
     notifier_list_notify(&migration_state_notifiers, s);
 
+    /* Open the return path; currently for postcopy but other things might
+     * also want it.
+     */
+    if (migrate_postcopy_ram()) {
+        if (open_outgoing_return_path(s)) {
+            error_report("Unable to open return-path for postcopy");
+            migrate_set_state(s, MIG_STATE_SETUP, MIG_STATE_ERROR);
+            migrate_fd_cleanup(s);
+            return;
+        }
+    }
+
     qemu_thread_create(&s->thread, "migration", migration_thread, s,
                        QEMU_THREAD_JOINABLE);
+    s->started_migration_thread = true;
 }
 
 PostcopyState  postcopy_state_get(MigrationIncomingState *mis)
trace-events +4 -0
index 59dea4c..ed8bbe2 100644
@@ -1404,9 +1404,13 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
+migration_thread_after_loop(void) ""
+migration_thread_file_err(void) ""
 migration_thread_setup_complete(void) ""
 open_outgoing_return_path(void) ""
 open_outgoing_return_path_continue(void) ""
+postcopy_start(void) ""
+postcopy_start_set_run(void) ""
 source_return_path_thread_bad_end(void) ""
 source_return_path_bad_header_com(void) ""
 source_return_path_thread_end(void) ""
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#140 lore raw

Re: [Qemu-devel] [PATCH v5 30/45] Postcopy: Postcopy startup in migration thread

Quoted 65 lines · * David Gibson ([email protected]) wrote:
Quoted 64 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Rework the migration thread to setup and start postcopy.

---
 include/migration/migration.h |   3 +
 migration/migration.c         | 161 ++++++++++++++++++++++++++++++++++++++++--
 trace-events                  |   4 ++
 3 files changed, 164 insertions(+), 4 deletions(-)
include/migration/migration.h +3 -0
index 821d561..2c607e7 100644
@@ -131,6 +131,9 @@ struct MigrationState
     /* Flag set once the migration has been asked to enter postcopy */
     bool start_postcopy;
 
+    /* Flag set once the migration thread is running (and needs joining) */
+    bool started_migration_thread;
+
     /* bitmap of pages that have been sent at least once
      * only maintained and used in postcopy at the moment
      * where it's used to send the dirtymap at the start
migration/migration.c +15 -2
index b1ad7b1..6bf9c8d 100644
@@ -468,7 +468,10 @@ static void migrate_fd_cleanup(void *opaque)
     if (s->file) {
         trace_migrate_fd_cleanup();
         qemu_mutex_unlock_iothread();
-        qemu_thread_join(&s->thread);
+        if (s->started_migration_thread) {
+            qemu_thread_join(&s->thread);
+            s->started_migration_thread = false;
+        }
         qemu_mutex_lock_iothread();
 
         qemu_fclose(s->file);
@@ -874,7 +877,6 @@ out:
     return NULL;
 }
 
-__attribute__ (( unused )) /* Until later in patch series */
 static int open_outgoing_return_path(MigrationState *ms)
 {
 
@@ -911,23 +913,141 @@ static void await_outgoing_return_path_close(MigrationState *ms)
 }
 
 /*
+ * Switch from normal iteration to postcopy
+ * Returns non-0 on error
+ */
+static int postcopy_start(MigrationState *ms, bool *old_vm_running)
+{
+    int ret;
+    const QEMUSizedBuffer *qsb;
+    int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
+    migrate_set_state(ms, MIG_STATE_ACTIVE, MIG_STATE_POSTCOPY_ACTIVE);
+
+    trace_postcopy_start();
Quoted 8 lines

migration/migration.c static void await_outgoing_return_path_close(MigrationState *ms) · line 931

Quoted 5 lines
migration/migration.c +5 -0
+    qemu_mutex_lock_iothread();
+    trace_postcopy_start_set_run();
+
+    qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
+    *old_vm_running = runstate_is_running();

I think that needs some explanation. Why are you doing a wakeup on the source host?

This matches the existing code in migration_thread for the end of precopy; Paolo's explanation of what it does is here:
https://lists.gnu.org/archive/html/qemu-devel/2014-08/msg04880.html

Quoted 131 lines
Quoted 131 lines
migration/migration.c +107 -0
+    ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
+
+    if (ret < 0) {
+        goto fail;
+    }
+
+    /*
+     * in Finish migrate and with the io-lock held everything should
+     * be quiet, but we've potentially still got dirty pages and we
+     * need to tell the destination to throw any pages it's already received
+     * that are dirty
+     */
+    if (ram_postcopy_send_discard_bitmap(ms)) {
+        error_report("postcopy send discard bitmap failed");
+        goto fail;
+    }
+
+    /*
+     * send rest of state - note things that are doing postcopy
+     * will notice we're in MIG_STATE_POSTCOPY_ACTIVE and not actually
+     * wrap their state up here
+     */
+    qemu_file_set_rate_limit(ms->file, INT64_MAX);
+    /* Ping just for debugging, helps line traces up */
+    qemu_savevm_send_ping(ms->file, 2);
+
+    /*
+     * We need to leave the fd free for page transfers during the
+     * loading of the device state, so wrap all the remaining
+     * commands and state into a package that gets sent in one go
+     */
+    QEMUFile *fb = qemu_bufopen("w", NULL);
+    if (!fb) {
+        error_report("Failed to create buffered file");
+        goto fail;
+    }
+
+    qemu_savevm_state_complete(fb);
+    qemu_savevm_send_ping(fb, 3);
+
+    qemu_savevm_send_postcopy_run(fb);
+
+    /* <><> end of stuff going into the package */
+    qsb = qemu_buf_get(fb);
+
+    /* Now send that blob */
+    if (qsb_get_length(qsb) > MAX_VM_CMD_PACKAGED_SIZE) {
+        error_report("postcopy_start: Unreasonably large packaged state: %lu",
+                     (unsigned long)(qsb_get_length(qsb)));
+        goto fail_closefb;
+    }
+    qemu_savevm_send_packaged(ms->file, qsb);
+    qemu_fclose(fb);
+    ms->downtime =  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
+
+    qemu_mutex_unlock_iothread();
+
+    /*
+     * Although this ping is just for debug, it could potentially be
+     * used for getting a better measurement of downtime at the source.
+     */
+    qemu_savevm_send_ping(ms->file, 4);
+
+    ret = qemu_file_get_error(ms->file);
+    if (ret) {
+        error_report("postcopy_start: Migration stream errored");
+        migrate_set_state(ms, MIG_STATE_POSTCOPY_ACTIVE, MIG_STATE_ERROR);
+    }
+
+    return ret;
+
+fail_closefb:
+    qemu_fclose(fb);
+fail:
+    migrate_set_state(ms, MIG_STATE_POSTCOPY_ACTIVE, MIG_STATE_ERROR);
+    qemu_mutex_unlock_iothread();
+    return -1;
+}
+
+/*
  * Master migration thread on the source VM.
  * It drives the migration and pumps the data down the outgoing channel.
  */
 static void *migration_thread(void *opaque)
 {
     MigrationState *s = opaque;
+    /* Used by the bandwidth calcs, updated later */
     int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
     int64_t initial_bytes = 0;
     int64_t max_size = 0;
     int64_t start_time = initial_time;
     bool old_vm_running = false;
+    bool entered_postcopy = false;
+    /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
+    enum MigrationPhase current_active_type = MIG_STATE_ACTIVE;
 
     qemu_savevm_state_header(s->file);
+
+    if (migrate_postcopy_ram()) {
+        /* Now tell the dest that it should open its end so it can reply */
+        qemu_savevm_send_open_return_path(s->file);
+
+        /* And do a ping that will make stuff easier to debug */
+        qemu_savevm_send_ping(s->file, 1);
+
+        /*
+         * Tell the destination that we *might* want to do postcopy later;
+         * if the other end can't do postcopy it should fail now, nice and
+         * early.
+         */
+        qemu_savevm_send_postcopy_advise(s->file);
+    }
+
     qemu_savevm_state_begin(s->file, &s->params);
 
     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
+    current_active_type = MIG_STATE_ACTIVE;
     migrate_set_state(s, MIG_STATE_SETUP, MIG_STATE_ACTIVE);
 
     trace_migration_thread_setup_complete();
@@ -946,6 +1066,22 @@ static void *migration_thread(void *opaque)
             trace_migrate_pending(pending_size, max_size,
                                   pend_post, pend_nonpost);
             if (pending_size && pending_size >= max_size) {
+                /* Still a significant amount to transfer */
+
+                current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
+                if (migrate_postcopy_ram() &&
+                    s->state != MIG_STATE_POSTCOPY_ACTIVE &&
+                    pend_nonpost <= max_size &&
Quoted 8 lines

migration/migration.c static void *migration_thread(void *opaque) · line 1079

Quoted 5 lines
migration/migration.c +5 -0
+                    atomic_read(&s->start_postcopy)) {
+
+                    if (!postcopy_start(s, &old_vm_running)) {
+                        current_active_type = MIG_STATE_POSTCOPY_ACTIVE;
+                        entered_postcopy = true;

Do you need entered_postcopy, or could you just use the existing MIG_STATE variable?

I need the separate flag, because this is used at the end of migration (when the existing state is MIGRATION_STATUS_COMPLETED) to know that there has been a postcopy stage, and is used to stop the recalculation of the 'downtime' which was previously incorrect. See below.

Quoted 22 lines
Quoted 22 lines
migration/migration.c +7 -1
+                    }
+
+                    continue;
+                }
+                /* Just another iteration step */
                 qemu_savevm_state_iterate(s->file);
             } else {
                 int ret;
@@ -975,7 +1111,8 @@ static void *migration_thread(void *opaque)
         }
 
         if (qemu_file_get_error(s->file)) {
-            migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
+            migrate_set_state(s, current_active_type, MIG_STATE_ERROR);
+            trace_migration_thread_file_err();
             break;
         }
         current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
@@ -1006,12 +1143,15 @@ static void *migration_thread(void *opaque)
         }
     }
 
Quoted 10 lines

migration/migration.c static void *migration_thread(void *opaque) · line 1154

Quoted 10 lines
migration/migration.c +4 -1
+    trace_migration_thread_after_loop();
     qemu_mutex_lock_iothread();
     if (s->state == MIG_STATE_COMPLETED) {
         int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
         uint64_t transferred_bytes = qemu_ftell(s->file);
         s->total_time = end_time - s->total_time;
-        s->downtime = end_time - start_time;
+        if (!entered_postcopy) {
+            s->downtime = end_time - start_time;
+        }

Here's the use of entered_postcopy, and you see that the s->state is always MIG_STATE_COMPLETED here.

Dave

Quoted 35 lines
Quoted 35 lines
migration/migration.c +13 -0
         if (s->total_time) {
             s->mbps = (((double) transferred_bytes * 8.0) /
                        ((double) s->total_time)) / 1000;
@@ -1043,8 +1183,21 @@ void migrate_fd_connect(MigrationState *s)
     /* Notify before starting migration thread */
     notifier_list_notify(&migration_state_notifiers, s);
 
+    /* Open the return path; currently for postcopy but other things might
+     * also want it.
+     */
+    if (migrate_postcopy_ram()) {
+        if (open_outgoing_return_path(s)) {
+            error_report("Unable to open return-path for postcopy");
+            migrate_set_state(s, MIG_STATE_SETUP, MIG_STATE_ERROR);
+            migrate_fd_cleanup(s);
+            return;
+        }
+    }
+
     qemu_thread_create(&s->thread, "migration", migration_thread, s,
                        QEMU_THREAD_JOINABLE);
+    s->started_migration_thread = true;
 }
 
 PostcopyState  postcopy_state_get(MigrationIncomingState *mis)
trace-events +2 -0
index 59dea4c..ed8bbe2 100644
@@ -1404,9 +1404,13 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
+migration_thread_after_loop(void) ""
+migration_thread_file_err(void) ""
Quoted 14 lines
Quoted 8 lines
trace-events +2 -0
 migration_thread_setup_complete(void) ""
 open_outgoing_return_path(void) ""
 open_outgoing_return_path_continue(void) ""
+postcopy_start(void) ""
+postcopy_start_set_run(void) ""
 source_return_path_thread_bad_end(void) ""
 source_return_path_bad_header_com(void) ""
 source_return_path_thread_end(void) ""
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#141 lore raw

Re: [Qemu-devel] [PATCH v5 30/45] Postcopy: Postcopy startup in migration thread

Quoted 8 lines · Dr. David Alan Gilbert
Quoted 5 lines
Quoted 5 lines
Quoted 2 lines

migration/migration.c static void await_outgoing_return_path_close(MigrationState *ms) · line 931

Quoted 2 lines
migration/migration.c +2 -0
+    qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
+    *old_vm_running = runstate_is_running();

I think that needs some explanation. Why are you doing a wakeup on the source host?

This matches the existing code in migration_thread for the end of precopy; Paolo's explanation of what it does is here:
https://lists.gnu.org/archive/html/qemu-devel/2014-08/msg04880.html

The more I look at it, the more I'm convinced it's working by chance or not working at all.

Here we probably need to do only the notifier_list_notify + qapi_event_send_wakeup.

Paolo

#142 lore raw

Re: [Qemu-devel] [PATCH v5 30/45] Postcopy: Postcopy startup in migration thread

Quoted 6 lines · * Paolo Bonzini ([email protected]) wrote:
Quoted 3 lines · Dr. David Alan Gilbert
Quoted 3 lines
Quoted 3 lines
Quoted 2 lines
Quoted 2 lines
migration/migration.c +2 -0
+    qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
+    *old_vm_running = runstate_is_running();
Quoted 8 lines
Quoted 5 lines
Quoted 2 lines
Quoted 2 lines

I think that needs some explanation. Why are you doing a wakeup on the source host?

This matches the existing code in migration_thread for the end of precopy; Paolo's explanation of what it does is here:
https://lists.gnu.org/archive/html/qemu-devel/2014-08/msg04880.html

The more I look at it, the more I'm convinced it's working by chance or not working at all.

Do you mean in general or in the postcopy case?

Quoted 2 lines

Here we probably need to do only the notifier_list_notify + qapi_event_send_wakeup.

Do you mean a :
wakeup_reason = QEMU_WAKEUP_REASON_OTHER; notifier_list_notify(&wakeup_notifiers, &wakeup_reason); wakeup_reason = QEMU_WAKEUP_REASON_NONE; qapi_event_send_wakeup(&error);

which I guess would need wrapping up in vl.c

(It's not really clear to me what this stuff does even with your previous explanation; if it's to do with migrating something suspended-to-ram I guess a postcopy is possible but it doesn't seem that sensible to use postcopy for a machine with a CPU that isn't running).

Dave

Quoted 2 lines

Paolo

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#143 lore raw

Re: [Qemu-devel] [PATCH v5 30/45] Postcopy: Postcopy startup in migration thread

Quoted 5 lines · Dr. David Alan Gilbert
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

+ qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);

Quoted 4 lines
Quoted 4 lines
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

+ *old_vm_running = runstate_is_running();

I think that needs some explanation. Why are you doing a wakeup on the source host?

Quoted 7 lines
Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Quoted 3 lines

This matches the existing code in migration_thread for the end of precopy; Paolo's explanation of what it does is here:
https://lists.gnu.org/archive/html/qemu-devel/2014-08/msg04880.html

The more I look at it, the more I'm convinced it's working by chance or not working at all.

Do you mean in general or in the postcopy case?

In general.

Quoted 10 lines
Quoted 2 lines

Here we probably need to do only the notifier_list_notify + qapi_event_send_wakeup.

Do you mean a :

   wakeup_reason = QEMU_WAKEUP_REASON_OTHER;
   notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
   wakeup_reason = QEMU_WAKEUP_REASON_NONE;
   qapi_event_send_wakeup(&error);

which I guess would need wrapping up in vl.c

Yes.

Quoted 5 lines

(It's not really clear to me what this stuff does even with your previous explanation; if it's to do with migrating something suspended-to-ram I guess a postcopy is possible but it doesn't seem that sensible to use postcopy for a machine with a CPU that isn't running).

Yes, but management does not know in advance that the machine will suspend to RAM. It's basically a race.

Paolo

#144 lore raw

Re: [Qemu-devel] [PATCH v5 30/45] Postcopy: Postcopy startup in migration thread

Quoted 12 lines · * Paolo Bonzini ([email protected]) wrote:
Quoted 9 lines · Dr. David Alan Gilbert
Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
Quoted 8 lines
Quoted 5 lines
Quoted 5 lines

+ qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);

Quoted 4 lines
Quoted 4 lines
Quoted 1 line
Quoted 1 line
Quoted 1 line

+ *old_vm_running = runstate_is_running();

I think that needs some explanation. Why are you doing a wakeup on the source host?

This matches the existing code in migration_thread for the end of precopy; Paolo's explanation of what it does is here:
https://lists.gnu.org/archive/html/qemu-devel/2014-08/msg04880.html

Quoted 5 lines
Quoted 3 lines
Quoted 2 lines
Quoted 2 lines

The more I look at it, the more I'm convinced it's working by chance or not working at all.

Do you mean in general or in the postcopy case?

In general.

OK, then lets take this off this thread and fix it generally and just make sure postcopy is consistent with whatever that change is.

Quoted 13 lines
Quoted 10 lines
Quoted 2 lines

Here we probably need to do only the notifier_list_notify + qapi_event_send_wakeup.

Do you mean a :

   wakeup_reason = QEMU_WAKEUP_REASON_OTHER;
   notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
   wakeup_reason = QEMU_WAKEUP_REASON_NONE;
   qapi_event_send_wakeup(&error);

which I guess would need wrapping up in vl.c

Yes.

Quoted 8 lines
Quoted 5 lines

(It's not really clear to me what this stuff does even with your previous explanation; if it's to do with migrating something suspended-to-ram I guess a postcopy is possible but it doesn't seem that sensible to use postcopy for a machine with a CPU that isn't running).

Yes, but management does not know in advance that the machine will suspend to RAM. It's basically a race.

OK, reasonable.

Dave

Quoted 2 lines

Paolo

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#145 lore raw

PATCH v5 31/45 Postcopy end in migration_thread

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

The end of migration in postcopy is a bit different since some of the things normally done at the end of migration have already been done on the transition to postcopy.

The end of migration code is getting a bit complciated now, so move out into its own function.

---
 migration/migration.c | 85 +++++++++++++++++++++++++++++++++++++--------------
 trace-events          |  6 ++++
 2 files changed, 68 insertions(+), 23 deletions(-)
migration/migration.c +62 -23
index 6bf9c8d..bd066f6 100644
@@ -894,7 +894,6 @@ static int open_outgoing_return_path(MigrationState *ms)
     return 0;
 }
 
-__attribute__ (( unused )) /* Until later in patch series */
 static void await_outgoing_return_path_close(MigrationState *ms)
 {
     /*
@@ -1010,6 +1009,64 @@ fail:
 }
 
 /*
+ * Used by migration_thread when there's not much left pending.
+ * The caller 'breaks' the loop when this returns.
+ */
+static void migration_thread_end_of_iteration(MigrationState *s,
+                                              int current_active_state,
+                                              bool *old_vm_running,
+                                              int64_t *start_time)
+{
+    int ret;
+    if (s->state == MIG_STATE_ACTIVE) {
+        qemu_mutex_lock_iothread();
+        *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
+        qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
+        *old_vm_running = runstate_is_running();
+
+        ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
+        if (ret >= 0) {
+            qemu_file_set_rate_limit(s->file, INT64_MAX);
+            qemu_savevm_state_complete(s->file);
+        }
+        qemu_mutex_unlock_iothread();
+
+        if (ret < 0) {
+            goto fail;
+        }
+    } else if (s->state == MIG_STATE_POSTCOPY_ACTIVE) {
+        trace_migration_thread_end_of_iteration_postcopy_end();
+
+        qemu_savevm_state_postcopy_complete(s->file);
+        trace_migration_thread_end_of_iteration_postcopy_end_after_complete();
+    }
+
+    /*
+     * If rp was opened we must clean up the thread before
+     * cleaning everything else up (since if there are no failures
+     * it will wait for the destination to send it's status in
+     * a SHUT command).
+     * Postcopy opens rp if enabled (even if it's not avtivated)
+     */
+    if (migrate_postcopy_ram()) {
+        trace_migration_thread_end_of_iteration_postcopy_end_before_rp();
+        await_outgoing_return_path_close(s);
+        trace_migration_thread_end_of_iteration_postcopy_end_after_rp();
+    }
+
+    if (qemu_file_get_error(s->file)) {
+        trace_migration_thread_end_of_iteration_file_err();
+        goto fail;
+    }
+
+    migrate_set_state(s, current_active_state, MIG_STATE_COMPLETED);
+    return;
+
+fail:
+    migrate_set_state(s, current_active_state, MIG_STATE_ERROR);
+}
+
+/*
  * Master migration thread on the source VM.
  * It drives the migration and pumps the data down the outgoing channel.
  */
@@ -1084,29 +1141,11 @@ static void *migration_thread(void *opaque)
                 /* Just another iteration step */
                 qemu_savevm_state_iterate(s->file);
             } else {
-                int ret;
-
-                qemu_mutex_lock_iothread();
-                start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
-                qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
-                old_vm_running = runstate_is_running();
-
-                ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
-                if (ret >= 0) {
-                    qemu_file_set_rate_limit(s->file, INT64_MAX);
-                    qemu_savevm_state_complete(s->file);
-                }
-                qemu_mutex_unlock_iothread();
+                trace_migration_thread_low_pending(pending_size);
 
-                if (ret < 0) {
-                    migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
-                    break;
-                }
-
-                if (!qemu_file_get_error(s->file)) {
-                    migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_COMPLETED);
-                    break;
-                }
+                migration_thread_end_of_iteration(s, current_active_type,
+                    &old_vm_running, &start_time);
+                break;
             }
         }
 
trace-events +6 -0
index ed8bbe2..bcbdef8 100644
@@ -1407,6 +1407,12 @@ migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
 migration_thread_after_loop(void) ""
 migration_thread_file_err(void) ""
 migration_thread_setup_complete(void) ""
+migration_thread_low_pending(uint64_t pending) "%" PRIu64
+migration_thread_end_of_iteration_file_err(void) ""
+migration_thread_end_of_iteration_postcopy_end(void) ""
+migration_thread_end_of_iteration_postcopy_end_after_complete(void) ""
+migration_thread_end_of_iteration_postcopy_end_before_rp(void) ""
+migration_thread_end_of_iteration_postcopy_end_after_rp(void) ""
 open_outgoing_return_path(void) ""
 open_outgoing_return_path_continue(void) ""
 postcopy_start(void) ""
Signature · 1 line
2.1.0
#146 lore raw

PATCH v5 32/45 Page request: Add MIG_RP_CMD_REQ_PAGES reverse command

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Add MIG_RP_CMD_REQ_PAGES command on Return path for the postcopy destination to request a page from the source.

---
 include/migration/migration.h |  4 +++
 migration/migration.c         | 70 +++++++++++++++++++++++++++++++++++++++++++
 trace-events                  |  1 +
 3 files changed, 75 insertions(+)
include/migration/migration.h +4 -0
index 2c607e7..2c15d63 100644
@@ -46,6 +46,8 @@ enum mig_rpcomm_cmd {
     MIG_RP_CMD_INVALID = 0,  /* Must be 0 */
     MIG_RP_CMD_SHUT,         /* sibling will not send any more RP messages */
     MIG_RP_CMD_PONG,         /* Response to a PING; data (seq: be32 ) */
+
+    MIG_RP_CMD_REQ_PAGES,    /* data (start: be64, len: be64) */
 };
 
 /* Postcopy page-map-incoming - data about each page on the inbound side */
@@ -253,6 +255,8 @@ void migrate_send_rp_shut(MigrationIncomingState *mis,
                           uint32_t value);
 void migrate_send_rp_pong(MigrationIncomingState *mis,
                           uint32_t value);
+void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char* rbname,
+                              ram_addr_t start, ram_addr_t len);
 
 void ram_control_before_iterate(QEMUFile *f, uint64_t flags);
 void ram_control_after_iterate(QEMUFile *f, uint64_t flags);
migration/migration.c +70 -0

100 lines not on this page · raw message

trace-events +1 -0
index bcbdef8..9bedee4 100644
@@ -1404,6 +1404,7 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
+migrate_handle_rp_req_pages(size_t start, size_t len) "at %zx for len %zx"
 migration_thread_after_loop(void) ""
 migration_thread_file_err(void) ""
 migration_thread_setup_complete(void) ""
Signature · 1 line
2.1.0
#147 lore raw

Re: [Qemu-devel] [PATCH v5 32/45] Page request: Add MIG_RP_CMD_REQ_PAGES reverse command

Quoted 60 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Add MIG_RP_CMD_REQ_PAGES command on Return path for the postcopy destination to request a page from the source.

---
 include/migration/migration.h |  4 +++
 migration/migration.c         | 70 +++++++++++++++++++++++++++++++++++++++++++
 trace-events                  |  1 +
 3 files changed, 75 insertions(+)
include/migration/migration.h +4 -0
index 2c607e7..2c15d63 100644
@@ -46,6 +46,8 @@ enum mig_rpcomm_cmd {
     MIG_RP_CMD_INVALID = 0,  /* Must be 0 */
     MIG_RP_CMD_SHUT,         /* sibling will not send any more RP messages */
     MIG_RP_CMD_PONG,         /* Response to a PING; data (seq: be32 ) */
+
+    MIG_RP_CMD_REQ_PAGES,    /* data (start: be64, len: be64) */
 };
 
 /* Postcopy page-map-incoming - data about each page on the inbound side */
@@ -253,6 +255,8 @@ void migrate_send_rp_shut(MigrationIncomingState *mis,
                           uint32_t value);
 void migrate_send_rp_pong(MigrationIncomingState *mis,
                           uint32_t value);
+void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char* rbname,
+                              ram_addr_t start, ram_addr_t len);
 
 void ram_control_before_iterate(QEMUFile *f, uint64_t flags);
 void ram_control_after_iterate(QEMUFile *f, uint64_t flags);
migration/migration.c +18 -0
index bd066f6..2e9d0dd 100644
@@ -138,6 +138,36 @@ void migrate_send_rp_pong(MigrationIncomingState *mis,
     migrate_send_rp_message(mis, MIG_RP_CMD_PONG, 4, (uint8_t *)&buf);
 }
 
+/* Request a range of pages from the source VM at the given
+ * start address.
+ *   rbname: Name of the RAMBlock to request the page in, if NULL it's the same
+ *           as the last request (a name must have been given previously)
+ *   Start: Address offset within the RB
+ *   Len: Length in bytes required - must be a multiple of pagesize
+ */
+void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
+                               ram_addr_t start, ram_addr_t len)
+{
+    uint8_t bufc[16+1+255]; /* start (8 byte), len (8 byte), rbname upto 256 */
+    uint64_t *buf64 = (uint64_t *)bufc;
+    size_t msglen = 16; /* start + len */
+
+    assert(!(len & 1));
+    if (rbname) {
+        int rbname_len = strlen(rbname);
+        assert(rbname_len < 256);

migration/migration.c void migrate_send_rp_pong(MigrationIncomingState *mis, · line 168

Quoted 10 lines
migration/migration.c +10 -0
+
+        len |= 1; /* Flag to say we've got a name */
+        bufc[msglen++] = rbname_len;
+        memcpy(bufc + msglen, rbname, rbname_len);
+        msglen += rbname_len;
+    }
+
+    buf64[0] = cpu_to_be64((uint64_t)start);
+    buf64[1] = cpu_to_be64((uint64_t)len);
+    migrate_send_rp_message(mis, MIG_RP_CMD_REQ_PAGES, msglen, bufc);

So.. what's the reason we actually need ramblock names on the wire, rather than working purely from GPAs?

It occurs to me that referencing ramblock names from the wire protocol exposes something that's kind of an internal detail, and may limit our options for reworking the memory subsystem in future.

Quoted 33 lines
migration/migration.c +15 -0
+}
+
 void qemu_start_incoming_migration(const char *uri, Error **errp)
 {
     const char *p;
@@ -789,6 +819,17 @@ static void source_return_path_bad(MigrationState *s)
 }
 
 /*
+ * Process a request for pages received on the return path,
+ * We're allowed to send more than requested (e.g. to round to our page size)
+ * and we don't need to send pages that have already been sent.
+ */
+static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
+                                       ram_addr_t start, ram_addr_t len)
+{
+    trace_migrate_handle_rp_req_pages(start, len);
+}
+
+/*
  * Handles messages sent on the return path towards the source VM
  *
  */
@@ -800,6 +841,8 @@ static void *source_return_path_thread(void *opaque)
     const int max_len = 512;
     uint8_t buf[max_len];
     uint32_t tmp32;
+    ram_addr_t start, len;
+    char *tmpstr;
     int res;
 
     trace_source_return_path_thread_entry();

migration/migration.c static void *source_return_path_thread(void *opaque) · line 863

Quoted 6 lines
migration/migration.c +3 -0
@@ -815,6 +858,11 @@ static void *source_return_path_thread(void *opaque)
             expected_len = 4;
             break;
 
+        case MIG_RP_CMD_REQ_PAGES:
+            /* 16 byte start/len _possibly_ plus an id str */
+            expected_len = 16 + 256;

Isn't that the maximum length, rather than the minimum or typical length?

Quoted 12 lines
migration/migration.c +5 -0
+            break;
+
         default:
             error_report("RP: Received invalid cmd 0x%04x length 0x%04x",
                     header_com, header_len);
@@ -860,6 +908,28 @@ static void *source_return_path_thread(void *opaque)
             trace_source_return_path_thread_pong(tmp32);
             break;
 
+        case MIG_RP_CMD_REQ_PAGES:
+            start = be64_to_cpup((uint64_t *)buf);
+            len = be64_to_cpup(((uint64_t *)buf)+1);

migration/migration.c static void *source_return_path_thread(void *opaque) · line 923

Quoted 10 lines
migration/migration.c +10 -0
+            tmpstr = NULL;
+            if (len & 1) {
+                len -= 1; /* Remove the flag */
+                /* Now we expect an idstr */
+                tmp32 = buf[16]; /* Length of the following idstr */
+                tmpstr = (char *)&buf[17];
+                buf[17+tmp32] = '\0';
+                expected_len = 16+1+tmp32;
+            } else {
+                expected_len = 16;

Ah.. so expected_len is changed here. But then what was the point of setting it in the earlier switch?

Quoted 24 lines
migration/migration.c +9 -0
+            }
+            if (header_len != expected_len) {
+                error_report("RP: Req_Page with length %d expecting %d",
+                        header_len, expected_len);
+                source_return_path_bad(ms);
+            }
+            migrate_handle_rp_req_pages(ms, tmpstr, start, len);
+            break;
+
         default:
             /* This shouldn't happen because we should catch this above */
             trace_source_return_path_bad_header_com();
trace-events +1 -0
index bcbdef8..9bedee4 100644
@@ -1404,6 +1404,7 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
+migrate_handle_rp_req_pages(size_t start, size_t len) "at %zx for len %zx"
 migration_thread_after_loop(void) ""
 migration_thread_file_err(void) ""
 migration_thread_setup_complete(void) ""
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#148 lore raw

Re: [Qemu-devel] [PATCH v5 32/45] Page request: Add MIG_RP_CMD_REQ_PAGES reverse command

Quoted 75 lines · * David Gibson ([email protected]) wrote:
Quoted 60 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Add MIG_RP_CMD_REQ_PAGES command on Return path for the postcopy destination to request a page from the source.

---
 include/migration/migration.h |  4 +++
 migration/migration.c         | 70 +++++++++++++++++++++++++++++++++++++++++++
 trace-events                  |  1 +
 3 files changed, 75 insertions(+)
include/migration/migration.h +4 -0
index 2c607e7..2c15d63 100644
@@ -46,6 +46,8 @@ enum mig_rpcomm_cmd {
     MIG_RP_CMD_INVALID = 0,  /* Must be 0 */
     MIG_RP_CMD_SHUT,         /* sibling will not send any more RP messages */
     MIG_RP_CMD_PONG,         /* Response to a PING; data (seq: be32 ) */
+
+    MIG_RP_CMD_REQ_PAGES,    /* data (start: be64, len: be64) */
 };
 
 /* Postcopy page-map-incoming - data about each page on the inbound side */
@@ -253,6 +255,8 @@ void migrate_send_rp_shut(MigrationIncomingState *mis,
                           uint32_t value);
 void migrate_send_rp_pong(MigrationIncomingState *mis,
                           uint32_t value);
+void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char* rbname,
+                              ram_addr_t start, ram_addr_t len);
 
 void ram_control_before_iterate(QEMUFile *f, uint64_t flags);
 void ram_control_after_iterate(QEMUFile *f, uint64_t flags);
migration/migration.c +18 -0
index bd066f6..2e9d0dd 100644
@@ -138,6 +138,36 @@ void migrate_send_rp_pong(MigrationIncomingState *mis,
     migrate_send_rp_message(mis, MIG_RP_CMD_PONG, 4, (uint8_t *)&buf);
 }
 
+/* Request a range of pages from the source VM at the given
+ * start address.
+ *   rbname: Name of the RAMBlock to request the page in, if NULL it's the same
+ *           as the last request (a name must have been given previously)
+ *   Start: Address offset within the RB
+ *   Len: Length in bytes required - must be a multiple of pagesize
+ */
+void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
+                               ram_addr_t start, ram_addr_t len)
+{
+    uint8_t bufc[16+1+255]; /* start (8 byte), len (8 byte), rbname upto 256 */
+    uint64_t *buf64 = (uint64_t *)bufc;
+    size_t msglen = 16; /* start + len */
+
+    assert(!(len & 1));
+    if (rbname) {
+        int rbname_len = strlen(rbname);
+        assert(rbname_len < 256);

migration/migration.c void migrate_send_rp_pong(MigrationIncomingState *mis, · line 168

Quoted 10 lines
migration/migration.c +10 -0
+
+        len |= 1; /* Flag to say we've got a name */
+        bufc[msglen++] = rbname_len;
+        memcpy(bufc + msglen, rbname, rbname_len);
+        msglen += rbname_len;
+    }
+
+    buf64[0] = cpu_to_be64((uint64_t)start);
+    buf64[1] = cpu_to_be64((uint64_t)len);
+    migrate_send_rp_message(mis, MIG_RP_CMD_REQ_PAGES, msglen, bufc);

So.. what's the reason we actually need ramblock names on the wire, rather than working purely from GPAs?

Quoted 3 lines

It occurs to me that referencing ramblock names from the wire protocol exposes something that's kind of an internal detail, and may limit our options for reworking the memory subsystem in future.

RAMBlock names are already exposed on the wire in precopy migration in the forward direction anyway (see save_page_header), however there are a few reasons:
1) There's no guarantee that the page you are transmitting is currently mapped into the guest. The ACPI tables are never mapped.
2) Aliases in GPA are allowed.

The only thing that's unique is a reference to the RAMBlock and an offset within it.
(and yes, it does break when we change RAMBlock names but that's normally accidental - it did happen sometime around QEMU 1.6 when the PCI strings were accidentally changed with a knock on effect of renaming RAMBlocks).

Quoted 36 lines
Quoted 36 lines
migration/migration.c +15 -0
+}
+
 void qemu_start_incoming_migration(const char *uri, Error **errp)
 {
     const char *p;
@@ -789,6 +819,17 @@ static void source_return_path_bad(MigrationState *s)
 }
 
 /*
+ * Process a request for pages received on the return path,
+ * We're allowed to send more than requested (e.g. to round to our page size)
+ * and we don't need to send pages that have already been sent.
+ */
+static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
+                                       ram_addr_t start, ram_addr_t len)
+{
+    trace_migrate_handle_rp_req_pages(start, len);
+}
+
+/*
  * Handles messages sent on the return path towards the source VM
  *
  */
@@ -800,6 +841,8 @@ static void *source_return_path_thread(void *opaque)
     const int max_len = 512;
     uint8_t buf[max_len];
     uint32_t tmp32;
+    ram_addr_t start, len;
+    char *tmpstr;
     int res;
 
     trace_source_return_path_thread_entry();
@@ -815,6 +858,11 @@ static void *source_return_path_thread(void *opaque)
             expected_len = 4;
             break;
 
Quoted 5 lines

migration/migration.c static void *source_return_path_thread(void *opaque) · line 863

Quoted 3 lines
migration/migration.c +3 -0
+        case MIG_RP_CMD_REQ_PAGES:
+            /* 16 byte start/len _possibly_ plus an id str */
+            expected_len = 16 + 256;

Isn't that the maximum length, rather than the minimum or typical length?

I'm just trying to be fairly paranoid prior to reading the header. If at this point we're working our way through garbage received off a misaligned stream then if we fail to spot it in this switch then we end up doing a qemu_get_buffer on that bad length. Checking it just for a maximum would make it safe against something malicious, but if the destination hadn't sent that much data then we'd just block here and never get around to reporting an error. This way, for most command types we're being pretty careful.

Quoted 9 lines
Quoted 9 lines
migration/migration.c +2 -0
+            break;
+
         default:
             error_report("RP: Received invalid cmd 0x%04x length 0x%04x",
                     header_com, header_len);
@@ -860,6 +908,28 @@ static void *source_return_path_thread(void *opaque)
             trace_source_return_path_thread_pong(tmp32);
             break;
 
Quoted 16 lines

migration/migration.c static void *source_return_path_thread(void *opaque) · line 923

Quoted 13 lines
migration/migration.c +13 -0
+        case MIG_RP_CMD_REQ_PAGES:
+            start = be64_to_cpup((uint64_t *)buf);
+            len = be64_to_cpup(((uint64_t *)buf)+1);
+            tmpstr = NULL;
+            if (len & 1) {
+                len -= 1; /* Remove the flag */
+                /* Now we expect an idstr */
+                tmp32 = buf[16]; /* Length of the following idstr */
+                tmpstr = (char *)&buf[17];
+                buf[17+tmp32] = '\0';
+                expected_len = 16+1+tmp32;
+            } else {
+                expected_len = 16;

Ah.. so expected_len is changed here. But then what was the point of setting it in the earlier switch?

For the upper bound on the qemu_get_buffer.

Dave

Quoted 17 lines
Quoted 17 lines
migration/migration.c +9 -0
+            }
+            if (header_len != expected_len) {
+                error_report("RP: Req_Page with length %d expecting %d",
+                        header_len, expected_len);
+                source_return_path_bad(ms);
+            }
+            migrate_handle_rp_req_pages(ms, tmpstr, start, len);
+            break;
+
         default:
             /* This shouldn't happen because we should catch this above */
             trace_source_return_path_bad_header_com();
trace-events +0 -0
index bcbdef8..9bedee4 100644
Quoted 14 lines
Quoted 8 lines
trace-events +1 -0
@@ -1404,6 +1404,7 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
+migrate_handle_rp_req_pages(size_t start, size_t len) "at %zx for len %zx"
 migration_thread_after_loop(void) ""
 migration_thread_file_err(void) ""
 migration_thread_setup_complete(void) ""
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#149 lore raw

Re: [Qemu-devel] [PATCH v5 32/45] Page request: Add MIG_RP_CMD_REQ_PAGES reverse command

Quoted 87 lines · Dr. David Alan Gilbert
Quoted 75 lines · * David Gibson ([email protected]) wrote:
Quoted 60 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Add MIG_RP_CMD_REQ_PAGES command on Return path for the postcopy destination to request a page from the source.

---
 include/migration/migration.h |  4 +++
 migration/migration.c         | 70 +++++++++++++++++++++++++++++++++++++++++++
 trace-events                  |  1 +
 3 files changed, 75 insertions(+)
include/migration/migration.h +4 -0
index 2c607e7..2c15d63 100644
@@ -46,6 +46,8 @@ enum mig_rpcomm_cmd {
     MIG_RP_CMD_INVALID = 0,  /* Must be 0 */
     MIG_RP_CMD_SHUT,         /* sibling will not send any more RP messages */
     MIG_RP_CMD_PONG,         /* Response to a PING; data (seq: be32 ) */
+
+    MIG_RP_CMD_REQ_PAGES,    /* data (start: be64, len: be64) */
 };
 
 /* Postcopy page-map-incoming - data about each page on the inbound side */
@@ -253,6 +255,8 @@ void migrate_send_rp_shut(MigrationIncomingState *mis,
                           uint32_t value);
 void migrate_send_rp_pong(MigrationIncomingState *mis,
                           uint32_t value);
+void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char* rbname,
+                              ram_addr_t start, ram_addr_t len);
 
 void ram_control_before_iterate(QEMUFile *f, uint64_t flags);
 void ram_control_after_iterate(QEMUFile *f, uint64_t flags);
migration/migration.c +18 -0
index bd066f6..2e9d0dd 100644
@@ -138,6 +138,36 @@ void migrate_send_rp_pong(MigrationIncomingState *mis,
     migrate_send_rp_message(mis, MIG_RP_CMD_PONG, 4, (uint8_t *)&buf);
 }
 
+/* Request a range of pages from the source VM at the given
+ * start address.
+ *   rbname: Name of the RAMBlock to request the page in, if NULL it's the same
+ *           as the last request (a name must have been given previously)
+ *   Start: Address offset within the RB
+ *   Len: Length in bytes required - must be a multiple of pagesize
+ */
+void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
+                               ram_addr_t start, ram_addr_t len)
+{
+    uint8_t bufc[16+1+255]; /* start (8 byte), len (8 byte), rbname upto 256 */
+    uint64_t *buf64 = (uint64_t *)bufc;
+    size_t msglen = 16; /* start + len */
+
+    assert(!(len & 1));
+    if (rbname) {
+        int rbname_len = strlen(rbname);
+        assert(rbname_len < 256);

migration/migration.c void migrate_send_rp_pong(MigrationIncomingState *mis, · line 168

Quoted 10 lines
migration/migration.c +10 -0
+
+        len |= 1; /* Flag to say we've got a name */
+        bufc[msglen++] = rbname_len;
+        memcpy(bufc + msglen, rbname, rbname_len);
+        msglen += rbname_len;
+    }
+
+    buf64[0] = cpu_to_be64((uint64_t)start);
+    buf64[1] = cpu_to_be64((uint64_t)len);
+    migrate_send_rp_message(mis, MIG_RP_CMD_REQ_PAGES, msglen, bufc);

So.. what's the reason we actually need ramblock names on the wire, rather than working purely from GPAs?

Quoted 3 lines

It occurs to me that referencing ramblock names from the wire protocol exposes something that's kind of an internal detail, and may limit our options for reworking the memory subsystem in future.

RAMBlock names are already exposed on the wire in precopy migration in the forward direction anyway (see save_page_header), however there are a few reasons:
1) There's no guarantee that the page you are transmitting is currently mapped into the guest. The ACPI tables are never mapped.
2) Aliases in GPA are allowed.

Quoted 5 lines

The only thing that's unique is a reference to the RAMBlock and an offset within it.
(and yes, it does break when we change RAMBlock names but that's normally accidental - it did happen sometime around QEMU 1.6 when the PCI strings were accidentally changed with a knock on effect of renaming RAMBlocks).

Ah, right, good point.

Quoted 78 lines
Quoted 36 lines
Quoted 36 lines
migration/migration.c +15 -0
+}
+
 void qemu_start_incoming_migration(const char *uri, Error **errp)
 {
     const char *p;
@@ -789,6 +819,17 @@ static void source_return_path_bad(MigrationState *s)
 }
 
 /*
+ * Process a request for pages received on the return path,
+ * We're allowed to send more than requested (e.g. to round to our page size)
+ * and we don't need to send pages that have already been sent.
+ */
+static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
+                                       ram_addr_t start, ram_addr_t len)
+{
+    trace_migrate_handle_rp_req_pages(start, len);
+}
+
+/*
  * Handles messages sent on the return path towards the source VM
  *
  */
@@ -800,6 +841,8 @@ static void *source_return_path_thread(void *opaque)
     const int max_len = 512;
     uint8_t buf[max_len];
     uint32_t tmp32;
+    ram_addr_t start, len;
+    char *tmpstr;
     int res;
 
     trace_source_return_path_thread_entry();
@@ -815,6 +858,11 @@ static void *source_return_path_thread(void *opaque)
             expected_len = 4;
             break;
 
Quoted 5 lines

migration/migration.c static void *source_return_path_thread(void *opaque) · line 863

Quoted 3 lines
migration/migration.c +3 -0
+        case MIG_RP_CMD_REQ_PAGES:
+            /* 16 byte start/len _possibly_ plus an id str */
+            expected_len = 16 + 256;

Isn't that the maximum length, rather than the minimum or typical length?

I'm just trying to be fairly paranoid prior to reading the header. If at this point we're working our way through garbage received off a misaligned stream then if we fail to spot it in this switch then we end up doing a qemu_get_buffer on that bad length. Checking it just for a maximum would make it safe against something malicious, but if the destination hadn't sent that much data then we'd just block here and never get around to reporting an error. This way, for most command types we're being pretty careful.

Quoted 9 lines
Quoted 9 lines
migration/migration.c +2 -0
+            break;
+
         default:
             error_report("RP: Received invalid cmd 0x%04x length 0x%04x",
                     header_com, header_len);
@@ -860,6 +908,28 @@ static void *source_return_path_thread(void *opaque)
             trace_source_return_path_thread_pong(tmp32);
             break;
 
Quoted 16 lines

migration/migration.c static void *source_return_path_thread(void *opaque) · line 923

Quoted 13 lines
migration/migration.c +13 -0
+        case MIG_RP_CMD_REQ_PAGES:
+            start = be64_to_cpup((uint64_t *)buf);
+            len = be64_to_cpup(((uint64_t *)buf)+1);
+            tmpstr = NULL;
+            if (len & 1) {
+                len -= 1; /* Remove the flag */
+                /* Now we expect an idstr */
+                tmp32 = buf[16]; /* Length of the following idstr */
+                tmpstr = (char *)&buf[17];
+                buf[17+tmp32] = '\0';
+                expected_len = 16+1+tmp32;
+            } else {
+                expected_len = 16;

Ah.. so expected_len is changed here. But then what was the point of setting it in the earlier switch?

Quoted 1 line

For the upper bound on the qemu_get_buffer.

Ok, I think I'd forgotten exactly how the checks worked from the earlier patch.

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#150 lore raw

PATCH v5 33/45 Page request: Process incoming page request

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

On receiving MIG_RPCOMM_REQ_PAGES look up the address and queue the page.

---
 arch_init.c                   | 55 +++++++++++++++++++++++++++++++++++++++++++
 include/exec/cpu-all.h        |  2 --
 include/migration/migration.h | 21 +++++++++++++++++
 include/qemu/typedefs.h       |  1 +
 migration/migration.c         | 33 +++++++++++++++++++++++++-
 trace-events                  |  3 ++-
 6 files changed, 111 insertions(+), 4 deletions(-)
arch_init.c +55 -0
index d2c4457..9d8fc6b 100644
@@ -669,6 +669,61 @@ static int ram_save_page(QEMUFile *f, RAMBlock* block, ram_addr_t offset,
 }
 
 /*
+ * Queue the pages for transmission, e.g. a request from postcopy destination
+ *   ms: MigrationStatus in which the queue is held
+ *   rbname: The RAMBlock the request is for - may be NULL (to mean reuse last)
+ *   start: Offset from the start of the RAMBlock
+ *   len: Length (in bytes) to send
+ *   Return: 0 on success
+ */
+int ram_save_queue_pages(MigrationState *ms, const char *rbname,
+                         ram_addr_t start, ram_addr_t len)
+{
+    RAMBlock *ramblock;
+
+    if (!rbname) {
+        /* Reuse last RAMBlock */
+        ramblock = ms->last_req_rb;
+
+        if (!ramblock) {
+            /*
+             * Shouldn't happen, we can't reuse the last RAMBlock if
+             * it's the 1st request.
+             */
+            error_report("ram_save_queue_pages no previous block");
+            return -1;
+        }
+    } else {
+        ramblock = ram_find_block(rbname);
+
+        if (!ramblock) {
+            /* We shouldn't be asked for a non-existent RAMBlock */
+            error_report("ram_save_queue_pages no block '%s'", rbname);
+            return -1;
+        }
+    }
+    trace_ram_save_queue_pages(ramblock->idstr, start, len);
+    if (start+len > ramblock->used_length) {
+        error_report("%s request overrun start=%zx len=%zx blocklen=%zx",
+                     __func__, start, len, ramblock->used_length);
+        return -1;
+    }
+
+    struct MigrationSrcPageRequest *new_entry =
+        g_malloc0(sizeof(struct MigrationSrcPageRequest));
+    new_entry->rb = ramblock;
+    new_entry->offset = start;
+    new_entry->len = len;
+    ms->last_req_rb = ramblock;
+
+    qemu_mutex_lock(&ms->src_page_req_mutex);
+    QSIMPLEQ_INSERT_TAIL(&ms->src_page_requests, new_entry, next_req);
+    qemu_mutex_unlock(&ms->src_page_req_mutex);
+
+    return 0;
+}
+
+/*
  * ram_find_and_save_block: Finds a page to send and sends it to f
  *
  * Returns:  The number of bytes written.
include/exec/cpu-all.h +0 -2
index 2c48286..3088000 100644
@@ -265,8 +265,6 @@ CPUArchState *cpu_copy(CPUArchState *env);
 
 /* memory API */
 
-typedef struct RAMBlock RAMBlock;
-
 struct RAMBlock {
     struct MemoryRegion *mr;
     uint8_t *host;
include/migration/migration.h +21 -0
index 2c15d63..b1c7cad 100644
@@ -100,6 +100,18 @@ MigrationIncomingState *migration_incoming_get_current(void);
 MigrationIncomingState *migration_incoming_state_new(QEMUFile *f);
 void migration_incoming_state_destroy(void);
 
+/*
+ * An outstanding page request, on the source, having been received
+ * and queued
+ */
+struct MigrationSrcPageRequest {
+    RAMBlock *rb;
+    hwaddr    offset;
+    hwaddr    len;
+
+    QSIMPLEQ_ENTRY(MigrationSrcPageRequest) next_req;
+};
+
 struct MigrationState
 {
     int64_t bandwidth_limit;
@@ -142,6 +154,12 @@ struct MigrationState
      * of the postcopy phase
      */
     unsigned long *sentmap;
+
+    /* Queue of outstanding page requests from the destination */
+    QemuMutex src_page_req_mutex;
+    QSIMPLEQ_HEAD(src_page_requests, MigrationSrcPageRequest) src_page_requests;
+    /* The RAMBlock used in the last src_page_request */
+    RAMBlock *last_req_rb;
 };
 
 void process_incoming_migration(QEMUFile *f);
@@ -276,6 +294,9 @@ size_t ram_control_save_page(QEMUFile *f, ram_addr_t block_offset,
                              ram_addr_t offset, size_t size,
                              int *bytes_sent);
 
+int ram_save_queue_pages(MigrationState *ms, const char *rbname,
+                         ram_addr_t start, ram_addr_t len);
+
 PostcopyState postcopy_state_get(MigrationIncomingState *mis);
 
 /* Set the state and return the old state */
include/qemu/typedefs.h +1 -0
index 0651275..396044d 100644
@@ -73,6 +73,7 @@ typedef struct QEMUSGList QEMUSGList;
 typedef struct QEMUSizedBuffer QEMUSizedBuffer;
 typedef struct QEMUTimerListGroup QEMUTimerListGroup;
 typedef struct QEMUTimer QEMUTimer;
+typedef struct RAMBlock RAMBlock;
 typedef struct Range Range;
 typedef struct SerialState SerialState;
 typedef struct SHPCDevice SHPCDevice;
migration/migration.c +32 -1
index 2e9d0dd..939f426 100644
@@ -26,6 +26,8 @@
 #include "qemu/thread.h"
 #include "qmp-commands.h"
 #include "trace.h"
+#include "exec/memory.h"
+#include "exec/address-spaces.h"
 
 enum MigrationPhase {
     MIG_STATE_ERROR = -1,
@@ -495,6 +497,15 @@ static void migrate_fd_cleanup(void *opaque)
 
     migrate_fd_cleanup_src_rp(s);
 
+    /* This queue generally should be empty - but in the case of a failed
+     * migration might have some droppings in.
+     */
+    struct MigrationSrcPageRequest *mspr, *next_mspr;
+    QSIMPLEQ_FOREACH_SAFE(mspr, &s->src_page_requests, next_req, next_mspr) {
+        QSIMPLEQ_REMOVE_HEAD(&s->src_page_requests, next_req);
+        g_free(mspr);
+    }
+
     if (s->file) {
         trace_migrate_fd_cleanup();
         qemu_mutex_unlock_iothread();
@@ -613,6 +624,9 @@ MigrationState *migrate_init(const MigrationParams *params)
     s->state = MIG_STATE_SETUP;
     trace_migrate_set_state(MIG_STATE_SETUP);
 
+    qemu_mutex_init(&s->src_page_req_mutex);
+    QSIMPLEQ_INIT(&s->src_page_requests);
+
     s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
     return s;
 }
@@ -826,7 +840,24 @@ static void source_return_path_bad(MigrationState *s)
 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
                                        ram_addr_t start, ram_addr_t len)
 {
-    trace_migrate_handle_rp_req_pages(start, len);
+    trace_migrate_handle_rp_req_pages(rbname, start, len);
+
+    /* Round everything up to our host page size */
+    long our_host_ps = getpagesize();
+    if (start & (our_host_ps-1)) {
+        long roundings = start & (our_host_ps-1);
+        start -= roundings;
+        len += roundings;
+    }
+    if (len & (our_host_ps-1)) {
+        long roundings = len & (our_host_ps-1);
+        len -= roundings;
+        len += our_host_ps;
+    }
+
+    if (ram_save_queue_pages(ms, rbname, start, len)) {
+        source_return_path_bad(ms);
+    }
 }
 
 /*
trace-events +2 -1
index 9bedee4..8a0d70d 100644
@@ -1218,6 +1218,7 @@ migration_bitmap_sync_start(void) ""
 migration_bitmap_sync_end(uint64_t dirty_pages) "dirty_pages %" PRIu64""
 migration_throttle(void) ""
 ram_postcopy_send_discard_bitmap(void) ""
+ram_save_queue_pages(const char *rbname, size_t start, size_t len) "%s: start: %zx len: %zx"
 
 # hw/display/qxl.c
 disable qxl_interface_set_mm_time(int qid, uint32_t mm_time) "%d %d"
@@ -1404,7 +1405,7 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
-migrate_handle_rp_req_pages(size_t start, size_t len) "at %zx for len %zx"
+migrate_handle_rp_req_pages(const char *rbname, size_t start, size_t len) "in %s at %zx len %zx"
 migration_thread_after_loop(void) ""
 migration_thread_file_err(void) ""
 migration_thread_setup_complete(void) ""
Signature · 1 line
2.1.0
#151 lore raw

Re: [Qemu-devel] [PATCH v5 33/45] Page request: Process incoming page request

Quoted 200 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

On receiving MIG_RPCOMM_REQ_PAGES look up the address and queue the page.

---
 arch_init.c                   | 55 +++++++++++++++++++++++++++++++++++++++++++
 include/exec/cpu-all.h        |  2 --
 include/migration/migration.h | 21 +++++++++++++++++
 include/qemu/typedefs.h       |  1 +
 migration/migration.c         | 33 +++++++++++++++++++++++++-
 trace-events                  |  3 ++-
 6 files changed, 111 insertions(+), 4 deletions(-)
arch_init.c +55 -0
index d2c4457..9d8fc6b 100644
@@ -669,6 +669,61 @@ static int ram_save_page(QEMUFile *f, RAMBlock* block, ram_addr_t offset,
 }
 
 /*
+ * Queue the pages for transmission, e.g. a request from postcopy destination
+ *   ms: MigrationStatus in which the queue is held
+ *   rbname: The RAMBlock the request is for - may be NULL (to mean reuse last)
+ *   start: Offset from the start of the RAMBlock
+ *   len: Length (in bytes) to send
+ *   Return: 0 on success
+ */
+int ram_save_queue_pages(MigrationState *ms, const char *rbname,
+                         ram_addr_t start, ram_addr_t len)
+{
+    RAMBlock *ramblock;
+
+    if (!rbname) {
+        /* Reuse last RAMBlock */
+        ramblock = ms->last_req_rb;
+
+        if (!ramblock) {
+            /*
+             * Shouldn't happen, we can't reuse the last RAMBlock if
+             * it's the 1st request.
+             */
+            error_report("ram_save_queue_pages no previous block");
+            return -1;
+        }
+    } else {
+        ramblock = ram_find_block(rbname);
+
+        if (!ramblock) {
+            /* We shouldn't be asked for a non-existent RAMBlock */
+            error_report("ram_save_queue_pages no block '%s'", rbname);
+            return -1;
+        }
+    }
+    trace_ram_save_queue_pages(ramblock->idstr, start, len);
+    if (start+len > ramblock->used_length) {
+        error_report("%s request overrun start=%zx len=%zx blocklen=%zx",
+                     __func__, start, len, ramblock->used_length);
+        return -1;
+    }
+
+    struct MigrationSrcPageRequest *new_entry =
+        g_malloc0(sizeof(struct MigrationSrcPageRequest));
+    new_entry->rb = ramblock;
+    new_entry->offset = start;
+    new_entry->len = len;
+    ms->last_req_rb = ramblock;
+
+    qemu_mutex_lock(&ms->src_page_req_mutex);
+    QSIMPLEQ_INSERT_TAIL(&ms->src_page_requests, new_entry, next_req);
+    qemu_mutex_unlock(&ms->src_page_req_mutex);
+
+    return 0;
+}
+
+/*
  * ram_find_and_save_block: Finds a page to send and sends it to f
  *
  * Returns:  The number of bytes written.
include/exec/cpu-all.h +0 -2
index 2c48286..3088000 100644
@@ -265,8 +265,6 @@ CPUArchState *cpu_copy(CPUArchState *env);
 
 /* memory API */
 
-typedef struct RAMBlock RAMBlock;
-
 struct RAMBlock {
     struct MemoryRegion *mr;
     uint8_t *host;
include/migration/migration.h +21 -0
index 2c15d63..b1c7cad 100644
@@ -100,6 +100,18 @@ MigrationIncomingState *migration_incoming_get_current(void);
 MigrationIncomingState *migration_incoming_state_new(QEMUFile *f);
 void migration_incoming_state_destroy(void);
 
+/*
+ * An outstanding page request, on the source, having been received
+ * and queued
+ */
+struct MigrationSrcPageRequest {
+    RAMBlock *rb;
+    hwaddr    offset;
+    hwaddr    len;
+
+    QSIMPLEQ_ENTRY(MigrationSrcPageRequest) next_req;
+};
+
 struct MigrationState
 {
     int64_t bandwidth_limit;
@@ -142,6 +154,12 @@ struct MigrationState
      * of the postcopy phase
      */
     unsigned long *sentmap;
+
+    /* Queue of outstanding page requests from the destination */
+    QemuMutex src_page_req_mutex;
+    QSIMPLEQ_HEAD(src_page_requests, MigrationSrcPageRequest) src_page_requests;
+    /* The RAMBlock used in the last src_page_request */
+    RAMBlock *last_req_rb;
 };
 
 void process_incoming_migration(QEMUFile *f);
@@ -276,6 +294,9 @@ size_t ram_control_save_page(QEMUFile *f, ram_addr_t block_offset,
                              ram_addr_t offset, size_t size,
                              int *bytes_sent);
 
+int ram_save_queue_pages(MigrationState *ms, const char *rbname,
+                         ram_addr_t start, ram_addr_t len);
+
 PostcopyState postcopy_state_get(MigrationIncomingState *mis);
 
 /* Set the state and return the old state */
include/qemu/typedefs.h +1 -0
index 0651275..396044d 100644
@@ -73,6 +73,7 @@ typedef struct QEMUSGList QEMUSGList;
 typedef struct QEMUSizedBuffer QEMUSizedBuffer;
 typedef struct QEMUTimerListGroup QEMUTimerListGroup;
 typedef struct QEMUTimer QEMUTimer;
+typedef struct RAMBlock RAMBlock;
 typedef struct Range Range;
 typedef struct SerialState SerialState;
 typedef struct SHPCDevice SHPCDevice;
migration/migration.c +18 -1
index 2e9d0dd..939f426 100644
@@ -26,6 +26,8 @@
 #include "qemu/thread.h"
 #include "qmp-commands.h"
 #include "trace.h"
+#include "exec/memory.h"
+#include "exec/address-spaces.h"
 
 enum MigrationPhase {
     MIG_STATE_ERROR = -1,
@@ -495,6 +497,15 @@ static void migrate_fd_cleanup(void *opaque)
 
     migrate_fd_cleanup_src_rp(s);
 
+    /* This queue generally should be empty - but in the case of a failed
+     * migration might have some droppings in.
+     */
+    struct MigrationSrcPageRequest *mspr, *next_mspr;
+    QSIMPLEQ_FOREACH_SAFE(mspr, &s->src_page_requests, next_req, next_mspr) {
+        QSIMPLEQ_REMOVE_HEAD(&s->src_page_requests, next_req);
+        g_free(mspr);
+    }
+
     if (s->file) {
         trace_migrate_fd_cleanup();
         qemu_mutex_unlock_iothread();
@@ -613,6 +624,9 @@ MigrationState *migrate_init(const MigrationParams *params)
     s->state = MIG_STATE_SETUP;
     trace_migrate_set_state(MIG_STATE_SETUP);
 
+    qemu_mutex_init(&s->src_page_req_mutex);
+    QSIMPLEQ_INIT(&s->src_page_requests);
+
     s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
     return s;
 }
@@ -826,7 +840,24 @@ static void source_return_path_bad(MigrationState *s)
 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
                                        ram_addr_t start, ram_addr_t len)
 {
-    trace_migrate_handle_rp_req_pages(start, len);
+    trace_migrate_handle_rp_req_pages(rbname, start, len);
+
+    /* Round everything up to our host page size */
+    long our_host_ps = getpagesize();

migration/migration.c static void source_return_path_bad(MigrationState *s) · line 856

Quoted 10 lines
migration/migration.c +10 -0
+    if (start & (our_host_ps-1)) {
+        long roundings = start & (our_host_ps-1);
+        start -= roundings;
+        len += roundings;
+    }
+    if (len & (our_host_ps-1)) {
+        long roundings = len & (our_host_ps-1);
+        len -= roundings;
+        len += our_host_ps;
+    }

Why is it necessary to round out to host page size on the source? I understand why the host page size is relevant on the destination, due to the userfaultfd and atomic populate constraints, but not on the source.

Quoted 27 lines
migration/migration.c +3 -0
+    if (ram_save_queue_pages(ms, rbname, start, len)) {
+        source_return_path_bad(ms);
+    }
 }
 
 /*
trace-events +2 -1
index 9bedee4..8a0d70d 100644
@@ -1218,6 +1218,7 @@ migration_bitmap_sync_start(void) ""
 migration_bitmap_sync_end(uint64_t dirty_pages) "dirty_pages %" PRIu64""
 migration_throttle(void) ""
 ram_postcopy_send_discard_bitmap(void) ""
+ram_save_queue_pages(const char *rbname, size_t start, size_t len) "%s: start: %zx len: %zx"
 
 # hw/display/qxl.c
 disable qxl_interface_set_mm_time(int qid, uint32_t mm_time) "%d %d"
@@ -1404,7 +1405,7 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
-migrate_handle_rp_req_pages(size_t start, size_t len) "at %zx for len %zx"
+migrate_handle_rp_req_pages(const char *rbname, size_t start, size_t len) "in %s at %zx len %zx"
 migration_thread_after_loop(void) ""
 migration_thread_file_err(void) ""
 migration_thread_setup_complete(void) ""
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#152 lore raw

Re: [Qemu-devel] [PATCH v5 33/45] Page request: Process incoming page request

Quoted 20 lines · * David Gibson ([email protected]) wrote:
Quoted 19 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

On receiving MIG_RPCOMM_REQ_PAGES look up the address and queue the page.

---
 arch_init.c                   | 55 +++++++++++++++++++++++++++++++++++++++++++
 include/exec/cpu-all.h        |  2 --
 include/migration/migration.h | 21 +++++++++++++++++
 include/qemu/typedefs.h       |  1 +
 migration/migration.c         | 33 +++++++++++++++++++++++++-
 trace-events                  |  3 ++-
 6 files changed, 111 insertions(+), 4 deletions(-)
arch_init.c +0 -0
index d2c4457..9d8fc6b 100644

<snip>

Quoted 19 lines
Quoted 8 lines

static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
ram_addr_t start, ram_addr_t len)
{

arch_init.c +4 -1
-    trace_migrate_handle_rp_req_pages(start, len);
+    trace_migrate_handle_rp_req_pages(rbname, start, len);
+
+    /* Round everything up to our host page size */
+    long our_host_ps = getpagesize();

arch_init.c

Quoted 10 lines
arch_init.c +10 -0
+    if (start & (our_host_ps-1)) {
+        long roundings = start & (our_host_ps-1);
+        start -= roundings;
+        len += roundings;
+    }
+    if (len & (our_host_ps-1)) {
+        long roundings = len & (our_host_ps-1);
+        len -= roundings;
+        len += our_host_ps;
+    }
Quoted 3 lines

Why is it necessary to round out to host page size on the source? I understand why the host page size is relevant on the destination, due to the userfaultfd and atomic populate constraints, but not on the source.

In principal the request you get from the destination should already be nicely aligned; but of course you can't actually trust it, so you have to at least test for alignment.

Since the code has to send whole host pages to keep the destination happy, it expects the requests that come out of the queue to be host page aligned.

At the moment we're only supporting matching page sizes, if we wanted to support mismatches then it probably needs to round to the size of destination host page sizes.

Dave

Quoted 16 lines
Quoted 16 lines
arch_init.c +3 -0
+    if (ram_save_queue_pages(ms, rbname, start, len)) {
+        source_return_path_bad(ms);
+    }
 }
 
 /*
trace-events +1 -0
index 9bedee4..8a0d70d 100644
@@ -1218,6 +1218,7 @@ migration_bitmap_sync_start(void) ""
 migration_bitmap_sync_end(uint64_t dirty_pages) "dirty_pages %" PRIu64""
 migration_throttle(void) ""
 ram_postcopy_send_discard_bitmap(void) ""
+ram_save_queue_pages(const char *rbname, size_t start, size_t len) "%s: start: %zx len: %zx"
 
Quoted 17 lines
Quoted 11 lines
trace-events +1 -1
 # hw/display/qxl.c
 disable qxl_interface_set_mm_time(int qid, uint32_t mm_time) "%d %d"
@@ -1404,7 +1405,7 @@ migrate_fd_error(void) ""
 migrate_fd_cancel(void) ""
 migrate_pending(uint64_t size, uint64_t max, uint64_t post, uint64_t nonpost) "pending size %" PRIu64 " max %" PRIu64 " (post=%" PRIu64 " nonpost=%" PRIu64 ")"
 migrate_send_rp_message(int cmd, uint16_t len) "cmd=%d, len=%d"
-migrate_handle_rp_req_pages(size_t start, size_t len) "at %zx for len %zx"
+migrate_handle_rp_req_pages(const char *rbname, size_t start, size_t len) "in %s at %zx len %zx"
 migration_thread_after_loop(void) ""
 migration_thread_file_err(void) ""
 migration_thread_setup_complete(void) ""
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#153 lore raw

Re: [Qemu-devel] [PATCH v5 33/45] Page request: Process incoming page request

Quoted 47 lines · Dr. David Alan Gilbert
Quoted 20 lines · * David Gibson ([email protected]) wrote:
Quoted 19 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

On receiving MIG_RPCOMM_REQ_PAGES look up the address and queue the page.

---
 arch_init.c                   | 55 +++++++++++++++++++++++++++++++++++++++++++
 include/exec/cpu-all.h        |  2 --
 include/migration/migration.h | 21 +++++++++++++++++
 include/qemu/typedefs.h       |  1 +
 migration/migration.c         | 33 +++++++++++++++++++++++++-
 trace-events                  |  3 ++-
 6 files changed, 111 insertions(+), 4 deletions(-)
arch_init.c +0 -0
index d2c4457..9d8fc6b 100644

<snip>

Quoted 19 lines
Quoted 8 lines

static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
ram_addr_t start, ram_addr_t len)
{

arch_init.c +4 -1
-    trace_migrate_handle_rp_req_pages(start, len);
+    trace_migrate_handle_rp_req_pages(rbname, start, len);
+
+    /* Round everything up to our host page size */
+    long our_host_ps = getpagesize();

arch_init.c

Quoted 10 lines
arch_init.c +10 -0
+    if (start & (our_host_ps-1)) {
+        long roundings = start & (our_host_ps-1);
+        start -= roundings;
+        len += roundings;
+    }
+    if (len & (our_host_ps-1)) {
+        long roundings = len & (our_host_ps-1);
+        len -= roundings;
+        len += our_host_ps;
+    }
Quoted 3 lines

Why is it necessary to round out to host page size on the source? I understand why the host page size is relevant on the destination, due to the userfaultfd and atomic populate constraints, but not on the source.

Quoted 7 lines

In principal the request you get from the destination should already be nicely aligned; but of course you can't actually trust it, so you have to at least test for alignment.

Since the code has to send whole host pages to keep the destination happy, it expects the requests that come out of the queue to be host page aligned.

I don't follow. It sounds like you'll only send non-aligned things if the destination (incorrectly) requests them. But in that case the only thing that the destination will mess up is itself, so where's the requirement to do anything on the source side?

Quoted 3 lines

At the moment we're only supporting matching page sizes, if we wanted to support mismatches then it probably needs to round to the size of destination host page sizes.

And can't that effectively be done by just answering the requests exactly as the destination makes them?

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#154 lore raw

PATCH v5 34/45 Page request: Consume pages off the post-copy queue

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

When transmitting RAM pages, consume pages that have been queued by MIG_RPCOMM_REQPAGE commands and send them ahead of normal page scanning.

Note:
a) After a queued page the linear walk carries on from after the
unqueued page; there is a reasonable chance that the destination was about to ask for other closeby pages anyway.

b) We have to be careful of any assumptions that the page walking
code makes, in particular it does some short cuts on its first linear walk that break as soon as we do a queued page.

---
 arch_init.c  | 154 +++++++++++++++++++++++++++++++++++++++++++++++++----------
 trace-events |   2 +
 2 files changed, 131 insertions(+), 25 deletions(-)
arch_init.c +129 -25
index 9d8fc6b..acf65e1 100644
@@ -328,6 +328,7 @@ static RAMBlock *last_seen_block;
 /* This is the last block from where we have sent data */
 static RAMBlock *last_sent_block;
 static ram_addr_t last_offset;
+static bool last_was_from_queue;
 static unsigned long *migration_bitmap;
 static uint64_t migration_dirty_pages;
 static uint32_t last_version;
@@ -461,6 +462,19 @@ static inline bool migration_bitmap_set_dirty(ram_addr_t addr)
     return ret;
 }
 
+static inline bool migration_bitmap_clear_dirty(ram_addr_t addr)
+{
+    bool ret;
+    int nr = addr >> TARGET_PAGE_BITS;
+
+    ret = test_and_clear_bit(nr, migration_bitmap);
+
+    if (ret) {
+        migration_dirty_pages--;
+    }
+    return ret;
+}
+
 static void migration_bitmap_sync_range(ram_addr_t start, ram_addr_t length)
 {
     ram_addr_t addr;
@@ -669,6 +683,39 @@ static int ram_save_page(QEMUFile *f, RAMBlock* block, ram_addr_t offset,
 }
 
 /*
+ * Unqueue a page from the queue fed by postcopy page requests
+ *
+ * Returns:      The RAMBlock* to transmit from (or NULL if the queue is empty)
+ *      ms:      MigrationState in
+ *  offset:      the byte offset within the RAMBlock for the start of the page
+ * ram_addr_abs: global offset in the dirty/sent bitmaps
+ */
+static RAMBlock *ram_save_unqueue_page(MigrationState *ms, ram_addr_t *offset,
+                                       ram_addr_t *ram_addr_abs)
+{
+    RAMBlock *result = NULL;
+    qemu_mutex_lock(&ms->src_page_req_mutex);
+    if (!QSIMPLEQ_EMPTY(&ms->src_page_requests)) {
+        struct MigrationSrcPageRequest *entry =
+                                    QSIMPLEQ_FIRST(&ms->src_page_requests);
+        result = entry->rb;
+        *offset = entry->offset;
+        *ram_addr_abs = (entry->offset + entry->rb->offset) & TARGET_PAGE_MASK;
+
+        if (entry->len > TARGET_PAGE_SIZE) {
+            entry->len -= TARGET_PAGE_SIZE;
+            entry->offset += TARGET_PAGE_SIZE;
+        } else {
+            QSIMPLEQ_REMOVE_HEAD(&ms->src_page_requests, next_req);
+            g_free(entry);
+        }
+    }
+    qemu_mutex_unlock(&ms->src_page_req_mutex);
+
+    return result;
+}
+
+/*
  * Queue the pages for transmission, e.g. a request from postcopy destination
  *   ms: MigrationStatus in which the queue is held
  *   rbname: The RAMBlock the request is for - may be NULL (to mean reuse last)
@@ -732,46 +779,102 @@ int ram_save_queue_pages(MigrationState *ms, const char *rbname,
 
 static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
 {
+    MigrationState *ms = migrate_get_current();
     RAMBlock *block = last_seen_block;
+    RAMBlock *tmpblock;
     ram_addr_t offset = last_offset;
+    ram_addr_t tmpoffset;
     bool complete_round = false;
     int bytes_sent = 0;
-    MemoryRegion *mr;
     ram_addr_t dirty_ram_abs; /* Address of the start of the dirty page in
                                  ram_addr_t space */
+    unsigned long hps = sysconf(_SC_PAGESIZE);
 
-    if (!block)
+    if (!block) {
         block = QTAILQ_FIRST(&ram_list.blocks);
+        last_was_from_queue = false;
+    }
 
-    while (true) {
-        mr = block->mr;
-        offset = migration_bitmap_find_and_reset_dirty(mr, offset,
-                                                       &dirty_ram_abs);
-        if (complete_round && block == last_seen_block &&
-            offset >= last_offset) {
-            break;
+    while (true) { /* Until we send a block or run out of stuff to send */
+        tmpblock = NULL;
+
+        /*
+         * Don't break host-page chunks up with queue items
+         * so only unqueue if,
+         *   a) The last item came from the queue anyway
+         *   b) The last sent item was the last target-page in a host page
+         */
+        if (last_was_from_queue || !last_sent_block ||
+            ((last_offset & (hps - 1)) == (hps - TARGET_PAGE_SIZE))) {
+            tmpblock = ram_save_unqueue_page(ms, &tmpoffset, &dirty_ram_abs);
         }
-        if (offset >= block->used_length) {
-            offset = 0;
-            block = QTAILQ_NEXT(block, next);
-            if (!block) {
-                block = QTAILQ_FIRST(&ram_list.blocks);
-                complete_round = true;
-                ram_bulk_stage = false;
+
+        if (tmpblock) {
+            /* We've got a block from the postcopy queue */
+            trace_ram_find_and_save_block_postcopy(tmpblock->idstr,
+                                                   (uint64_t)tmpoffset,
+                                                   (uint64_t)dirty_ram_abs);
+            /*
+             * We're sending this page, and since it's postcopy nothing else
+             * will dirty it, and we must make sure it doesn't get sent again.
+             */
+            if (!migration_bitmap_clear_dirty(dirty_ram_abs)) {
+                trace_ram_find_and_save_block_postcopy_not_dirty(
+                    tmpblock->idstr, (uint64_t)tmpoffset,
+                    (uint64_t)dirty_ram_abs,
+                    test_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap));
+
+                continue;
             }
+            /*
+             * As soon as we start servicing pages out of order, then we have
+             * to kill the bulk stage, since the bulk stage assumes
+             * in (migration_bitmap_find_and_reset_dirty) that every page is
+             * dirty, that's no longer true.
+             */
+            ram_bulk_stage = false;
+            /*
+             * We mustn't change block/offset unless it's to a valid one
+             * otherwise we can go down some of the exit cases in the normal
+             * path.
+             */
+            block = tmpblock;
+            offset = tmpoffset;
+            last_was_from_queue = true;
         } else {
-            bytes_sent = ram_save_page(f, block, offset, last_stage);
-
-            /* if page is unmodified, continue to the next */
-            if (bytes_sent > 0) {
-                MigrationState *ms = migrate_get_current();
-                if (ms->sentmap) {
-                    set_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap);
+            MemoryRegion *mr;
+            /* priority queue empty, so just search for something dirty */
+            mr = block->mr;
+            offset = migration_bitmap_find_and_reset_dirty(mr, offset,
+                                                           &dirty_ram_abs);
+            if (complete_round && block == last_seen_block &&
+                offset >= last_offset) {
+                break;
+            }
+            if (offset >= block->used_length) {
+                offset = 0;
+                block = QTAILQ_NEXT(block, next);
+                if (!block) {
+                    block = QTAILQ_FIRST(&ram_list.blocks);
+                    complete_round = true;
+                    ram_bulk_stage = false;
                 }
+                continue; /* pick an offset in the new block */
+            }
+            last_was_from_queue = false;
+        }
 
-                last_sent_block = block;
-                break;
+        /* We have a page to send, so send it */
+        bytes_sent = ram_save_page(f, block, offset, last_stage);
+
+        /* if page is unmodified, continue to the next */
+        if (bytes_sent > 0) {
+            if (ms->sentmap) {
+                set_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap);
             }
+
+            last_sent_block = block;
+            break;
         }
     }
     last_seen_block = block;
@@ -865,6 +968,7 @@ static void reset_ram_globals(void)
     last_offset = 0;
     last_version = ram_list.version;
     ram_bulk_stage = true;
+    last_was_from_queue = false;
 }
 
 #define MAX_WAIT 50 /* ms, half buffered_file limit */
trace-events +2 -0
index 8a0d70d..781cf5c 100644
@@ -1217,6 +1217,8 @@ qemu_file_fclose(void) ""
 migration_bitmap_sync_start(void) ""
 migration_bitmap_sync_end(uint64_t dirty_pages) "dirty_pages %" PRIu64""
 migration_throttle(void) ""
+ram_find_and_save_block_postcopy(const char *block_name, uint64_t tmp_offset, uint64_t ram_addr) "%s/%" PRIx64 " ram_addr=%" PRIx64
+ram_find_and_save_block_postcopy_not_dirty(const char *block_name, uint64_t tmp_offset, uint64_t ram_addr, int sent) "%s/%" PRIx64 " ram_addr=%" PRIx64 " (sent=%d)"
 ram_postcopy_send_discard_bitmap(void) ""
 ram_save_queue_pages(const char *rbname, size_t start, size_t len) "%s: start: %zx len: %zx"
 
Signature · 1 line
2.1.0
#155 lore raw

Re: [Qemu-devel] [PATCH v5 34/45] Page request: Consume pages off the post-copy queue

Quoted 123 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

When transmitting RAM pages, consume pages that have been queued by MIG_RPCOMM_REQPAGE commands and send them ahead of normal page scanning.

Note:
a) After a queued page the linear walk carries on from after the
unqueued page; there is a reasonable chance that the destination was about to ask for other closeby pages anyway.

b) We have to be careful of any assumptions that the page walking
code makes, in particular it does some short cuts on its first linear walk that break as soon as we do a queued page.

---
 arch_init.c  | 154 +++++++++++++++++++++++++++++++++++++++++++++++++----------
 trace-events |   2 +
 2 files changed, 131 insertions(+), 25 deletions(-)
arch_init.c +56 -9
index 9d8fc6b..acf65e1 100644
@@ -328,6 +328,7 @@ static RAMBlock *last_seen_block;
 /* This is the last block from where we have sent data */
 static RAMBlock *last_sent_block;
 static ram_addr_t last_offset;
+static bool last_was_from_queue;
 static unsigned long *migration_bitmap;
 static uint64_t migration_dirty_pages;
 static uint32_t last_version;
@@ -461,6 +462,19 @@ static inline bool migration_bitmap_set_dirty(ram_addr_t addr)
     return ret;
 }
 
+static inline bool migration_bitmap_clear_dirty(ram_addr_t addr)
+{
+    bool ret;
+    int nr = addr >> TARGET_PAGE_BITS;
+
+    ret = test_and_clear_bit(nr, migration_bitmap);
+
+    if (ret) {
+        migration_dirty_pages--;
+    }
+    return ret;
+}
+
 static void migration_bitmap_sync_range(ram_addr_t start, ram_addr_t length)
 {
     ram_addr_t addr;
@@ -669,6 +683,39 @@ static int ram_save_page(QEMUFile *f, RAMBlock* block, ram_addr_t offset,
 }
 
 /*
+ * Unqueue a page from the queue fed by postcopy page requests
+ *
+ * Returns:      The RAMBlock* to transmit from (or NULL if the queue is empty)
+ *      ms:      MigrationState in
+ *  offset:      the byte offset within the RAMBlock for the start of the page
+ * ram_addr_abs: global offset in the dirty/sent bitmaps
+ */
+static RAMBlock *ram_save_unqueue_page(MigrationState *ms, ram_addr_t *offset,
+                                       ram_addr_t *ram_addr_abs)
+{
+    RAMBlock *result = NULL;
+    qemu_mutex_lock(&ms->src_page_req_mutex);
+    if (!QSIMPLEQ_EMPTY(&ms->src_page_requests)) {
+        struct MigrationSrcPageRequest *entry =
+                                    QSIMPLEQ_FIRST(&ms->src_page_requests);
+        result = entry->rb;
+        *offset = entry->offset;
+        *ram_addr_abs = (entry->offset + entry->rb->offset) & TARGET_PAGE_MASK;
+
+        if (entry->len > TARGET_PAGE_SIZE) {
+            entry->len -= TARGET_PAGE_SIZE;
+            entry->offset += TARGET_PAGE_SIZE;
+        } else {
+            QSIMPLEQ_REMOVE_HEAD(&ms->src_page_requests, next_req);
+            g_free(entry);
+        }
+    }
+    qemu_mutex_unlock(&ms->src_page_req_mutex);
+
+    return result;
+}
+
+/*
  * Queue the pages for transmission, e.g. a request from postcopy destination
  *   ms: MigrationStatus in which the queue is held
  *   rbname: The RAMBlock the request is for - may be NULL (to mean reuse last)
@@ -732,46 +779,102 @@ int ram_save_queue_pages(MigrationState *ms, const char *rbname,
 
 static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
 {
+    MigrationState *ms = migrate_get_current();
     RAMBlock *block = last_seen_block;
+    RAMBlock *tmpblock;
     ram_addr_t offset = last_offset;
+    ram_addr_t tmpoffset;
     bool complete_round = false;
     int bytes_sent = 0;
-    MemoryRegion *mr;
     ram_addr_t dirty_ram_abs; /* Address of the start of the dirty page in
                                  ram_addr_t space */
+    unsigned long hps = sysconf(_SC_PAGESIZE);
 
-    if (!block)
+    if (!block) {
         block = QTAILQ_FIRST(&ram_list.blocks);
+        last_was_from_queue = false;
+    }
 
-    while (true) {
-        mr = block->mr;
-        offset = migration_bitmap_find_and_reset_dirty(mr, offset,
-                                                       &dirty_ram_abs);
-        if (complete_round && block == last_seen_block &&
-            offset >= last_offset) {
-            break;
+    while (true) { /* Until we send a block or run out of stuff to send */
+        tmpblock = NULL;

arch_init.c int ram_save_queue_pages(MigrationState *ms, const char *rbname, · line 809

Quoted 10 lines
arch_init.c +10 -0
+
+        /*
+         * Don't break host-page chunks up with queue items
+         * so only unqueue if,
+         *   a) The last item came from the queue anyway
+         *   b) The last sent item was the last target-page in a host page
+         */
+        if (last_was_from_queue || !last_sent_block ||
+            ((last_offset & (hps - 1)) == (hps - TARGET_PAGE_SIZE))) {
+            tmpblock = ram_save_unqueue_page(ms, &tmpoffset, &dirty_ram_abs);

This test for whether we've completed a host page is pretty awkward. I think it would be cleaner to have an inner loop / helper function that completes sending an entire host page (whether requested or scanned), before allowing the outer loop to even come back to here to reconsider the queue.

Quoted 31 lines
arch_init.c +22 -7
         }
-        if (offset >= block->used_length) {
-            offset = 0;
-            block = QTAILQ_NEXT(block, next);
-            if (!block) {
-                block = QTAILQ_FIRST(&ram_list.blocks);
-                complete_round = true;
-                ram_bulk_stage = false;
+
+        if (tmpblock) {
+            /* We've got a block from the postcopy queue */
+            trace_ram_find_and_save_block_postcopy(tmpblock->idstr,
+                                                   (uint64_t)tmpoffset,
+                                                   (uint64_t)dirty_ram_abs);
+            /*
+             * We're sending this page, and since it's postcopy nothing else
+             * will dirty it, and we must make sure it doesn't get sent again.
+             */
+            if (!migration_bitmap_clear_dirty(dirty_ram_abs)) {
+                trace_ram_find_and_save_block_postcopy_not_dirty(
+                    tmpblock->idstr, (uint64_t)tmpoffset,
+                    (uint64_t)dirty_ram_abs,
+                    test_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap));
+
+                continue;
             }
+            /*
+             * As soon as we start servicing pages out of order, then we have
+             * to kill the bulk stage, since the bulk stage assumes
+             * in (migration_bitmap_find_and_reset_dirty) that every page is
+             * dirty, that's no longer true.

arch_init.c int ram_save_queue_pages(MigrationState *ms, const char *rbname, · line 843

Quoted 10 lines
arch_init.c +10 -0
+             */
+            ram_bulk_stage = false;
+            /*
+             * We mustn't change block/offset unless it's to a valid one
+             * otherwise we can go down some of the exit cases in the normal
+             * path.
+             */
+            block = tmpblock;
+            offset = tmpoffset;
+            last_was_from_queue = true;

Hrm. So now block can change during the execution of ram_save_block(), which really suggests that splitting by block is no longer a sensible subdivision of the loop surrounding ram_save_block. I think it would make more sense to replace that entire surrounding loop, so that the logic is essentially

    while (not finished) {
        if (something is queued) {
	    send that
        } else {
	    scan for an unsent block and offset
	    send that instead
	}
Quoted 67 lines
arch_init.c +31 -9
         } else {
-            bytes_sent = ram_save_page(f, block, offset, last_stage);
-
-            /* if page is unmodified, continue to the next */
-            if (bytes_sent > 0) {
-                MigrationState *ms = migrate_get_current();
-                if (ms->sentmap) {
-                    set_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap);
+            MemoryRegion *mr;
+            /* priority queue empty, so just search for something dirty */
+            mr = block->mr;
+            offset = migration_bitmap_find_and_reset_dirty(mr, offset,
+                                                           &dirty_ram_abs);
+            if (complete_round && block == last_seen_block &&
+                offset >= last_offset) {
+                break;
+            }
+            if (offset >= block->used_length) {
+                offset = 0;
+                block = QTAILQ_NEXT(block, next);
+                if (!block) {
+                    block = QTAILQ_FIRST(&ram_list.blocks);
+                    complete_round = true;
+                    ram_bulk_stage = false;
                 }
+                continue; /* pick an offset in the new block */
+            }
+            last_was_from_queue = false;
+        }
 
-                last_sent_block = block;
-                break;
+        /* We have a page to send, so send it */
+        bytes_sent = ram_save_page(f, block, offset, last_stage);
+
+        /* if page is unmodified, continue to the next */
+        if (bytes_sent > 0) {
+            if (ms->sentmap) {
+                set_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap);
             }
+
+            last_sent_block = block;
+            break;
         }
     }
     last_seen_block = block;
@@ -865,6 +968,7 @@ static void reset_ram_globals(void)
     last_offset = 0;
     last_version = ram_list.version;
     ram_bulk_stage = true;
+    last_was_from_queue = false;
 }
 
 #define MAX_WAIT 50 /* ms, half buffered_file limit */
trace-events +2 -0
index 8a0d70d..781cf5c 100644
@@ -1217,6 +1217,8 @@ qemu_file_fclose(void) ""
 migration_bitmap_sync_start(void) ""
 migration_bitmap_sync_end(uint64_t dirty_pages) "dirty_pages %" PRIu64""
 migration_throttle(void) ""
+ram_find_and_save_block_postcopy(const char *block_name, uint64_t tmp_offset, uint64_t ram_addr) "%s/%" PRIx64 " ram_addr=%" PRIx64
+ram_find_and_save_block_postcopy_not_dirty(const char *block_name, uint64_t tmp_offset, uint64_t ram_addr, int sent) "%s/%" PRIx64 " ram_addr=%" PRIx64 " (sent=%d)"
 ram_postcopy_send_discard_bitmap(void) ""
 ram_save_queue_pages(const char *rbname, size_t start, size_t len) "%s: start: %zx len: %zx"
 
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#156 lore raw

Re: [Qemu-devel] [PATCH v5 34/45] Page request: Consume pages off the post-copy queue

Quoted 132 lines · * David Gibson ([email protected]) wrote:
Quoted 131 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

When transmitting RAM pages, consume pages that have been queued by MIG_RPCOMM_REQPAGE commands and send them ahead of normal page scanning.

Note:
a) After a queued page the linear walk carries on from after the
unqueued page; there is a reasonable chance that the destination was about to ask for other closeby pages anyway.

b) We have to be careful of any assumptions that the page walking
code makes, in particular it does some short cuts on its first linear walk that break as soon as we do a queued page.

---
 arch_init.c  | 154 +++++++++++++++++++++++++++++++++++++++++++++++++----------
 trace-events |   2 +
 2 files changed, 131 insertions(+), 25 deletions(-)
arch_init.c +64 -9
index 9d8fc6b..acf65e1 100644
@@ -328,6 +328,7 @@ static RAMBlock *last_seen_block;
 /* This is the last block from where we have sent data */
 static RAMBlock *last_sent_block;
 static ram_addr_t last_offset;
+static bool last_was_from_queue;
 static unsigned long *migration_bitmap;
 static uint64_t migration_dirty_pages;
 static uint32_t last_version;
@@ -461,6 +462,19 @@ static inline bool migration_bitmap_set_dirty(ram_addr_t addr)
     return ret;
 }
 
+static inline bool migration_bitmap_clear_dirty(ram_addr_t addr)
+{
+    bool ret;
+    int nr = addr >> TARGET_PAGE_BITS;
+
+    ret = test_and_clear_bit(nr, migration_bitmap);
+
+    if (ret) {
+        migration_dirty_pages--;
+    }
+    return ret;
+}
+
 static void migration_bitmap_sync_range(ram_addr_t start, ram_addr_t length)
 {
     ram_addr_t addr;
@@ -669,6 +683,39 @@ static int ram_save_page(QEMUFile *f, RAMBlock* block, ram_addr_t offset,
 }
 
 /*
+ * Unqueue a page from the queue fed by postcopy page requests
+ *
+ * Returns:      The RAMBlock* to transmit from (or NULL if the queue is empty)
+ *      ms:      MigrationState in
+ *  offset:      the byte offset within the RAMBlock for the start of the page
+ * ram_addr_abs: global offset in the dirty/sent bitmaps
+ */
+static RAMBlock *ram_save_unqueue_page(MigrationState *ms, ram_addr_t *offset,
+                                       ram_addr_t *ram_addr_abs)
+{
+    RAMBlock *result = NULL;
+    qemu_mutex_lock(&ms->src_page_req_mutex);
+    if (!QSIMPLEQ_EMPTY(&ms->src_page_requests)) {
+        struct MigrationSrcPageRequest *entry =
+                                    QSIMPLEQ_FIRST(&ms->src_page_requests);
+        result = entry->rb;
+        *offset = entry->offset;
+        *ram_addr_abs = (entry->offset + entry->rb->offset) & TARGET_PAGE_MASK;
+
+        if (entry->len > TARGET_PAGE_SIZE) {
+            entry->len -= TARGET_PAGE_SIZE;
+            entry->offset += TARGET_PAGE_SIZE;
+        } else {
+            QSIMPLEQ_REMOVE_HEAD(&ms->src_page_requests, next_req);
+            g_free(entry);
+        }
+    }
+    qemu_mutex_unlock(&ms->src_page_req_mutex);
+
+    return result;
+}
+
+/*
  * Queue the pages for transmission, e.g. a request from postcopy destination
  *   ms: MigrationStatus in which the queue is held
  *   rbname: The RAMBlock the request is for - may be NULL (to mean reuse last)
@@ -732,46 +779,102 @@ int ram_save_queue_pages(MigrationState *ms, const char *rbname,
 
 static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
 {
+    MigrationState *ms = migrate_get_current();
     RAMBlock *block = last_seen_block;
+    RAMBlock *tmpblock;
     ram_addr_t offset = last_offset;
+    ram_addr_t tmpoffset;
     bool complete_round = false;
     int bytes_sent = 0;
-    MemoryRegion *mr;
     ram_addr_t dirty_ram_abs; /* Address of the start of the dirty page in
                                  ram_addr_t space */
+    unsigned long hps = sysconf(_SC_PAGESIZE);
 
-    if (!block)
+    if (!block) {
         block = QTAILQ_FIRST(&ram_list.blocks);
+        last_was_from_queue = false;
+    }
 
-    while (true) {
-        mr = block->mr;
-        offset = migration_bitmap_find_and_reset_dirty(mr, offset,
-                                                       &dirty_ram_abs);
-        if (complete_round && block == last_seen_block &&
-            offset >= last_offset) {
-            break;
+    while (true) { /* Until we send a block or run out of stuff to send */
+        tmpblock = NULL;
+
+        /*
+         * Don't break host-page chunks up with queue items
+         * so only unqueue if,
+         *   a) The last item came from the queue anyway
+         *   b) The last sent item was the last target-page in a host page
+         */
+        if (last_was_from_queue || !last_sent_block ||
Quoted 8 lines

arch_init.c int ram_save_queue_pages(MigrationState *ms, const char *rbname, · line 809

Quoted 2 lines
arch_init.c +2 -0
+            ((last_offset & (hps - 1)) == (hps - TARGET_PAGE_SIZE))) {
+            tmpblock = ram_save_unqueue_page(ms, &tmpoffset, &dirty_ram_abs);

This test for whether we've completed a host page is pretty awkward. I think it would be cleaner to have an inner loop / helper function that completes sending an entire host page (whether requested or scanned), before allowing the outer loop to even come back to here to reconsider the queue.

I've reworked that in the v7 series I've just posted; please see if it's more to your taste (I've not tested it on a machine with bigger pages yet though). (This patch is 32/42 in v7).

Dave

Quoted 111 lines
Quoted 32 lines
arch_init.c +22 -7
         }
-        if (offset >= block->used_length) {
-            offset = 0;
-            block = QTAILQ_NEXT(block, next);
-            if (!block) {
-                block = QTAILQ_FIRST(&ram_list.blocks);
-                complete_round = true;
-                ram_bulk_stage = false;
+
+        if (tmpblock) {
+            /* We've got a block from the postcopy queue */
+            trace_ram_find_and_save_block_postcopy(tmpblock->idstr,
+                                                   (uint64_t)tmpoffset,
+                                                   (uint64_t)dirty_ram_abs);
+            /*
+             * We're sending this page, and since it's postcopy nothing else
+             * will dirty it, and we must make sure it doesn't get sent again.
+             */
+            if (!migration_bitmap_clear_dirty(dirty_ram_abs)) {
+                trace_ram_find_and_save_block_postcopy_not_dirty(
+                    tmpblock->idstr, (uint64_t)tmpoffset,
+                    (uint64_t)dirty_ram_abs,
+                    test_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap));
+
+                continue;
             }
+            /*
+             * As soon as we start servicing pages out of order, then we have
+             * to kill the bulk stage, since the bulk stage assumes
+             * in (migration_bitmap_find_and_reset_dirty) that every page is
+             * dirty, that's no longer true.

arch_init.c int ram_save_queue_pages(MigrationState *ms, const char *rbname, · line 843

Quoted 10 lines
arch_init.c +10 -0
+             */
+            ram_bulk_stage = false;
+            /*
+             * We mustn't change block/offset unless it's to a valid one
+             * otherwise we can go down some of the exit cases in the normal
+             * path.
+             */
+            block = tmpblock;
+            offset = tmpoffset;
+            last_was_from_queue = true;

Hrm. So now block can change during the execution of ram_save_block(), which really suggests that splitting by block is no longer a sensible subdivision of the loop surrounding ram_save_block. I think it would make more sense to replace that entire surrounding loop, so that the logic is essentially

    while (not finished) {
        if (something is queued) {
	    send that
        } else {
	    scan for an unsent block and offset
	    send that instead
	}
Quoted 53 lines
arch_init.c +31 -9
         } else {
-            bytes_sent = ram_save_page(f, block, offset, last_stage);
-
-            /* if page is unmodified, continue to the next */
-            if (bytes_sent > 0) {
-                MigrationState *ms = migrate_get_current();
-                if (ms->sentmap) {
-                    set_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap);
+            MemoryRegion *mr;
+            /* priority queue empty, so just search for something dirty */
+            mr = block->mr;
+            offset = migration_bitmap_find_and_reset_dirty(mr, offset,
+                                                           &dirty_ram_abs);
+            if (complete_round && block == last_seen_block &&
+                offset >= last_offset) {
+                break;
+            }
+            if (offset >= block->used_length) {
+                offset = 0;
+                block = QTAILQ_NEXT(block, next);
+                if (!block) {
+                    block = QTAILQ_FIRST(&ram_list.blocks);
+                    complete_round = true;
+                    ram_bulk_stage = false;
                 }
+                continue; /* pick an offset in the new block */
+            }
+            last_was_from_queue = false;
+        }
 
-                last_sent_block = block;
-                break;
+        /* We have a page to send, so send it */
+        bytes_sent = ram_save_page(f, block, offset, last_stage);
+
+        /* if page is unmodified, continue to the next */
+        if (bytes_sent > 0) {
+            if (ms->sentmap) {
+                set_bit(dirty_ram_abs >> TARGET_PAGE_BITS, ms->sentmap);
             }
+
+            last_sent_block = block;
+            break;
         }
     }
     last_seen_block = block;
@@ -865,6 +968,7 @@ static void reset_ram_globals(void)
     last_offset = 0;
     last_version = ram_list.version;
     ram_bulk_stage = true;
+    last_was_from_queue = false;
 }
 
Quoted 20 lines
Quoted 14 lines
arch_init.c +0 -0
 #define MAX_WAIT 50 /* ms, half buffered_file limit */
trace-events +2 -0
index 8a0d70d..781cf5c 100644
@@ -1217,6 +1217,8 @@ qemu_file_fclose(void) ""
 migration_bitmap_sync_start(void) ""
 migration_bitmap_sync_end(uint64_t dirty_pages) "dirty_pages %" PRIu64""
 migration_throttle(void) ""
+ram_find_and_save_block_postcopy(const char *block_name, uint64_t tmp_offset, uint64_t ram_addr) "%s/%" PRIx64 " ram_addr=%" PRIx64
+ram_find_and_save_block_postcopy_not_dirty(const char *block_name, uint64_t tmp_offset, uint64_t ram_addr, int sent) "%s/%" PRIx64 " ram_addr=%" PRIx64 " (sent=%d)"
 ram_postcopy_send_discard_bitmap(void) ""
 ram_save_queue_pages(const char *rbname, size_t start, size_t len) "%s: start: %zx len: %zx"
 
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#157 lore raw

PATCH v5 35/45 postcopy_ram.c: place_page and helpers

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

postcopy_place_page (etc) provide a way for postcopy to place a page into guests memory atomically (using the copy ioctl on the ufd).

---
 include/migration/migration.h    |   2 +
 include/migration/postcopy-ram.h |  16 ++++++
 migration/postcopy-ram.c         | 113 ++++++++++++++++++++++++++++++++++++++-
 trace-events                     |   1 +
 4 files changed, 130 insertions(+), 2 deletions(-)
include/migration/migration.h +2 -0
index b1c7cad..139bb1b 100644
@@ -94,6 +94,8 @@ struct MigrationIncomingState {
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
     PostcopyPMI    postcopy_pmi;
+    void          *postcopy_tmp_page;
+    long           postcopy_place_skipped; /* Check for incorrect place ops */
 };
 
 MigrationIncomingState *migration_incoming_get_current(void);
include/migration/postcopy-ram.h +16 -0
index fbb2a93..3d30280 100644
@@ -80,4 +80,20 @@ void postcopy_discard_send_chunk(MigrationState *ms, PostcopyDiscardState *pds,
 void postcopy_discard_send_finish(MigrationState *ms,
                                   PostcopyDiscardState *pds);
 
+/*
+ * Place a page (from) at (host) efficiently
+ *    There are restrictions on how 'from' must be mapped, in general best
+ *    to use other postcopy_ routines to allocate.
+ * returns 0 on success
+ */
+int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
+                        long bitmap_offset, bool all_zero);
+
+/*
+ * Allocate a page of memory that can be mapped at a later point in time
+ * using postcopy_place_page
+ * Returns: Pointer to allocated page
+ */
+void *postcopy_get_tmp_page(MigrationIncomingState *mis);
+
 #endif
migration/postcopy-ram.c +111 -2

149 lines not on this page · raw message

trace-events +1 -0
index 781cf5c..16a91d9 100644
@@ -1497,6 +1497,7 @@ rdma_start_outgoing_migration_after_rdma_source_init(void) ""
 postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s mask words sent=%d in %d commands"
 postcopy_cleanup_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 postcopy_init_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
+postcopy_place_page(unsigned long offset, void *host_addr, bool all_zero, int old_state) "offset=%lx host=%p all_zero=%d old_state=%d"
 
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 1 line
2.1.0
#158 lore raw

Re: [Qemu-devel] [PATCH v5 35/45] postcopy_ram.c: place_page and helpers

Quoted 91 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

postcopy_place_page (etc) provide a way for postcopy to place a page into guests memory atomically (using the copy ioctl on the ufd).

---
 include/migration/migration.h    |   2 +
 include/migration/postcopy-ram.h |  16 ++++++
 migration/postcopy-ram.c         | 113 ++++++++++++++++++++++++++++++++++++++-
 trace-events                     |   1 +
 4 files changed, 130 insertions(+), 2 deletions(-)
include/migration/migration.h +2 -0
index b1c7cad..139bb1b 100644
@@ -94,6 +94,8 @@ struct MigrationIncomingState {
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
     PostcopyPMI    postcopy_pmi;
+    void          *postcopy_tmp_page;
+    long           postcopy_place_skipped; /* Check for incorrect place ops */
 };
 
 MigrationIncomingState *migration_incoming_get_current(void);
include/migration/postcopy-ram.h +16 -0
index fbb2a93..3d30280 100644
@@ -80,4 +80,20 @@ void postcopy_discard_send_chunk(MigrationState *ms, PostcopyDiscardState *pds,
 void postcopy_discard_send_finish(MigrationState *ms,
                                   PostcopyDiscardState *pds);
 
+/*
+ * Place a page (from) at (host) efficiently
+ *    There are restrictions on how 'from' must be mapped, in general best
+ *    to use other postcopy_ routines to allocate.
+ * returns 0 on success
+ */
+int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
+                        long bitmap_offset, bool all_zero);
+
+/*
+ * Allocate a page of memory that can be mapped at a later point in time
+ * using postcopy_place_page
+ * Returns: Pointer to allocated page
+ */
+void *postcopy_get_tmp_page(MigrationIncomingState *mis);
+
 #endif
migration/postcopy-ram.c +5 -2
index 33dd332..86fa5a0 100644
@@ -197,7 +197,6 @@ static PostcopyPMIState postcopy_pmi_get_state_nolock(
 }
 
 /* Retrieve the state of the given page */
-__attribute__ (( unused )) /* Until later in patch series */
 static PostcopyPMIState postcopy_pmi_get_state(MigrationIncomingState *mis,
                                                size_t bitmap_index)
 {
@@ -213,7 +212,6 @@ static PostcopyPMIState postcopy_pmi_get_state(MigrationIncomingState *mis,
  * Set the page state to the given state if the previous state was as expected
  * Return the actual previous state.
  */
-__attribute__ (( unused )) /* Until later in patch series */
 static PostcopyPMIState postcopy_pmi_change_state(MigrationIncomingState *mis,
                                            size_t bitmap_index,
                                            PostcopyPMIState expected_state,
@@ -477,6 +475,7 @@ static int cleanup_area(const char *block_name, void *host_addr,
 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
 {
     postcopy_pmi_init(mis, ram_pages);
+    mis->postcopy_place_skipped = -1;
 
     if (qemu_ram_foreach_block(init_area, mis)) {
         return -1;
@@ -495,6 +494,10 @@ int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
         return -1;
     }
 
+    if (mis->postcopy_tmp_page) {
+        munmap(mis->postcopy_tmp_page, getpagesize());
+        mis->postcopy_tmp_page = NULL;
+    }
     return 0;
 }
 

migration/postcopy-ram.c int postcopy_ram_enable_notify(MigrationIncomingState *mis) · line 568

Quoted 5 lines
migration/postcopy-ram.c +2 -0
@@ -561,6 +564,100 @@ int postcopy_ram_enable_notify(MigrationIncomingState *mis)
     return 0;
 }
 
+/*
+ * Place a host page (from) at (host) tomically

s/tomically/atomically/

migration/postcopy-ram.c int postcopy_ram_enable_notify(MigrationIncomingState *mis) · line 580

Quoted 12 lines
migration/postcopy-ram.c +12 -0
+ *    There are restrictions on how 'from' must be mapped, in general best
+ *    to use other postcopy_ routines to allocate.
+ * all_zero: Hint that the page being placed is 0 throughout
+ * returns 0 on success
+ * bitmap_offset: Index into the migration bitmaps
+ *
+ * State changes:
+ *   none -> received
+ *   requested -> received (ack)
+ *
+ * Note the UF thread is also updating the state, and maybe none->requested
+ * at the same time.

Hrm.. these facts do tend me towards thinking that separate and explicit requested and received bits will be clearer than treating it as an enum state variable

Quoted 42 lines
migration/postcopy-ram.c +42 -0
+ */
+int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
+                        long bitmap_offset, bool all_zero)
+{
+    PostcopyPMIState old_state, tmp_state, new_state;
+
+    if (!all_zero) {
+        struct uffdio_copy copy_struct;
+
+        copy_struct.dst = (uint64_t)(uintptr_t)host;
+        copy_struct.src = (uint64_t)(uintptr_t)from;
+        copy_struct.len = getpagesize();
+        copy_struct.mode = 0;
+
+        /* copy also acks to the kernel waking the stalled thread up
+         * TODO: We can inhibit that ack and only do it if it was requested
+         * which would be slightly cheaper, but we'd have to be careful
+         * of the order of updating our page state.
+         */
+        if (ioctl(mis->userfault_fd, UFFDIO_COPY, &copy_struct)) {
+            int e = errno;
+            error_report("%s: %s copy host: %p from: %p pmi=%d",
+                         __func__, strerror(e), host, from,
+                         postcopy_pmi_get_state(mis, bitmap_offset));
+
+            return -e;
+        }
+    } else {
+        struct uffdio_zeropage zero_struct;
+
+        zero_struct.range.start = (uint64_t)(uintptr_t)host;
+        zero_struct.range.len = getpagesize();
+        zero_struct.mode = 0;
+
+        if (ioctl(mis->userfault_fd, UFFDIO_ZEROPAGE, &zero_struct)) {
+            int e = errno;
+            error_report("%s: %s zero host: %p from: %p pmi=%d",
+                         __func__, strerror(e), host, from,
+                         postcopy_pmi_get_state(mis, bitmap_offset));
+
+            return -e;
+        }

migration/postcopy-ram.c int postcopy_ram_enable_notify(MigrationIncomingState *mis) · line 632

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+    }
+
+    bitmap_offset &= ~(mis->postcopy_pmi.host_bits-1);
+    new_state = POSTCOPY_PMI_RECEIVED;
+    tmp_state = postcopy_pmi_get_state(mis, bitmap_offset);
+    do {
+        old_state = tmp_state;
+        tmp_state = postcopy_pmi_change_state(mis, bitmap_offset, old_state,
+                                              new_state);
+    } while (old_state != tmp_state);

Yeah.. see treating the state as two separate booleans, here you'd just need to update received, without caring about whether requested has changed.

Quoted 62 lines
migration/postcopy-ram.c +40 -0
+    trace_postcopy_place_page(bitmap_offset, host, all_zero, old_state);
+
+    return 0;
+}
+
+/*
+ * Returns a target page of memory that can be mapped at a later point in time
+ * using postcopy_place_page
+ * The same address is used repeatedly, postcopy_place_page just takes the
+ * backing page away.
+ * Returns: Pointer to allocated page
+ *
+ */
+void *postcopy_get_tmp_page(MigrationIncomingState *mis)
+{
+    if (!mis->postcopy_tmp_page) {
+        mis->postcopy_tmp_page = mmap(NULL, getpagesize(),
+                             PROT_READ | PROT_WRITE, MAP_PRIVATE |
+                             MAP_ANONYMOUS, -1, 0);
+        if (!mis->postcopy_tmp_page) {
+            perror("mapping postcopy tmp page");
+            return NULL;
+        }
+    }
+
+    return mis->postcopy_tmp_page;
+}
+
 #else
 /* No target OS support, stubs just fail */
 bool postcopy_ram_supported_by_host(void)
@@ -608,6 +705,18 @@ int postcopy_ram_enable_notify(MigrationIncomingState *mis)
 {
     assert(0);
 }
+
+int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
+                        long bitmap_offset, bool all_zero)
+{
+    assert(0);
+}
+
+void *postcopy_get_tmp_page(MigrationIncomingState *mis)
+{
+    assert(0);
+}
+
 #endif
 
 /* ------------------------------------------------------------------------- */
trace-events +1 -0
index 781cf5c..16a91d9 100644
@@ -1497,6 +1497,7 @@ rdma_start_outgoing_migration_after_rdma_source_init(void) ""
 postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s mask words sent=%d in %d commands"
 postcopy_cleanup_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 postcopy_init_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
+postcopy_place_page(unsigned long offset, void *host_addr, bool all_zero, int old_state) "offset=%lx host=%p all_zero=%d old_state=%d"
 
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#159 lore raw

Re: [Qemu-devel] [PATCH v5 35/45] postcopy_ram.c: place_page and helpers

Quoted 91 lines · * David Gibson ([email protected]) wrote:
Quoted 90 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

postcopy_place_page (etc) provide a way for postcopy to place a page into guests memory atomically (using the copy ioctl on the ufd).

---
 include/migration/migration.h    |   2 +
 include/migration/postcopy-ram.h |  16 ++++++
 migration/postcopy-ram.c         | 113 ++++++++++++++++++++++++++++++++++++++-
 trace-events                     |   1 +
 4 files changed, 130 insertions(+), 2 deletions(-)
include/migration/migration.h +2 -0
index b1c7cad..139bb1b 100644
@@ -94,6 +94,8 @@ struct MigrationIncomingState {
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
     PostcopyPMI    postcopy_pmi;
+    void          *postcopy_tmp_page;
+    long           postcopy_place_skipped; /* Check for incorrect place ops */
 };
 
 MigrationIncomingState *migration_incoming_get_current(void);
include/migration/postcopy-ram.h +16 -0
index fbb2a93..3d30280 100644
@@ -80,4 +80,20 @@ void postcopy_discard_send_chunk(MigrationState *ms, PostcopyDiscardState *pds,
 void postcopy_discard_send_finish(MigrationState *ms,
                                   PostcopyDiscardState *pds);
 
+/*
+ * Place a page (from) at (host) efficiently
+ *    There are restrictions on how 'from' must be mapped, in general best
+ *    to use other postcopy_ routines to allocate.
+ * returns 0 on success
+ */
+int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
+                        long bitmap_offset, bool all_zero);
+
+/*
+ * Allocate a page of memory that can be mapped at a later point in time
+ * using postcopy_place_page
+ * Returns: Pointer to allocated page
+ */
+void *postcopy_get_tmp_page(MigrationIncomingState *mis);
+
 #endif
migration/postcopy-ram.c +5 -2
index 33dd332..86fa5a0 100644
@@ -197,7 +197,6 @@ static PostcopyPMIState postcopy_pmi_get_state_nolock(
 }
 
 /* Retrieve the state of the given page */
-__attribute__ (( unused )) /* Until later in patch series */
 static PostcopyPMIState postcopy_pmi_get_state(MigrationIncomingState *mis,
                                                size_t bitmap_index)
 {
@@ -213,7 +212,6 @@ static PostcopyPMIState postcopy_pmi_get_state(MigrationIncomingState *mis,
  * Set the page state to the given state if the previous state was as expected
  * Return the actual previous state.
  */
-__attribute__ (( unused )) /* Until later in patch series */
 static PostcopyPMIState postcopy_pmi_change_state(MigrationIncomingState *mis,
                                            size_t bitmap_index,
                                            PostcopyPMIState expected_state,
@@ -477,6 +475,7 @@ static int cleanup_area(const char *block_name, void *host_addr,
 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
 {
     postcopy_pmi_init(mis, ram_pages);
+    mis->postcopy_place_skipped = -1;
 
     if (qemu_ram_foreach_block(init_area, mis)) {
         return -1;
@@ -495,6 +494,10 @@ int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
         return -1;
     }
 
+    if (mis->postcopy_tmp_page) {
+        munmap(mis->postcopy_tmp_page, getpagesize());
+        mis->postcopy_tmp_page = NULL;
+    }
     return 0;
 }
 
Quoted 8 lines

migration/postcopy-ram.c int postcopy_ram_enable_notify(MigrationIncomingState *mis) · line 568

Quoted 6 lines
migration/postcopy-ram.c +2 -0
@@ -561,6 +564,100 @@ int postcopy_ram_enable_notify(MigrationIncomingState *mis)
     return 0;
 }
 
+/*
+ * Place a host page (from) at (host) tomically

s/tomically/atomically/

Done.

Quoted 13 lines

migration/postcopy-ram.c int postcopy_ram_enable_notify(MigrationIncomingState *mis) · line 580

Quoted 12 lines
migration/postcopy-ram.c +12 -0
+ *    There are restrictions on how 'from' must be mapped, in general best
+ *    to use other postcopy_ routines to allocate.
+ * all_zero: Hint that the page being placed is 0 throughout
+ * returns 0 on success
+ * bitmap_offset: Index into the migration bitmaps
+ *
+ * State changes:
+ *   none -> received
+ *   requested -> received (ack)
+ *
+ * Note the UF thread is also updating the state, and maybe none->requested
+ * at the same time.
Quoted 3 lines

Hrm.. these facts do tend me towards thinking that separate and explicit requested and received bits will be clearer than treating it as an enum state variable

This is all about to get simpler; Andrea realised he can make a small change to the kernel interface semantics that means that I no longer have to keep the destination side bitmaps. That saves all this messing about updating page states at all.

Quoted 48 lines
Quoted 48 lines
migration/postcopy-ram.c +48 -0
+ */
+int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
+                        long bitmap_offset, bool all_zero)
+{
+    PostcopyPMIState old_state, tmp_state, new_state;
+
+    if (!all_zero) {
+        struct uffdio_copy copy_struct;
+
+        copy_struct.dst = (uint64_t)(uintptr_t)host;
+        copy_struct.src = (uint64_t)(uintptr_t)from;
+        copy_struct.len = getpagesize();
+        copy_struct.mode = 0;
+
+        /* copy also acks to the kernel waking the stalled thread up
+         * TODO: We can inhibit that ack and only do it if it was requested
+         * which would be slightly cheaper, but we'd have to be careful
+         * of the order of updating our page state.
+         */
+        if (ioctl(mis->userfault_fd, UFFDIO_COPY, &copy_struct)) {
+            int e = errno;
+            error_report("%s: %s copy host: %p from: %p pmi=%d",
+                         __func__, strerror(e), host, from,
+                         postcopy_pmi_get_state(mis, bitmap_offset));
+
+            return -e;
+        }
+    } else {
+        struct uffdio_zeropage zero_struct;
+
+        zero_struct.range.start = (uint64_t)(uintptr_t)host;
+        zero_struct.range.len = getpagesize();
+        zero_struct.mode = 0;
+
+        if (ioctl(mis->userfault_fd, UFFDIO_ZEROPAGE, &zero_struct)) {
+            int e = errno;
+            error_report("%s: %s zero host: %p from: %p pmi=%d",
+                         __func__, strerror(e), host, from,
+                         postcopy_pmi_get_state(mis, bitmap_offset));
+
+            return -e;
+        }
+    }
+
+    bitmap_offset &= ~(mis->postcopy_pmi.host_bits-1);
+    new_state = POSTCOPY_PMI_RECEIVED;
+    tmp_state = postcopy_pmi_get_state(mis, bitmap_offset);
+    do {
Quoted 8 lines

migration/postcopy-ram.c int postcopy_ram_enable_notify(MigrationIncomingState *mis) · line 632

Quoted 4 lines
migration/postcopy-ram.c +4 -0
+        old_state = tmp_state;
+        tmp_state = postcopy_pmi_change_state(mis, bitmap_offset, old_state,
+                                              new_state);
+    } while (old_state != tmp_state);

Yeah.. see treating the state as two separate booleans, here you'd just need to update received, without caring about whether requested has changed.

It's all very dependent on the exact things you need to do with the states; whenever you get into a situation where you have to do something on a combination of the bits you suddenly have to be a lot more careful.

Anyway, as I say, both of those bits are about to disappear.

Dave

Quoted 61 lines
Quoted 61 lines
migration/postcopy-ram.c +40 -0
+    trace_postcopy_place_page(bitmap_offset, host, all_zero, old_state);
+
+    return 0;
+}
+
+/*
+ * Returns a target page of memory that can be mapped at a later point in time
+ * using postcopy_place_page
+ * The same address is used repeatedly, postcopy_place_page just takes the
+ * backing page away.
+ * Returns: Pointer to allocated page
+ *
+ */
+void *postcopy_get_tmp_page(MigrationIncomingState *mis)
+{
+    if (!mis->postcopy_tmp_page) {
+        mis->postcopy_tmp_page = mmap(NULL, getpagesize(),
+                             PROT_READ | PROT_WRITE, MAP_PRIVATE |
+                             MAP_ANONYMOUS, -1, 0);
+        if (!mis->postcopy_tmp_page) {
+            perror("mapping postcopy tmp page");
+            return NULL;
+        }
+    }
+
+    return mis->postcopy_tmp_page;
+}
+
 #else
 /* No target OS support, stubs just fail */
 bool postcopy_ram_supported_by_host(void)
@@ -608,6 +705,18 @@ int postcopy_ram_enable_notify(MigrationIncomingState *mis)
 {
     assert(0);
 }
+
+int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
+                        long bitmap_offset, bool all_zero)
+{
+    assert(0);
+}
+
+void *postcopy_get_tmp_page(MigrationIncomingState *mis)
+{
+    assert(0);
+}
+
 #endif
 
 /* ------------------------------------------------------------------------- */
trace-events +1 -0
index 781cf5c..16a91d9 100644
@@ -1497,6 +1497,7 @@ rdma_start_outgoing_migration_after_rdma_source_init(void) ""
 postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s mask words sent=%d in %d commands"
 postcopy_cleanup_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 postcopy_init_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
+postcopy_place_page(unsigned long offset, void *host_addr, bool all_zero, int old_state) "offset=%lx host=%p all_zero=%d old_state=%d"
 
Quoted 8 lines
Quoted 2 lines
trace-events +0 -0
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#160 lore raw

PATCH v5 36/45 Postcopy: Use helpers to map pages during migration

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

In postcopy, the destination guest is running at the same time as it's receiving pages; as we receive new pages we must put them into the guests address space atomically to avoid a running CPU accessing a partially written page.

Use the helpers in postcopy-ram.c to map these pages.

Note, gcc 4.9.2 is giving me false uninitialized warnings in ram_load's switch, so anything conditionally set at the start of the switch needs initializing; filed as
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64614

---
 arch_init.c | 137 ++++++++++++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 111 insertions(+), 26 deletions(-)
arch_init.c +111 -26
index acf65e1..7a1c9ea 100644
@@ -1479,9 +1479,39 @@ static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
     return 0;
 }
 
+/*
+ * Helper for host_from_stream_offset in the succesful case.
+ * Returns the host pointer for the given block and offset
+ *   calling the postcopy hook and filling in *rb.
+ */
+static void *host_with_postcopy_hook(MigrationIncomingState *mis,
+                                     ram_addr_t offset,
+                                     RAMBlock *block,
+                                     RAMBlock **rb)
+{
+    if (rb) {
+        *rb = block;
+    }
+
+    postcopy_hook_early_receive(mis,
+        (offset + block->offset) >> TARGET_PAGE_BITS);
+    return memory_region_get_ram_ptr(block->mr) + offset;
+}
+
+/*
+ * Read a RAMBlock ID from the stream f, find the host address of the
+ * start of that block and add on 'offset'
+ *
+ * f: Stream to read from
+ * mis: MigrationIncomingState
+ * offset: Offset within the block
+ * flags: Page flags (mostly to see if it's a continuation of previous block)
+ * rb: Pointer to RAMBlock* that gets filled in with the RB we find
+ */
 static inline void *host_from_stream_offset(QEMUFile *f,
+                                            MigrationIncomingState *mis,
                                             ram_addr_t offset,
-                                            int flags)
+                                            int flags, RAMBlock **rb)
 {
     static RAMBlock *block = NULL;
     char id[256];
@@ -1492,8 +1522,7 @@ static inline void *host_from_stream_offset(QEMUFile *f,
             error_report("Ack, bad migration stream!");
             return NULL;
         }
-
-        return memory_region_get_ram_ptr(block->mr) + offset;
+        return host_with_postcopy_hook(mis, offset, block, rb);
     }
 
     len = qemu_get_byte(f);
@@ -1503,7 +1532,7 @@ static inline void *host_from_stream_offset(QEMUFile *f,
     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
         if (!strncmp(id, block->idstr, sizeof(id)) &&
             block->max_length > offset) {
-            return memory_region_get_ram_ptr(block->mr) + offset;
+            return host_with_postcopy_hook(mis, offset, block, rb);
         }
     }
 
@@ -1537,6 +1566,15 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)
 {
     int flags = 0, ret = 0;
     static uint64_t seq_iter;
+    /*
+     * System is running in postcopy mode, page inserts to host memory must be
+     * atomic
+     */
+    MigrationIncomingState *mis = migration_incoming_get_current();
+    bool postcopy_running = postcopy_state_get(mis) >=
+                            POSTCOPY_INCOMING_LISTENING;
+    void *postcopy_host_page = NULL;
+    bool postcopy_place_needed = false;
 
     seq_iter++;
 
@@ -1545,14 +1583,57 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)
     }
 
     while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
+        RAMBlock *rb = 0; /* =0 needed to silence compiler */
         ram_addr_t addr, total_ram_bytes;
-        void *host;
+        void *host = 0;
+        void *page_buffer = 0;
         uint8_t ch;
+        bool all_zero = false;
 
         addr = qemu_get_be64(f);
         flags = addr & ~TARGET_PAGE_MASK;
         addr &= TARGET_PAGE_MASK;
 
+        if (flags & (RAM_SAVE_FLAG_COMPRESS | RAM_SAVE_FLAG_PAGE |
+                     RAM_SAVE_FLAG_XBZRLE)) {
+            host = host_from_stream_offset(f, mis, addr, flags, &rb);
+            if (!host) {
+                error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
+                ret = -EINVAL;
+                break;
+            }
+            if (!postcopy_running) {
+                page_buffer = host;
+            } else {
+                /*
+                 * Postcopy requires that we place whole host pages atomically.
+                 * To make it atomic, the data is read into a temporary page
+                 * that's moved into place later.
+                 * The migration protocol uses,  possibly smaller, target-pages
+                 * however the source ensures it always sends all the components
+                 * of a host page in order.
+                 */
+                if (!postcopy_host_page) {
+                    postcopy_host_page = postcopy_get_tmp_page(mis);
+                }
+                page_buffer = postcopy_host_page +
+                              ((uintptr_t)host & ~qemu_host_page_mask);
+                /* If all TP are zero then we can optimise the place */
+                if (!((uintptr_t)host & ~qemu_host_page_mask)) {
+                    all_zero = true;
+                }
+
+                /*
+                 * If it's the last part of a host page then we place the host
+                 * page
+                 */
+                postcopy_place_needed = (((uintptr_t)host + TARGET_PAGE_SIZE) &
+                                         ~qemu_host_page_mask) == 0;
+            }
+        } else {
+            postcopy_place_needed = false;
+        }
+
         switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
         case RAM_SAVE_FLAG_MEM_SIZE:
             /* Synchronize RAM block list */
@@ -1590,32 +1671,27 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)
             }
             break;
         case RAM_SAVE_FLAG_COMPRESS:
-            host = host_from_stream_offset(f, addr, flags);
-            if (!host) {
-                error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
-                ret = -EINVAL;
-                break;
-            }
-
             ch = qemu_get_byte(f);
-            ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
-            break;
-        case RAM_SAVE_FLAG_PAGE:
-            host = host_from_stream_offset(f, addr, flags);
-            if (!host) {
-                error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
-                ret = -EINVAL;
-                break;
+            if (!postcopy_running) {
+                ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
+            } else {
+                memset(page_buffer, ch, TARGET_PAGE_SIZE);
+                if (ch) {
+                    all_zero = false;
+                }
             }
+            break;
 
-            qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
+        case RAM_SAVE_FLAG_PAGE:
+            all_zero = false;
+            qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
             break;
+
         case RAM_SAVE_FLAG_XBZRLE:
-            host = host_from_stream_offset(f, addr, flags);
-            if (!host) {
-                error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
-                ret = -EINVAL;
-                break;
+            all_zero = false;
+            if (postcopy_running) {
+                error_report("XBZRLE RAM block in postcopy mode @%zx\n", addr);
+                return -EINVAL;
             }
 
             if (load_xbzrle(f, addr, host) < 0) {
@@ -1637,6 +1713,15 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)
                 ret = -EINVAL;
             }
         }
+
+        if (postcopy_place_needed) {
+            /* This gets called at the last target page in the host page */
+            ret = postcopy_place_page(mis, host + TARGET_PAGE_SIZE -
+                                           qemu_host_page_size,
+                                      postcopy_host_page,
+                                      (addr + rb->offset) >> TARGET_PAGE_BITS,
+                                      all_zero);
+        }
         if (!ret) {
             ret = qemu_file_get_error(f);
         }
Signature · 1 line
2.1.0
#161 lore raw

Re: [Qemu-devel] [PATCH v5 36/45] Postcopy: Use helpers to map pages during migration

Quoted 33 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

In postcopy, the destination guest is running at the same time as it's receiving pages; as we receive new pages we must put them into the guests address space atomically to avoid a running CPU accessing a partially written page.

Use the helpers in postcopy-ram.c to map these pages.

Note, gcc 4.9.2 is giving me false uninitialized warnings in ram_load's switch, so anything conditionally set at the start of the switch needs initializing; filed as
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64614

---
 arch_init.c | 137 ++++++++++++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 111 insertions(+), 26 deletions(-)
arch_init.c +6 -0
index acf65e1..7a1c9ea 100644
@@ -1479,9 +1479,39 @@ static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
     return 0;
 }
 
+/*
+ * Helper for host_from_stream_offset in the succesful case.
+ * Returns the host pointer for the given block and offset
+ *   calling the postcopy hook and filling in *rb.
+ */
+static void *host_with_postcopy_hook(MigrationIncomingState *mis,

arch_init.c static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host) · line 1497

Quoted 10 lines
arch_init.c +10 -0
+                                     ram_addr_t offset,
+                                     RAMBlock *block,
+                                     RAMBlock **rb)
+{
+    if (rb) {
+        *rb = block;
+    }
+
+    postcopy_hook_early_receive(mis,
+        (offset + block->offset) >> TARGET_PAGE_BITS);

What does postcopy_hook_early_receive() do?

Quoted 95 lines
arch_init.c +53 -5
+    return memory_region_get_ram_ptr(block->mr) + offset;
+}
+
+/*
+ * Read a RAMBlock ID from the stream f, find the host address of the
+ * start of that block and add on 'offset'
+ *
+ * f: Stream to read from
+ * mis: MigrationIncomingState
+ * offset: Offset within the block
+ * flags: Page flags (mostly to see if it's a continuation of previous block)
+ * rb: Pointer to RAMBlock* that gets filled in with the RB we find
+ */
 static inline void *host_from_stream_offset(QEMUFile *f,
+                                            MigrationIncomingState *mis,
                                             ram_addr_t offset,
-                                            int flags)
+                                            int flags, RAMBlock **rb)
 {
     static RAMBlock *block = NULL;
     char id[256];
@@ -1492,8 +1522,7 @@ static inline void *host_from_stream_offset(QEMUFile *f,
             error_report("Ack, bad migration stream!");
             return NULL;
         }
-
-        return memory_region_get_ram_ptr(block->mr) + offset;
+        return host_with_postcopy_hook(mis, offset, block, rb);
     }
 
     len = qemu_get_byte(f);
@@ -1503,7 +1532,7 @@ static inline void *host_from_stream_offset(QEMUFile *f,
     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
         if (!strncmp(id, block->idstr, sizeof(id)) &&
             block->max_length > offset) {
-            return memory_region_get_ram_ptr(block->mr) + offset;
+            return host_with_postcopy_hook(mis, offset, block, rb);
         }
     }
 
@@ -1537,6 +1566,15 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)
 {
     int flags = 0, ret = 0;
     static uint64_t seq_iter;
+    /*
+     * System is running in postcopy mode, page inserts to host memory must be
+     * atomic
+     */
+    MigrationIncomingState *mis = migration_incoming_get_current();
+    bool postcopy_running = postcopy_state_get(mis) >=
+                            POSTCOPY_INCOMING_LISTENING;
+    void *postcopy_host_page = NULL;
+    bool postcopy_place_needed = false;
 
     seq_iter++;
 
@@ -1545,14 +1583,57 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)
     }
 
     while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
+        RAMBlock *rb = 0; /* =0 needed to silence compiler */
         ram_addr_t addr, total_ram_bytes;
-        void *host;
+        void *host = 0;
+        void *page_buffer = 0;
         uint8_t ch;
+        bool all_zero = false;
 
         addr = qemu_get_be64(f);
         flags = addr & ~TARGET_PAGE_MASK;
         addr &= TARGET_PAGE_MASK;
 
+        if (flags & (RAM_SAVE_FLAG_COMPRESS | RAM_SAVE_FLAG_PAGE |
+                     RAM_SAVE_FLAG_XBZRLE)) {
+            host = host_from_stream_offset(f, mis, addr, flags, &rb);
+            if (!host) {
+                error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
+                ret = -EINVAL;
+                break;
+            }
+            if (!postcopy_running) {
+                page_buffer = host;
+            } else {
+                /*
+                 * Postcopy requires that we place whole host pages atomically.
+                 * To make it atomic, the data is read into a temporary page
+                 * that's moved into place later.
+                 * The migration protocol uses,  possibly smaller, target-pages
+                 * however the source ensures it always sends all the components
+                 * of a host page in order.
+                 */
+                if (!postcopy_host_page) {
+                    postcopy_host_page = postcopy_get_tmp_page(mis);
+                }
+                page_buffer = postcopy_host_page +

arch_init.c static int ram_load(QEMUFile *f, void *opaque, int version_id) · line 1629

Quoted 10 lines
arch_init.c +10 -0
+                              ((uintptr_t)host & ~qemu_host_page_mask);
+                /* If all TP are zero then we can optimise the place */
+                if (!((uintptr_t)host & ~qemu_host_page_mask)) {
+                    all_zero = true;
+                }
+
+                /*
+                 * If it's the last part of a host page then we place the host
+                 * page
+                 */

So it's assumed in a bunch of places that the other end will send target pages in order until you have a whole host page. Which is fine, but it would be nice to have some tests to verify that, just in case somebody changes that behaviour in future, then wonders why everything broke.

As I suggested on the earlier patch, I think some of this stuff might become less clunky, if you had a "receive_host_page" subfunction with its own inner loop.

Quoted 26 lines
arch_init.c +7 -11
+                postcopy_place_needed = (((uintptr_t)host + TARGET_PAGE_SIZE) &
+                                         ~qemu_host_page_mask) == 0;
+            }
+        } else {
+            postcopy_place_needed = false;
+        }
+
         switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
         case RAM_SAVE_FLAG_MEM_SIZE:
             /* Synchronize RAM block list */
@@ -1590,32 +1671,27 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)
             }
             break;
         case RAM_SAVE_FLAG_COMPRESS:
-            host = host_from_stream_offset(f, addr, flags);
-            if (!host) {
-                error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
-                ret = -EINVAL;
-                break;
-            }
-
             ch = qemu_get_byte(f);
-            ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
-            break;
-        case RAM_SAVE_FLAG_PAGE:
-            host = host_from_stream_offset(f, addr, flags);

arch_init.c static int ram_load(QEMUFile *f, void *opaque, int version_id) · line 1680

Quoted 10 lines
arch_init.c +6 -4
-            if (!host) {
-                error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
-                ret = -EINVAL;
-                break;
+            if (!postcopy_running) {
+                ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
+            } else {
+                memset(page_buffer, ch, TARGET_PAGE_SIZE);
+                if (ch) {
+                    all_zero = false;

It's a bit nasty that the non-postcopy cases are now out-of-line with the postcopy cases in-line. I think it would be nicer to alter the helper functions so that they work on a supplied buffer, rather than directly on the ram state. Then you should be able to use the same helpers for either case, with just different postcopy logic before and after the actual page load.

Quoted 39 lines
arch_init.c +19 -6
+                }
             }
+            break;
 
-            qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
+        case RAM_SAVE_FLAG_PAGE:
+            all_zero = false;
+            qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
             break;
+
         case RAM_SAVE_FLAG_XBZRLE:
-            host = host_from_stream_offset(f, addr, flags);
-            if (!host) {
-                error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
-                ret = -EINVAL;
-                break;
+            all_zero = false;
+            if (postcopy_running) {
+                error_report("XBZRLE RAM block in postcopy mode @%zx\n", addr);
+                return -EINVAL;
             }
 
             if (load_xbzrle(f, addr, host) < 0) {
@@ -1637,6 +1713,15 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)
                 ret = -EINVAL;
             }
         }
+
+        if (postcopy_place_needed) {
+            /* This gets called at the last target page in the host page */
+            ret = postcopy_place_page(mis, host + TARGET_PAGE_SIZE -
+                                           qemu_host_page_size,
+                                      postcopy_host_page,
+                                      (addr + rb->offset) >> TARGET_PAGE_BITS,
+                                      all_zero);
+        }
         if (!ret) {
             ret = qemu_file_get_error(f);
         }
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#162 lore raw

PATCH v5 37/45 qemu_ram_block_from_host

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Postcopy sends RAMBlock names and offsets over the wire (since it can't rely on the order of ramaddr being the same), and it starts out with HVA fault addresses from the kernel.

qemu_ram_block_from_host translates a HVA into a RAMBlock, an offset in the RAMBlock, the global ram_addr_t value and it's bitmap position.

Rewrite qemu_ram_addr_from_host to use qemu_ram_block_from_host.

Provide qemu_ram_get_idstr since its the actual name text sent on the wire.

---
 exec.c                    | 56 ++++++++++++++++++++++++++++++++++++++++++-----
 include/exec/cpu-common.h |  4 ++++
 2 files changed, 55 insertions(+), 5 deletions(-)
exec.c +51 -5
index eafd964..0b02464 100644
@@ -1237,6 +1237,11 @@ static RAMBlock *find_ram_block(ram_addr_t addr)
     return NULL;
 }
 
+const char *qemu_ram_get_idstr(RAMBlock *rb)
+{
+    return rb->idstr;
+}
+
 void qemu_ram_set_idstr(ram_addr_t addr, const char *name, DeviceState *dev)
 {
     RAMBlock *new_block = find_ram_block(addr);
@@ -1669,16 +1674,35 @@ static void *qemu_ram_ptr_length(ram_addr_t addr, hwaddr *size)
     }
 }
 
-/* Some of the softmmu routines need to translate from a host pointer
-   (typically a TLB entry) back to a ram offset.  */
-MemoryRegion *qemu_ram_addr_from_host(void *ptr, ram_addr_t *ram_addr)
+/*
+ * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
+ * in that RAMBlock.
+ *
+ * ptr: Host pointer to look up
+ * round_offset: If true round the result offset down to a page boundary
+ * *ram_addr: set to result ram_addr
+ * *offset: set to result offset within the RAMBlock
+ * *bm_index: bitmap index (i.e. scaled ram_addr for use where the scale
+ *                          isn't available)
+ *
+ * Returns: RAMBlock (or NULL if not found)
+ */
+RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
+                                   ram_addr_t *ram_addr,
+                                   ram_addr_t *offset,
+                                   unsigned long *bm_index)
 {
     RAMBlock *block;
     uint8_t *host = ptr;
 
     if (xen_enabled()) {
         *ram_addr = xen_ram_addr_from_mapcache(ptr);
-        return qemu_get_ram_block(*ram_addr)->mr;
+        block = qemu_get_ram_block(*ram_addr);
+        if (!block) {
+            return NULL;
+        }
+        *offset = (host - block->host);
+        return block;
     }
 
     block = ram_list.mru_block;
@@ -1699,7 +1723,29 @@ MemoryRegion *qemu_ram_addr_from_host(void *ptr, ram_addr_t *ram_addr)
     return NULL;
 
 found:
-    *ram_addr = block->offset + (host - block->host);
+    *offset = (host - block->host);
+    if (round_offset) {
+        *offset &= TARGET_PAGE_MASK;
+    }
+    *ram_addr = block->offset + *offset;
+    *bm_index = *ram_addr >> TARGET_PAGE_BITS;
+    return block;
+}
+
+/* Some of the softmmu routines need to translate from a host pointer
+   (typically a TLB entry) back to a ram offset.  */
+MemoryRegion *qemu_ram_addr_from_host(void *ptr, ram_addr_t *ram_addr)
+{
+    RAMBlock *block;
+    ram_addr_t offset; /* Not used */
+    unsigned long index; /* Not used */
+
+    block = qemu_ram_block_from_host(ptr, false, ram_addr, &offset, &index);
+
+    if (!block) {
+        return NULL;
+    }
+
     return block->mr;
 }
 
include/exec/cpu-common.h +4 -0
index a31300c..d23a97f 100644
@@ -61,8 +61,12 @@ typedef uint32_t CPUReadMemoryFunc(void *opaque, hwaddr addr);
 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length);
 /* This should not be used by devices.  */
 MemoryRegion *qemu_ram_addr_from_host(void *ptr, ram_addr_t *ram_addr);
+RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
+                                   ram_addr_t *ram_addr, ram_addr_t *offset,
+                                   unsigned long *bm_index);
 void qemu_ram_set_idstr(ram_addr_t addr, const char *name, DeviceState *dev);
 void qemu_ram_unset_idstr(ram_addr_t addr);
+const char *qemu_ram_get_idstr(RAMBlock *rb);
 
 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
                             int len, int is_write);
Signature · 1 line
2.1.0
Reviewed-by on v5 37/45
#163 lore raw

Re: [Qemu-devel] [PATCH v5 37/45] qemu_ram_block_from_host

Quoted 5 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Postcopy sends RAMBlock names and offsets over the wire (since it can't rely on the order of ramaddr being the same), and it starts out with HVA fault addresses from the kernel.

Though as noted earlier, I do wonder if GPA might be a better idea.

Quoted 10 lines

qemu_ram_block_from_host translates a HVA into a RAMBlock, an offset in the RAMBlock, the global ram_addr_t value and it's bitmap position.

Rewrite qemu_ram_addr_from_host to use qemu_ram_block_from_host.

Provide qemu_ram_get_idstr since its the actual name text sent on the wire.

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#164 lore raw

PATCH v5 38/45 Don't sync dirty bitmaps in postcopy

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Once we're in postcopy the source processors are stopped and memory shouldn't change any more, so there's no need to look at the dirty map.

There are two notes to this:
1) If we do resync and a page had changed then the page would get sent again, which the destination wouldn't allow (since it might have also modified the page)
2) Before disabling this I'd seen very rare cases where a page had been marked dirtied although the memory contents are apparently identical

---
 arch_init.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
arch_init.c +6 -2
index 7a1c9ea..9d8ca95 100644
@@ -1398,7 +1398,10 @@ static int ram_save_iterate(QEMUFile *f, void *opaque)
 static int ram_save_complete(QEMUFile *f, void *opaque)
 {
     qemu_mutex_lock_ramlist();
-    migration_bitmap_sync();
+
+    if (!migration_postcopy_phase(migrate_get_current())) {
+        migration_bitmap_sync();
+    }
 
     ram_control_before_iterate(f, RAM_CONTROL_FINISH);
 
@@ -1433,7 +1436,8 @@ static void ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
 
     remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
 
-    if (remaining_size < max_size) {
+    if (!migration_postcopy_phase(migrate_get_current()) &&
+        remaining_size < max_size) {
         qemu_mutex_lock_iothread();
         migration_bitmap_sync();
         qemu_mutex_unlock_iothread();
Signature · 1 line
2.1.0
Reviewed-by on v5 38/45
#165 lore raw

Re: [Qemu-devel] [PATCH v5 38/45] Don't sync dirty bitmaps in postcopy

Quoted 10 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Once we're in postcopy the source processors are stopped and memory shouldn't change any more, so there's no need to look at the dirty map.

There are two notes to this:
1) If we do resync and a page had changed then the page would get sent again, which the destination wouldn't allow (since it might have also modified the page)

I'm not quite sure what you mean by "resync" in this context.

Quoted 4 lines

2) Before disabling this I'd seen very rare cases where a page had been marked dirtied although the memory contents are apparently identical

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#166 lore raw

Re: [Qemu-devel] [PATCH v5 38/45] Don't sync dirty bitmaps in postcopy

Quoted 7 lines · * David Gibson ([email protected]) wrote:
Quoted 6 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Once we're in postcopy the source processors are stopped and memory shouldn't change any more, so there's no need to look at the dirty map.

Quoted 6 lines
Quoted 4 lines

There are two notes to this:
1) If we do resync and a page had changed then the page would get sent again, which the destination wouldn't allow (since it might have also modified the page)

I'm not quite sure what you mean by "resync" in this context.

I mean synchronise the raw dirty bitmap with the migration bitmap, which we normally do at every cycle through migration.

Quoted 6 lines
Quoted 4 lines

2) Before disabling this I'd seen very rare cases where a page had been marked dirtied although the memory contents are apparently identical

Thanks,

Dave

Quoted 6 lines
Signature · 5 lines
-- 
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#167 lore raw

PATCH v5 39/45 Host page!=target page: Cleanup bitmaps

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Prior to the start of postcopy, ensure that everything that will be transferred later is a whole host-page in size.

This is accomplished by discarding partially transferred host pages and marking any that are partially dirty as fully dirty.

---
 arch_init.c | 227 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 224 insertions(+), 3 deletions(-)
arch_init.c +224 -3
index 9d8ca95..9bc799b 100644
@@ -788,7 +788,6 @@ static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
     int bytes_sent = 0;
     ram_addr_t dirty_ram_abs; /* Address of the start of the dirty page in
                                  ram_addr_t space */
-    unsigned long hps = sysconf(_SC_PAGESIZE);
 
     if (!block) {
         block = QTAILQ_FIRST(&ram_list.blocks);
@@ -805,7 +804,8 @@ static int ram_find_and_save_block(QEMUFile *f, bool last_stage)
          *   b) The last sent item was the last target-page in a host page
          */
         if (last_was_from_queue || !last_sent_block ||
-            ((last_offset & (hps - 1)) == (hps - TARGET_PAGE_SIZE))) {
+            ((last_offset & ~qemu_host_page_mask) ==
+             (qemu_host_page_size - TARGET_PAGE_SIZE))) {
             tmpblock = ram_save_unqueue_page(ms, &tmpoffset, &dirty_ram_abs);
         }
 
@@ -1040,7 +1040,6 @@ static uint32_t get_32bits_map(unsigned long *map, int64_t start)
  * A helper to put 32 bits into a bit map; trivial for HOST_LONG_BITS=32
  * messier for 64; the bitmaps are actually long's that are 32 or 64bit
  */
-__attribute__ (( unused )) /* Until later in patch series */
 static void put_32bits_map(unsigned long *map, int64_t start,
                            uint32_t v)
 {
@@ -1169,15 +1168,237 @@ static int pc_each_ram_discard(MigrationState *ms)
 }
 
 /*
+ * Helper for postcopy_chunk_hostpages where HPS/TPS >=32
+ *
+ * !! Untested !!
+ */
+static int hostpage_big_chunk_helper(const char *block_name, void *host_addr,
+                                     ram_addr_t offset, ram_addr_t length,
+                                     void *opaque)
+{
+    MigrationState *ms = opaque;
+    unsigned int host_len = (qemu_host_page_size / TARGET_PAGE_SIZE) / 32;
+    unsigned long first32, last32, cur32, current_hp;
+    unsigned long first = offset >> TARGET_PAGE_BITS;
+    unsigned long last = (offset + (length - 1)) >> TARGET_PAGE_BITS;
+
+    PostcopyDiscardState *pds = postcopy_discard_send_init(ms,
+                                                           first & 31,
+                                                           block_name);
+    first32 = first / 32;
+    last32 = last / 32;
+
+    /*
+     * I'm assuming RAMBlocks must start at the start of host pages,
+     * but I guess they might not use the whole of the host page
+     */
+
+    /* Work along one host page at a time */
+    for (current_hp = first32; current_hp <= last32; current_hp += host_len) {
+        bool discard = 0;
+        bool redirty = 0;
+        bool has_some_dirty = false;
+        bool has_some_undirty = false;
+        bool has_some_sent = false;
+        bool has_some_unsent = false;
+
+        /*
+         * Check all the 32bit chunks of mask for this hp, and see if anything
+         * needs updating.
+         */
+        for (cur32 = current_hp; cur32 < (current_hp + host_len); cur32++) {
+            /* a chunk of sent pages */
+            uint32_t sdata = get_32bits_map(ms->sentmap, cur32 * 32);
+            /* a chunk of dirty pages */
+            uint32_t ddata = get_32bits_map(migration_bitmap, cur32 * 32);
+
+            if (sdata) {
+                has_some_sent = true;
+            }
+            if (sdata != 0xfffffffful) {
+                has_some_unsent = true;
+            }
+            if (ddata) {
+                has_some_dirty = true;
+            }
+            if (ddata != 0xfffffffful) {
+                has_some_undirty = true;
+            }
+
+        }
+
+        if (has_some_sent && has_some_unsent) {
+            /* Partially sent host page */
+            discard = true;
+            redirty = true;
+        }
+
+        if (has_some_dirty && has_some_undirty) {
+            /* Partially dirty host page */
+            redirty = true;
+        }
+
+        if (!discard && !redirty) {
+            /* All consistent - next host page */
+            continue;
+        }
+
+
+        /* Now walk the 32bit chunks again, sending discards etc */
+        for (cur32 = current_hp; cur32 < (current_hp + host_len); cur32++) {
+            /* a chunk of sent pages */
+            uint32_t sdata = get_32bits_map(ms->sentmap, cur32 * 32);
+            /* a chunk of dirty pages */
+            uint32_t ddata = get_32bits_map(migration_bitmap, cur32 * 32);
+
+            if (discard && sdata) {
+                /* Tell the destination to discard these pages */
+                postcopy_discard_send_chunk(ms, pds, (cur32-first32) * 32,
+                                            sdata);
+                /* And clear them in the sent data structure */
+                put_32bits_map(ms->sentmap, cur32 * 32, 0);
+            }
+
+            if (redirty) {
+                put_32bits_map(migration_bitmap, cur32 * 32,
+                               0xffffffffu);
+                /* Inc the count of dirty pages */
+                migration_dirty_pages += ctpop32(~ddata);
+            }
+        }
+    }
+
+    postcopy_discard_send_finish(ms, pds);
+
+    return 0;
+}
+
+
+/*
+ * Utility for the outgoing postcopy code.
+ *
+ * Discard any partially sent host-page size chunks, mark any partially
+ * dirty host-page size chunks as all dirty.
+ *
+ * Returns: 0 on success
+ */
+static int postcopy_chunk_hostpages(MigrationState *ms)
+{
+    struct RAMBlock *block;
+    unsigned int host_bits = qemu_host_page_size / TARGET_PAGE_SIZE;
+    uint32_t host_mask;
+
+    assert(is_power_of_2(host_bits));
+
+    if (qemu_host_page_size == TARGET_PAGE_SIZE) {
+        /* Easy case - TPS==HPS - nothing to be done */
+        return 0;
+    }
+
+    /* Easiest way to make sure we don't resume in the middle of a host-page */
+    last_seen_block = NULL;
+    last_sent_block = NULL;
+
+    /*
+     * The currently worst known ratio is ARM that has 1kB target pages, and
+     * can have 64kB host pages, which is thus inconveniently larger than our
+     * 32bit chunks, but there again the migration bitmap that we're reworking
+     * are 'long's and those can be 32bit so it's also inconvenient to work
+     * in 64bit chunks.
+     */
+    if (host_bits >= 32) {
+        /* Deal with the odd case separately */
+        return qemu_ram_foreach_block(hostpage_big_chunk_helper, ms);
+    } else {
+        host_mask =  (1u << host_bits) - 1;
+    }
+
+    QTAILQ_FOREACH(block, &ram_list.blocks, next) {
+        unsigned long first32, last32, cur32;
+        unsigned long first = block->offset >> TARGET_PAGE_BITS;
+        unsigned long last = (block->offset + (block->used_length - 1))
+                                >> TARGET_PAGE_BITS;
+        PostcopyDiscardState *pds = postcopy_discard_send_init(ms,
+                                                               first & 31,
+                                                               block->idstr);
+
+        first32 = first / 32;
+        last32 = last / 32;
+        for (cur32 = first32; cur32 <= last32; cur32++) {
+            unsigned int current_hp;
+            /* Deal with start/end not on alignment */
+            uint32_t mask = make_32bit_mask(first, last, cur32);
+
+            /* a chunk of sent pages */
+            uint32_t sdata = get_32bits_map(ms->sentmap, cur32 * 32);
+            /* a chunk of dirty pages */
+            uint32_t ddata = get_32bits_map(migration_bitmap, cur32 * 32);
+            uint32_t discard = 0;
+            uint32_t redirty = 0;
+            sdata &= mask;
+            ddata &= mask;
+
+            for (current_hp = 0; current_hp < 32; current_hp += host_bits) {
+                uint32_t host_sent = (sdata >> current_hp) & host_mask;
+                uint32_t host_dirty = (ddata >> current_hp) & host_mask;
+
+                if (host_sent && (host_sent != host_mask)) {
+                    /* Partially sent host page */
+                    redirty |= host_mask << current_hp;
+                    discard |= host_mask << current_hp;
+
+                } else if (host_dirty && (host_dirty != host_mask)) {
+                    /* Partially dirty host page */
+                    redirty |= host_mask << current_hp;
+                }
+            }
+            if (discard) {
+                /* Tell the destination to discard these pages */
+                postcopy_discard_send_chunk(ms, pds, (cur32-first32) * 32,
+                                            discard);
+                /* And clear them in the sent data structure */
+                sdata = get_32bits_map(ms->sentmap, cur32 * 32);
+                put_32bits_map(ms->sentmap, cur32 * 32, sdata & ~discard);
+            }
+            if (redirty) {
+                /*
+                 * Reread original dirty bits and OR in ones we clear; we
+                 * must reread since we might be at the start or end of
+                 * a RAMBlock that the original 'mask' discarded some
+                 * bits from
+                */
+                ddata = get_32bits_map(migration_bitmap, cur32 * 32);
+                put_32bits_map(migration_bitmap, cur32 * 32,
+                           ddata | redirty);
+                /* Inc the count of dirty pages */
+                migration_dirty_pages += ctpop32(redirty - (ddata & redirty));
+            }
+        }
+
+        postcopy_discard_send_finish(ms, pds);
+    }
+
+    return 0;
+}
+
+/*
  * Transmit the set of pages to be discarded after precopy to the target
  * these are pages that have been sent previously but have been dirtied
  * Hopefully this is pretty sparse
  */
 int ram_postcopy_send_discard_bitmap(MigrationState *ms)
 {
+    int ret;
+
     /* This should be our last sync, the src is now paused */
     migration_bitmap_sync();
 
+    /* Deal with TPS != HPS */
+    ret = postcopy_chunk_hostpages(ms);
+    if (ret) {
+        return ret;
+    }
+
     /*
      * Update the sentmap to be  sentmap&=dirty
      */
Signature · 1 line
2.1.0
#168 lore raw

Re: [Qemu-devel] [PATCH v5 39/45] Host page!=target page: Cleanup bitmaps

Quoted 7 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Prior to the start of postcopy, ensure that everything that will be transferred later is a whole host-page in size.

This is accomplished by discarding partially transferred host pages and marking any that are partially dirty as fully dirty.

Again, I wonder if this might be a bit more obvious with send/receive_host_page() helpers. Rather than jiggering the basic data structures, you make the code only do the transmission in terms of host page sized chunks, doing the dirty check against all the necessary target page bits.

Or better yet, a migration_chunk_size variable, rather than host page size. Initially that would be initialized to host page size, but gives easier flexibility to improve future handling of cases where source hps != dest hps.

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#169 lore raw

PATCH v5 40/45 Postcopy; Handle userfault requests

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

userfaultfd is a Linux syscall that gives an fd that receives a stream of notifications of accesses to pages registered with it and allows the program to acknowledge those stalls and tell the accessing thread to carry on.

---
 include/migration/migration.h |   4 +
 migration/postcopy-ram.c      | 217 ++++++++++++++++++++++++++++++++++++++++--
 trace-events                  |  12 +++
 3 files changed, 223 insertions(+), 10 deletions(-)
include/migration/migration.h +4 -0
index 139bb1b..cec064f 100644
@@ -86,11 +86,15 @@ struct MigrationIncomingState {
 
     PostcopyState postcopy_state;
 
+    bool           have_fault_thread;
     QemuThread     fault_thread;
     QemuSemaphore  fault_thread_sem;
 
     /* For the kernel to send us notifications */
     int            userfault_fd;
+    /* To tell the fault_thread to quit */
+    int            userfault_quit_fd;
+
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
     PostcopyPMI    postcopy_pmi;
migration/postcopy-ram.c +207 -10

271 lines not on this page · raw message

trace-events +12 -0
index 16a91d9..d955a28 100644
@@ -1498,6 +1498,18 @@ postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s ma
 postcopy_cleanup_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 postcopy_init_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 postcopy_place_page(unsigned long offset, void *host_addr, bool all_zero, int old_state) "offset=%lx host=%p all_zero=%d old_state=%d"
+postcopy_ram_enable_notify(void) ""
+postcopy_ram_fault_thread_entry(void) ""
+postcopy_ram_fault_thread_exit(void) ""
+postcopy_ram_fault_thread_quit(void) ""
+postcopy_ram_fault_thread_request(uint64_t hostaddr, unsigned long index, const char *ramblock, size_t offset) "Request for HVA=%" PRIx64 " index=%lx rb=%s offset=%zx"
+postcopy_ram_fault_thread_notify_pre(uint64_t hostaddr) "%" PRIx64
+postcopy_ram_fault_thread_notify_zero(void *hostaddr) "%p"
+postcopy_ram_fault_thread_notify_zero_ack(void *hostaddr, unsigned long bitmap_index) "%p %lx"
+postcopy_ram_incoming_cleanup_closeuf(void) ""
+postcopy_ram_incoming_cleanup_entry(void) ""
+postcopy_ram_incoming_cleanup_exit(void) ""
+postcopy_ram_incoming_cleanup_join(void) ""
 
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 1 line
2.1.0
#170 lore raw

Re: [Qemu-devel] [PATCH v5 40/45] Postcopy; Handle userfault requests

Quoted 48 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

userfaultfd is a Linux syscall that gives an fd that receives a stream of notifications of accesses to pages registered with it and allows the program to acknowledge those stalls and tell the accessing thread to carry on.

---
 include/migration/migration.h |   4 +
 migration/postcopy-ram.c      | 217 ++++++++++++++++++++++++++++++++++++++++--
 trace-events                  |  12 +++
 3 files changed, 223 insertions(+), 10 deletions(-)
include/migration/migration.h +4 -0
index 139bb1b..cec064f 100644
@@ -86,11 +86,15 @@ struct MigrationIncomingState {
 
     PostcopyState postcopy_state;
 
+    bool           have_fault_thread;
     QemuThread     fault_thread;
     QemuSemaphore  fault_thread_sem;
 
     /* For the kernel to send us notifications */
     int            userfault_fd;
+    /* To tell the fault_thread to quit */
+    int            userfault_quit_fd;
+
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
     PostcopyPMI    postcopy_pmi;
migration/postcopy-ram.c +2 -0
index 86fa5a0..abc039e 100644
@@ -47,6 +47,8 @@ struct PostcopyDiscardState {
  */
 #if defined(__linux__)
 
+#include <poll.h>
+#include <sys/eventfd.h>
 #include <sys/mman.h>
 #include <sys/ioctl.h>
 #include <sys/types.h>

migration/postcopy-ram.c void postcopy_pmi_dump(MigrationIncomingState *mis) · line 269

Quoted 5 lines
migration/postcopy-ram.c +1 -1
@@ -264,7 +266,7 @@ void postcopy_pmi_dump(MigrationIncomingState *mis)
 void postcopy_hook_early_receive(MigrationIncomingState *mis,
                                  size_t bitmap_index)
 {
-    if (mis->postcopy_state == POSTCOPY_INCOMING_ADVISE) {
+    if (postcopy_state_get(mis) == POSTCOPY_INCOMING_ADVISE) {

It kind of looks like that's a fix which should be folded into an earlier patch.

Quoted 201 lines
migration/postcopy-ram.c +165 -8
         /*
          * If we're in precopy-advise mode we need to track received pages even
          * though we don't need to place pages atomically yet.
@@ -489,15 +491,40 @@ int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
  */
 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
 {
-    /* TODO: Join the fault thread once we're sure it will exit */
-    if (qemu_ram_foreach_block(cleanup_area, mis)) {
-        return -1;
+    trace_postcopy_ram_incoming_cleanup_entry();
+
+    if (mis->have_fault_thread) {
+        uint64_t tmp64;
+
+        if (qemu_ram_foreach_block(cleanup_area, mis)) {
+            return -1;
+        }
+        /*
+         * Tell the fault_thread to exit, it's an eventfd that should
+         * currently be at 0, we're going to inc it to 1
+         */
+        tmp64 = 1;
+        if (write(mis->userfault_quit_fd, &tmp64, 8) == 8) {
+            trace_postcopy_ram_incoming_cleanup_join();
+            qemu_thread_join(&mis->fault_thread);
+        } else {
+            /* Not much we can do here, but may as well report it */
+            perror("incing userfault_quit_fd");
+        }
+        trace_postcopy_ram_incoming_cleanup_closeuf();
+        close(mis->userfault_fd);
+        close(mis->userfault_quit_fd);
+        mis->have_fault_thread = false;
     }
 
+    postcopy_state_set(mis, POSTCOPY_INCOMING_END);
+    migrate_send_rp_shut(mis, qemu_file_get_error(mis->file) != 0);
+
     if (mis->postcopy_tmp_page) {
         munmap(mis->postcopy_tmp_page, getpagesize());
         mis->postcopy_tmp_page = NULL;
     }
+    trace_postcopy_ram_incoming_cleanup_exit();
     return 0;
 }
 
@@ -531,36 +558,206 @@ static int ram_block_enable_notify(const char *block_name, void *host_addr,
 }
 
 /*
+ * Tell the kernel that we've now got some memory it previously asked for.
+ */
+static int ack_userfault(MigrationIncomingState *mis, void *start, size_t len)
+{
+    struct uffdio_range range_struct;
+
+    range_struct.start = (uint64_t)(uintptr_t)start;
+    range_struct.len = (uint64_t)len;
+
+    errno = 0;
+    if (ioctl(mis->userfault_fd, UFFDIO_WAKE, &range_struct)) {
+        int e = errno;
+
+        if (e == ENOENT) {
+            /* Kernel said it wasn't waiting - one case where this can
+             * happen is where two threads triggered the userfault
+             * and we receive the page and ack it just after we received
+             * the 2nd request and that ends up deciding it should ack it
+             * We could optimise it out, but it's rare.
+             */
+            /*fprintf(stderr, "ack_userfault: %p/%zx ENOENT\n", start, len); */
+            return 0;
+        }
+        error_report("postcopy_ram: Failed to notify kernel for %p/%zx (%d)",
+                     start, len, e);
+        return -e;
+    }
+
+    return 0;
+}
+
+/*
  * Handle faults detected by the USERFAULT markings
  */
 static void *postcopy_ram_fault_thread(void *opaque)
 {
     MigrationIncomingState *mis = (MigrationIncomingState *)opaque;
-
-    fprintf(stderr, "postcopy_ram_fault_thread\n");
-    /* TODO: In later patch */
+    uint64_t hostaddr; /* The kernel always gives us 64 bit, not a pointer */
+    int ret;
+    size_t hostpagesize = getpagesize();
+    RAMBlock *rb = NULL;
+    RAMBlock *last_rb = NULL; /* last RAMBlock we sent part of */
+    uint8_t *local_tmp_page;
+
+    trace_postcopy_ram_fault_thread_entry();
     qemu_sem_post(&mis->fault_thread_sem);
-    while (1) {
-        /* TODO: In later patch */
+
+    local_tmp_page = mmap(NULL, getpagesize(),
+                          PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
+                          -1, 0);
+    if (!local_tmp_page) {
+        perror("mapping local tmp page");
+        return NULL;
     }
+    if (madvise(local_tmp_page, getpagesize(), MADV_DONTFORK)) {
+        munmap(local_tmp_page, getpagesize());
+        perror("postcpy local page DONTFORK");
+        return NULL;
+    }
+
+    while (true) {
+        PostcopyPMIState old_state, tmp_state;
+        ram_addr_t rb_offset;
+        ram_addr_t in_raspace;
+        unsigned long bitmap_index;
+        struct pollfd pfd[2];
+
+        /*
+         * We're mainly waiting for the kernel to give us a faulting HVA,
+         * however we can be told to quit via userfault_quit_fd which is
+         * an eventfd
+         */
+        pfd[0].fd = mis->userfault_fd;
+        pfd[0].events = POLLIN;
+        pfd[0].revents = 0;
+        pfd[1].fd = mis->userfault_quit_fd;
+        pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */
+        pfd[1].revents = 0;
+
+        if (poll(pfd, 2, -1 /* Wait forever */) == -1) {
+            perror("userfault poll");
+            break;
+        }
+
+        if (pfd[1].revents) {
+            trace_postcopy_ram_fault_thread_quit();
+            break;
+        }
+
+        ret = read(mis->userfault_fd, &hostaddr, sizeof(hostaddr));
+        if (ret != sizeof(hostaddr)) {
+            if (ret < 0) {
+                perror("Failed to read full userfault hostaddr");
+                break;
+            } else {
+                error_report("%s: Read %d bytes from userfaultfd expected %zd",
+                             __func__, ret, sizeof(hostaddr));
+                break; /* Lost alignment, don't know what we'd read next */
+            }
+        }
+
+        rb = qemu_ram_block_from_host((void *)(uintptr_t)hostaddr, true,
+                                      &in_raspace, &rb_offset, &bitmap_index);
+        if (!rb) {
+            error_report("postcopy_ram_fault_thread: Fault outside guest: %"
+                         PRIx64, hostaddr);
+            break;
+        }
 
+        trace_postcopy_ram_fault_thread_request(hostaddr, bitmap_index,
+                                                qemu_ram_get_idstr(rb),
+                                                rb_offset);
+
+        tmp_state = postcopy_pmi_get_state(mis, bitmap_index);
+        do {
+            old_state = tmp_state;
+
+            switch (old_state) {
+            case POSTCOPY_PMI_REQUESTED:
+                /* Do nothing - it's already requested */
+                break;
+
+            case POSTCOPY_PMI_RECEIVED:
+                /* Already arrived - no state change, just kick the kernel */
+                trace_postcopy_ram_fault_thread_notify_pre(hostaddr);
+                if (ack_userfault(mis,
+                                  (void *)((uintptr_t)hostaddr
+                                           & ~(hostpagesize - 1)),
+                                  hostpagesize)) {
+                    assert(0);
+                }
+                break;
+
+            case POSTCOPY_PMI_MISSING:
+                tmp_state = postcopy_pmi_change_state(mis, bitmap_index,
+                                           old_state, POSTCOPY_PMI_REQUESTED);
+                if (tmp_state == POSTCOPY_PMI_MISSING) {
+                    /*
+                     * Send the request to the source - we want to request one
+                     * of our host page sizes (which is >= TPS)
+                     */
+                    if (rb != last_rb) {
+                        last_rb = rb;
+                        migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),
+                                                 rb_offset, hostpagesize);

migration/postcopy-ram.c static int ram_block_enable_notify(const char *block_name, void *host_addr, · line 715

Quoted 10 lines
migration/postcopy-ram.c +10 -0
+                    } else {
+                        /* Save some space */
+                        migrate_send_rp_req_pages(mis, NULL,
+                                                 rb_offset, hostpagesize);
+                    }
+                } /* else it just arrived from the source and the kernel will
+                     be kicked during the receive */
+                break;
+           }
+        } while (tmp_state != old_state);

Again, I think using separate requested/received bits rather than treating them as a single state could avoid this clunky loop.

migration/postcopy-ram.c static int ram_block_enable_notify(const char *block_name, void *host_addr, · line 725

Quoted 11 lines
migration/postcopy-ram.c +5 -1
+    }
+    munmap(local_tmp_page, getpagesize());
+    trace_postcopy_ram_fault_thread_exit();
     return NULL;
 }
 
 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
 {
-    /* Create the fault handler thread and wait for it to be ready */
+    /* Open the fd for the kernel to give us userfaults */
+    mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC);

I think it would be good to declare your own userfaultfd() wrappers around syscall(). That way it will be easier to clean up once libc knows about them.

Quoted 61 lines
migration/postcopy-ram.c +24 -0
+    if (mis->userfault_fd == -1) {
+        perror("Failed to open userfault fd");
+        return -1;
+    }
+
+    /*
+     * Although the host check already tested the API, we need to
+     * do the check again as an ABI handshake on the new fd.
+     */
+    if (!ufd_version_check(mis->userfault_fd)) {
+        return -1;
+    }
+
+    /* Now an eventfd we use to tell the fault-thread to quit */
+    mis->userfault_quit_fd = eventfd(0, EFD_CLOEXEC);
+    if (mis->userfault_quit_fd == -1) {
+        perror("Opening userfault_quit_fd");
+        close(mis->userfault_fd);
+        return -1;
+    }
+
     qemu_sem_init(&mis->fault_thread_sem, 0);
     qemu_thread_create(&mis->fault_thread, "postcopy/fault",
                        postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE);
     qemu_sem_wait(&mis->fault_thread_sem);
     qemu_sem_destroy(&mis->fault_thread_sem);
+    mis->have_fault_thread = true;
 
     /* Mark so that we get notified of accesses to unwritten areas */
     if (qemu_ram_foreach_block(ram_block_enable_notify, mis)) {
         return -1;
     }
 
+    trace_postcopy_ram_enable_notify();
+
     return 0;
 }
 
trace-events +12 -0
index 16a91d9..d955a28 100644
@@ -1498,6 +1498,18 @@ postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s ma
 postcopy_cleanup_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 postcopy_init_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 postcopy_place_page(unsigned long offset, void *host_addr, bool all_zero, int old_state) "offset=%lx host=%p all_zero=%d old_state=%d"
+postcopy_ram_enable_notify(void) ""
+postcopy_ram_fault_thread_entry(void) ""
+postcopy_ram_fault_thread_exit(void) ""
+postcopy_ram_fault_thread_quit(void) ""
+postcopy_ram_fault_thread_request(uint64_t hostaddr, unsigned long index, const char *ramblock, size_t offset) "Request for HVA=%" PRIx64 " index=%lx rb=%s offset=%zx"
+postcopy_ram_fault_thread_notify_pre(uint64_t hostaddr) "%" PRIx64
+postcopy_ram_fault_thread_notify_zero(void *hostaddr) "%p"
+postcopy_ram_fault_thread_notify_zero_ack(void *hostaddr, unsigned long bitmap_index) "%p %lx"
+postcopy_ram_incoming_cleanup_closeuf(void) ""
+postcopy_ram_incoming_cleanup_entry(void) ""
+postcopy_ram_incoming_cleanup_exit(void) ""
+postcopy_ram_incoming_cleanup_join(void) ""
 
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#171 lore raw

Re: [Qemu-devel] [PATCH v5 40/45] Postcopy; Handle userfault requests

Quoted 43 lines · * David Gibson ([email protected]) wrote:
Quoted 42 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

userfaultfd is a Linux syscall that gives an fd that receives a stream of notifications of accesses to pages registered with it and allows the program to acknowledge those stalls and tell the accessing thread to carry on.

---
 include/migration/migration.h |   4 +
 migration/postcopy-ram.c      | 217 ++++++++++++++++++++++++++++++++++++++++--
 trace-events                  |  12 +++
 3 files changed, 223 insertions(+), 10 deletions(-)
include/migration/migration.h +4 -0
index 139bb1b..cec064f 100644
@@ -86,11 +86,15 @@ struct MigrationIncomingState {
 
     PostcopyState postcopy_state;
 
+    bool           have_fault_thread;
     QemuThread     fault_thread;
     QemuSemaphore  fault_thread_sem;
 
     /* For the kernel to send us notifications */
     int            userfault_fd;
+    /* To tell the fault_thread to quit */
+    int            userfault_quit_fd;
+
     QEMUFile *return_path;
     QemuMutex      rp_mutex;    /* We send replies from multiple threads */
     PostcopyPMI    postcopy_pmi;
migration/postcopy-ram.c +0 -0
index 86fa5a0..abc039e 100644
@@ -47,6 +47,8 @@ struct PostcopyDiscardState {
  */
 #if defined(__linux__)
 
Quoted 14 lines

migration/postcopy-ram.c void postcopy_pmi_dump(MigrationIncomingState *mis) · line 269

Quoted 11 lines
migration/postcopy-ram.c +3 -1
+#include <poll.h>
+#include <sys/eventfd.h>
 #include <sys/mman.h>
 #include <sys/ioctl.h>
 #include <sys/types.h>
@@ -264,7 +266,7 @@ void postcopy_pmi_dump(MigrationIncomingState *mis)
 void postcopy_hook_early_receive(MigrationIncomingState *mis,
                                  size_t bitmap_index)
 {
-    if (mis->postcopy_state == POSTCOPY_INCOMING_ADVISE) {
+    if (postcopy_state_get(mis) == POSTCOPY_INCOMING_ADVISE) {

It kind of looks like that's a fix which should be folded into an earlier patch.

Thanks; gone.

Quoted 207 lines
Quoted 207 lines
migration/postcopy-ram.c +170 -8
         /*
          * If we're in precopy-advise mode we need to track received pages even
          * though we don't need to place pages atomically yet.
@@ -489,15 +491,40 @@ int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
  */
 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
 {
-    /* TODO: Join the fault thread once we're sure it will exit */
-    if (qemu_ram_foreach_block(cleanup_area, mis)) {
-        return -1;
+    trace_postcopy_ram_incoming_cleanup_entry();
+
+    if (mis->have_fault_thread) {
+        uint64_t tmp64;
+
+        if (qemu_ram_foreach_block(cleanup_area, mis)) {
+            return -1;
+        }
+        /*
+         * Tell the fault_thread to exit, it's an eventfd that should
+         * currently be at 0, we're going to inc it to 1
+         */
+        tmp64 = 1;
+        if (write(mis->userfault_quit_fd, &tmp64, 8) == 8) {
+            trace_postcopy_ram_incoming_cleanup_join();
+            qemu_thread_join(&mis->fault_thread);
+        } else {
+            /* Not much we can do here, but may as well report it */
+            perror("incing userfault_quit_fd");
+        }
+        trace_postcopy_ram_incoming_cleanup_closeuf();
+        close(mis->userfault_fd);
+        close(mis->userfault_quit_fd);
+        mis->have_fault_thread = false;
     }
 
+    postcopy_state_set(mis, POSTCOPY_INCOMING_END);
+    migrate_send_rp_shut(mis, qemu_file_get_error(mis->file) != 0);
+
     if (mis->postcopy_tmp_page) {
         munmap(mis->postcopy_tmp_page, getpagesize());
         mis->postcopy_tmp_page = NULL;
     }
+    trace_postcopy_ram_incoming_cleanup_exit();
     return 0;
 }
 
@@ -531,36 +558,206 @@ static int ram_block_enable_notify(const char *block_name, void *host_addr,
 }
 
 /*
+ * Tell the kernel that we've now got some memory it previously asked for.
+ */
+static int ack_userfault(MigrationIncomingState *mis, void *start, size_t len)
+{
+    struct uffdio_range range_struct;
+
+    range_struct.start = (uint64_t)(uintptr_t)start;
+    range_struct.len = (uint64_t)len;
+
+    errno = 0;
+    if (ioctl(mis->userfault_fd, UFFDIO_WAKE, &range_struct)) {
+        int e = errno;
+
+        if (e == ENOENT) {
+            /* Kernel said it wasn't waiting - one case where this can
+             * happen is where two threads triggered the userfault
+             * and we receive the page and ack it just after we received
+             * the 2nd request and that ends up deciding it should ack it
+             * We could optimise it out, but it's rare.
+             */
+            /*fprintf(stderr, "ack_userfault: %p/%zx ENOENT\n", start, len); */
+            return 0;
+        }
+        error_report("postcopy_ram: Failed to notify kernel for %p/%zx (%d)",
+                     start, len, e);
+        return -e;
+    }
+
+    return 0;
+}
+
+/*
  * Handle faults detected by the USERFAULT markings
  */
 static void *postcopy_ram_fault_thread(void *opaque)
 {
     MigrationIncomingState *mis = (MigrationIncomingState *)opaque;
-
-    fprintf(stderr, "postcopy_ram_fault_thread\n");
-    /* TODO: In later patch */
+    uint64_t hostaddr; /* The kernel always gives us 64 bit, not a pointer */
+    int ret;
+    size_t hostpagesize = getpagesize();
+    RAMBlock *rb = NULL;
+    RAMBlock *last_rb = NULL; /* last RAMBlock we sent part of */
+    uint8_t *local_tmp_page;
+
+    trace_postcopy_ram_fault_thread_entry();
     qemu_sem_post(&mis->fault_thread_sem);
-    while (1) {
-        /* TODO: In later patch */
+
+    local_tmp_page = mmap(NULL, getpagesize(),
+                          PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
+                          -1, 0);
+    if (!local_tmp_page) {
+        perror("mapping local tmp page");
+        return NULL;
     }
+    if (madvise(local_tmp_page, getpagesize(), MADV_DONTFORK)) {
+        munmap(local_tmp_page, getpagesize());
+        perror("postcpy local page DONTFORK");
+        return NULL;
+    }
+
+    while (true) {
+        PostcopyPMIState old_state, tmp_state;
+        ram_addr_t rb_offset;
+        ram_addr_t in_raspace;
+        unsigned long bitmap_index;
+        struct pollfd pfd[2];
+
+        /*
+         * We're mainly waiting for the kernel to give us a faulting HVA,
+         * however we can be told to quit via userfault_quit_fd which is
+         * an eventfd
+         */
+        pfd[0].fd = mis->userfault_fd;
+        pfd[0].events = POLLIN;
+        pfd[0].revents = 0;
+        pfd[1].fd = mis->userfault_quit_fd;
+        pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */
+        pfd[1].revents = 0;
+
+        if (poll(pfd, 2, -1 /* Wait forever */) == -1) {
+            perror("userfault poll");
+            break;
+        }
+
+        if (pfd[1].revents) {
+            trace_postcopy_ram_fault_thread_quit();
+            break;
+        }
+
+        ret = read(mis->userfault_fd, &hostaddr, sizeof(hostaddr));
+        if (ret != sizeof(hostaddr)) {
+            if (ret < 0) {
+                perror("Failed to read full userfault hostaddr");
+                break;
+            } else {
+                error_report("%s: Read %d bytes from userfaultfd expected %zd",
+                             __func__, ret, sizeof(hostaddr));
+                break; /* Lost alignment, don't know what we'd read next */
+            }
+        }
+
+        rb = qemu_ram_block_from_host((void *)(uintptr_t)hostaddr, true,
+                                      &in_raspace, &rb_offset, &bitmap_index);
+        if (!rb) {
+            error_report("postcopy_ram_fault_thread: Fault outside guest: %"
+                         PRIx64, hostaddr);
+            break;
+        }
 
+        trace_postcopy_ram_fault_thread_request(hostaddr, bitmap_index,
+                                                qemu_ram_get_idstr(rb),
+                                                rb_offset);
+
+        tmp_state = postcopy_pmi_get_state(mis, bitmap_index);
+        do {
+            old_state = tmp_state;
+
+            switch (old_state) {
+            case POSTCOPY_PMI_REQUESTED:
+                /* Do nothing - it's already requested */
+                break;
+
+            case POSTCOPY_PMI_RECEIVED:
+                /* Already arrived - no state change, just kick the kernel */
+                trace_postcopy_ram_fault_thread_notify_pre(hostaddr);
+                if (ack_userfault(mis,
+                                  (void *)((uintptr_t)hostaddr
+                                           & ~(hostpagesize - 1)),
+                                  hostpagesize)) {
+                    assert(0);
+                }
+                break;
+
+            case POSTCOPY_PMI_MISSING:
+                tmp_state = postcopy_pmi_change_state(mis, bitmap_index,
+                                           old_state, POSTCOPY_PMI_REQUESTED);
+                if (tmp_state == POSTCOPY_PMI_MISSING) {
+                    /*
+                     * Send the request to the source - we want to request one
+                     * of our host page sizes (which is >= TPS)
+                     */
+                    if (rb != last_rb) {
+                        last_rb = rb;
+                        migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),
+                                                 rb_offset, hostpagesize);
+                    } else {
+                        /* Save some space */
+                        migrate_send_rp_req_pages(mis, NULL,
+                                                 rb_offset, hostpagesize);
+                    }
Quoted 8 lines

migration/postcopy-ram.c static int ram_block_enable_notify(const char *block_name, void *host_addr, · line 715

Quoted 5 lines
migration/postcopy-ram.c +5 -0
+                } /* else it just arrived from the source and the kernel will
+                     be kicked during the receive */
+                break;
+           }
+        } while (tmp_state != old_state);

Again, I think using separate requested/received bits rather than treating them as a single state could avoid this clunky loop.

As mentioned; the PMI is simplified out so this all disappears.

Quoted 12 lines

migration/postcopy-ram.c static int ram_block_enable_notify(const char *block_name, void *host_addr, · line 725

Quoted 11 lines
migration/postcopy-ram.c +5 -1
+    }
+    munmap(local_tmp_page, getpagesize());
+    trace_postcopy_ram_fault_thread_exit();
     return NULL;
 }
 
 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
 {
-    /* Create the fault handler thread and wait for it to be ready */
+    /* Open the fd for the kernel to give us userfaults */
+    mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC);
Quoted 3 lines

I think it would be good to declare your own userfaultfd() wrappers around syscall(). That way it will be easier to clean up once libc knows about them.

OK, I'll look at that; this might depend if I find the better way of dealing with a new syscall definition as mentioned in the other patch.

Dave

Quoted 59 lines
Quoted 59 lines
migration/postcopy-ram.c +24 -0
+    if (mis->userfault_fd == -1) {
+        perror("Failed to open userfault fd");
+        return -1;
+    }
+
+    /*
+     * Although the host check already tested the API, we need to
+     * do the check again as an ABI handshake on the new fd.
+     */
+    if (!ufd_version_check(mis->userfault_fd)) {
+        return -1;
+    }
+
+    /* Now an eventfd we use to tell the fault-thread to quit */
+    mis->userfault_quit_fd = eventfd(0, EFD_CLOEXEC);
+    if (mis->userfault_quit_fd == -1) {
+        perror("Opening userfault_quit_fd");
+        close(mis->userfault_fd);
+        return -1;
+    }
+
     qemu_sem_init(&mis->fault_thread_sem, 0);
     qemu_thread_create(&mis->fault_thread, "postcopy/fault",
                        postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE);
     qemu_sem_wait(&mis->fault_thread_sem);
     qemu_sem_destroy(&mis->fault_thread_sem);
+    mis->have_fault_thread = true;
 
     /* Mark so that we get notified of accesses to unwritten areas */
     if (qemu_ram_foreach_block(ram_block_enable_notify, mis)) {
         return -1;
     }
 
+    trace_postcopy_ram_enable_notify();
+
     return 0;
 }
 
trace-events +12 -0
index 16a91d9..d955a28 100644
@@ -1498,6 +1498,18 @@ postcopy_discard_send_finish(const char *ramblock, int nwords, int ncmds) "%s ma
 postcopy_cleanup_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 postcopy_init_area(const char *ramblock, void *host_addr, size_t offset, size_t length) "%s: %p offset=%zx length=%zx"
 postcopy_place_page(unsigned long offset, void *host_addr, bool all_zero, int old_state) "offset=%lx host=%p all_zero=%d old_state=%d"
+postcopy_ram_enable_notify(void) ""
+postcopy_ram_fault_thread_entry(void) ""
+postcopy_ram_fault_thread_exit(void) ""
+postcopy_ram_fault_thread_quit(void) ""
+postcopy_ram_fault_thread_request(uint64_t hostaddr, unsigned long index, const char *ramblock, size_t offset) "Request for HVA=%" PRIx64 " index=%lx rb=%s offset=%zx"
+postcopy_ram_fault_thread_notify_pre(uint64_t hostaddr) "%" PRIx64
+postcopy_ram_fault_thread_notify_zero(void *hostaddr) "%p"
+postcopy_ram_fault_thread_notify_zero_ack(void *hostaddr, unsigned long bitmap_index) "%p %lx"
+postcopy_ram_incoming_cleanup_closeuf(void) ""
+postcopy_ram_incoming_cleanup_entry(void) ""
+postcopy_ram_incoming_cleanup_exit(void) ""
+postcopy_ram_incoming_cleanup_join(void) ""
 
Quoted 8 lines
Quoted 2 lines
trace-events +0 -0
 # kvm-all.c
 kvm_ioctl(int type, void *arg) "type 0x%x, arg %p"
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#172 lore raw

PATCH v5 41/45 Start up a postcopy/listener thread ready for incoming page data

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

The loading of a device state (during postcopy) may access guest memory that's still on the source machine and thus might need a page fill; split off a separate thread that handles the incoming page data so that the original incoming migration code can finish off the device data.

---
 include/migration/migration.h |  4 +++
 migration/migration.c         |  6 ++++
 savevm.c                      | 71 +++++++++++++++++++++++++++++++++++++++++--
 trace-events                  |  2 ++
 4 files changed, 81 insertions(+), 2 deletions(-)
include/migration/migration.h +4 -0
index cec064f..c2af2ef 100644
@@ -90,6 +90,10 @@ struct MigrationIncomingState {
     QemuThread     fault_thread;
     QemuSemaphore  fault_thread_sem;
 
+    bool           have_listen_thread;
+    QemuThread     listen_thread;
+    QemuSemaphore  listen_thread_sem;
+
     /* For the kernel to send us notifications */
     int            userfault_fd;
     /* To tell the fault_thread to quit */
migration/migration.c +6 -0
index 939f426..c108851 100644
@@ -1067,6 +1067,12 @@ static int postcopy_start(MigrationState *ms, bool *old_vm_running)
         goto fail;
     }
 
+    /*
+     * Make sure the receiver can get incoming pages before we send the rest
+     * of the state
+     */
+    qemu_savevm_send_postcopy_listen(fb);
+
     qemu_savevm_state_complete(fb);
     qemu_savevm_send_ping(fb, 3);
 
savevm.c +69 -2

89 lines not on this page · raw message

trace-events +2 -0
index d955a28..82b3631 100644
@@ -1183,6 +1183,8 @@ loadvm_postcopy_ram_handle_discard(void) ""
 loadvm_postcopy_ram_handle_discard_end(void) ""
 loadvm_process_command(uint16_t com, uint16_t len) "com=0x%x len=%d"
 loadvm_process_command_ping(uint32_t val) "%x"
+postcopy_ram_listen_thread_exit(void) ""
+postcopy_ram_listen_thread_start(void) ""
 qemu_savevm_send_postcopy_advise(void) ""
 qemu_savevm_send_postcopy_ram_discard(void) ""
 qemu_savevm_state_complete_skip_for_postcopy(const char *section) "skipping: %s"
Signature · 1 line
2.1.0
#173 lore raw

PATCH v5 42/45 postcopy: Wire up loadvm_postcopy_handle_{run, end} commands

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Wire up more of the handlers for the commands on the destination side, in particular loadvm_postcopy_handle_run now has enough to start the guest running.

handle_end has to wait for the main thread to finish.

---
 include/migration/migration.h |  6 +++++
 migration/migration.c         |  2 ++
 savevm.c                      | 56 ++++++++++++++++++++++++++++++++++++++-----
 trace-events                  |  4 +++-
 4 files changed, 61 insertions(+), 7 deletions(-)
include/migration/migration.h +6 -0
index c2af2ef..02376df 100644
@@ -86,6 +86,12 @@ struct MigrationIncomingState {
 
     PostcopyState postcopy_state;
 
+    /*
+     * Free at the start of the main state load, set as the main thread finishes
+     * loading state.
+     */
+    QemuEvent      main_thread_load_event;
+
     bool           have_fault_thread;
     QemuThread     fault_thread;
     QemuSemaphore  fault_thread_sem;
migration/migration.c +2 -0
index c108851..97b86cc 100644
@@ -84,6 +84,7 @@ MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
     mis_current->file = f;
     QLIST_INIT(&mis_current->loadvm_handlers);
     qemu_mutex_init(&mis_current->rp_mutex);
+    qemu_event_init(&mis_current->main_thread_load_event, false);
 
     return mis_current;
 }
@@ -91,6 +92,7 @@ MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
 void migration_incoming_state_destroy(void)
 {
     postcopy_pmi_destroy(mis_current);
+    qemu_event_destroy(&mis_current->main_thread_load_event);
     loadvm_free_handlers(mis_current);
     g_free(mis_current);
     mis_current = NULL;
savevm.c +50 -6

94 lines not on this page · raw message

trace-events +3 -1
index 82b3631..869988b 100644
@@ -1176,9 +1176,11 @@ loadvm_handle_cmd_packaged(unsigned int length) "%u"
 loadvm_handle_cmd_packaged_main(int ret) "%d"
 loadvm_handle_cmd_packaged_received(int ret) "%d"
 loadvm_postcopy_handle_advise(void) ""
-loadvm_postcopy_handle_end(void) ""
+loadvm_postcopy_handle_end(uint8_t status) "%d"
 loadvm_postcopy_handle_listen(void) ""
 loadvm_postcopy_handle_run(void) ""
+loadvm_postcopy_handle_run_cpu_sync(void) ""
+loadvm_postcopy_handle_run_vmstart(void) ""
 loadvm_postcopy_ram_handle_discard(void) ""
 loadvm_postcopy_ram_handle_discard_end(void) ""
 loadvm_process_command(uint16_t com, uint16_t len) "com=0x%x len=%d"
Signature · 1 line
2.1.0
#174 lore raw

PATCH v5 43/45 End of migration for postcopy

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Tweak the end of migration cleanup; we don't want to close stuff down at the end of the main stream, since the postcopy is still sending pages on the other thread.

---
 migration/migration.c | 25 ++++++++++++++++++++++++-
 trace-events          |  2 ++
 2 files changed, 26 insertions(+), 1 deletion(-)
migration/migration.c +24 -1
index 97b86cc..a137444 100644
@@ -199,12 +199,35 @@ static void process_incoming_migration_co(void *opaque)
 {
     QEMUFile *f = opaque;
     Error *local_err = NULL;
+    MigrationIncomingState *mis;
+    PostcopyState ps;
     int ret;
 
-    migration_incoming_state_new(f);
+    mis = migration_incoming_state_new(f);
 
     ret = qemu_loadvm_state(f);
 
+    ps = postcopy_state_get(mis);
+    trace_process_incoming_migration_co_end(ret, ps);
+    if (ps != POSTCOPY_INCOMING_NONE) {
+        if (ps == POSTCOPY_INCOMING_ADVISE) {
+            /*
+             * Where a migration had postcopy enabled (and thus went to advise)
+             * but managed to complete within the precopy period, we can use
+             * the normal exit.
+             */
+            postcopy_ram_incoming_cleanup(mis);
+        } else if (ret >= 0) {
+            /*
+             * Postcopy was started, cleanup should happen at the end of the
+             * postcopy thread.
+             */
+            trace_process_incoming_migration_co_postcopy_end_main();
+            return;
+        }
+        /* Else if something went wrong then just fall out of the normal exit */
+    }
+
     qemu_fclose(f);
     free_xbzrle_decoded_buf();
     migration_incoming_state_destroy();
trace-events +2 -0
index 869988b..cbf4f88 100644
@@ -1434,6 +1434,8 @@ source_return_path_thread_loop_top(void) ""
 source_return_path_thread_pong(uint32_t val) "%x"
 source_return_path_thread_shut(uint32_t val) "%x"
 migrate_transferred(uint64_t tranferred, uint64_t time_spent, double bandwidth, uint64_t size) "transferred %" PRIu64 " time_spent %" PRIu64 " bandwidth %g max_size %" PRId64
+process_incoming_migration_co_end(int ret, int ps) "ret=%d postcopy-state=%d"
+process_incoming_migration_co_postcopy_end_main(void) ""
 
 # migration/rdma.c
 __qemu_rdma_add_block(int block, uint64_t addr, uint64_t offset, uint64_t len, uint64_t end, uint64_t bits, int chunks) "Added Block: %d, addr: %" PRIu64 ", offset: %" PRIu64 " length: %" PRIu64 " end: %" PRIu64 " bits %" PRIu64 " chunks %d"
Signature · 1 line
2.1.0
#175 lore raw

PATCH v5 44/45 Disable mlock around incoming postcopy

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Userfault doesn't work with mlock; mlock is designed to nail down pages so they don't move, userfault is designed to tell you when they're not there.

munlock the pages we userfault protect before postcopy. mlock everything again at the end if mlock is enabled.

---
 include/sysemu/sysemu.h  |  1 +
 migration/postcopy-ram.c | 24 ++++++++++++++++++++++++
 2 files changed, 25 insertions(+)
include/sysemu/sysemu.h +1 -0
index 0f2e4ed..25cc791 100644
@@ -176,6 +176,7 @@ extern int boot_menu;
 extern bool boot_strict;
 extern uint8_t *boot_splash_filedata;
 extern size_t boot_splash_filedata_size;
+extern bool enable_mlock;
 extern uint8_t qemu_extra_params_fw[2];
 extern QEMUClockType rtc_clock;
 extern const char *mem_path;
migration/postcopy-ram.c +24 -0
index abc039e..d8f5ccd 100644
@@ -299,6 +299,11 @@ static bool ufd_version_check(int ufd)
 }
 
 
+/*
+ * Note: This has the side effect of munlock'ing all of RAM, that's
+ * normally fine since if the postcopy succeeds it gets turned back on at the
+ * end.
+ */
 bool postcopy_ram_supported_by_host(void)
 {
     long pagesize = getpagesize();
@@ -327,6 +332,15 @@ bool postcopy_ram_supported_by_host(void)
     }
 
     /*
+     * userfault and mlock don't go together; we'll put it back later if
+     * it was enabled.
+     */
+    if (munlockall()) {
+        perror("postcopy_ram_incoming_init: munlockall");
+        return -1;
+    }
+
+    /*
      *  We need to check that the ops we need are supported on anon memory
      *  To do that we need to register a chunk and see the flags that
      *  are returned.
@@ -517,6 +531,16 @@ int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
         mis->have_fault_thread = false;
     }
 
+    if (enable_mlock) {
+        if (os_mlock() < 0) {
+            error_report("mlock: %s", strerror(errno));
+            /*
+             * It doesn't feel right to fail at this point, we have a valid
+             * VM state.
+             */
+        }
+    }
+
     postcopy_state_set(mis, POSTCOPY_INCOMING_END);
     migrate_send_rp_shut(mis, qemu_file_get_error(mis->file) != 0);
 
Signature · 1 line
2.1.0
Reviewed-by on v5 44/45
#176 lore raw

Re: [Qemu-devel] [PATCH v5 44/45] Disable mlock around incoming postcopy

Quoted 10 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

Userfault doesn't work with mlock; mlock is designed to nail down pages so they don't move, userfault is designed to tell you when they're not there.

munlock the pages we userfault protect before postcopy. mlock everything again at the end if mlock is enabled.

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#177 lore raw

PATCH v5 45/45 Inhibit ballooning during postcopy

In reply to Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

The userfault mechanism used for postcopy generates faults for us on pages that are 'not present', inflating a balloon in the guest causes host pages to be marked as 'not present'; doing this during a postcopy, as potentially the same pages were being received from the source, would confuse the state of the received page -> disable ballooning during postcopy.

When disabled we drop balloon requests from the guest. Since ballooning is generally initiated by the host, the management system should avoid initiating any balloon instructions to the guest during migration, although it's not possible to know how long it would take a guest to process a request made prior to the start of migration.

---
 balloon.c                  | 11 +++++++++++
 hw/virtio/virtio-balloon.c |  4 +++-
 include/sysemu/balloon.h   |  2 ++
 migration/postcopy-ram.c   |  9 +++++++++
 4 files changed, 25 insertions(+), 1 deletion(-)
balloon.c +11 -0
index dea19a4..faedb60 100644
@@ -35,6 +35,17 @@
 static QEMUBalloonEvent *balloon_event_fn;
 static QEMUBalloonStatus *balloon_stat_fn;
 static void *balloon_opaque;
+static bool balloon_inhibited;
+
+bool qemu_balloon_is_inhibited(void)
+{
+    return balloon_inhibited;
+}
+
+void qemu_balloon_inhibit(bool state)
+{
+    balloon_inhibited = state;
+}
 
 static bool have_ballon(Error **errp)
 {
hw/virtio/virtio-balloon.c +3 -1
index 7bfbb75..b0e94ee 100644
@@ -36,9 +36,11 @@
 static void balloon_page(void *addr, int deflate)
 {
 #if defined(__linux__)
-    if (!kvm_enabled() || kvm_has_sync_mmu())
+    if (!qemu_balloon_is_inhibited() && (!kvm_enabled() ||
+                                         kvm_has_sync_mmu())) {
         qemu_madvise(addr, TARGET_PAGE_SIZE,
                 deflate ? QEMU_MADV_WILLNEED : QEMU_MADV_DONTNEED);
+    }
 #endif
 }
 
include/sysemu/balloon.h +2 -0
index 0345e01..6851d99 100644
@@ -23,5 +23,7 @@ typedef void (QEMUBalloonStatus)(void *opaque, BalloonInfo *info);
 int qemu_add_balloon_handler(QEMUBalloonEvent *event_func,
 			     QEMUBalloonStatus *stat_func, void *opaque);
 void qemu_remove_balloon_handler(void *opaque);
+bool qemu_balloon_is_inhibited(void);
+void qemu_balloon_inhibit(bool state);
 
 #endif
migration/postcopy-ram.c +9 -0
index d8f5ccd..b9f5848 100644
@@ -24,6 +24,7 @@
 #include "migration/migration.h"
 #include "migration/postcopy-ram.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/balloon.h"
 #include "qemu/bitmap.h"
 #include "qemu/error-report.h"
 #include "trace.h"
@@ -531,6 +532,8 @@ int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
         mis->have_fault_thread = false;
     }
 
+    qemu_balloon_inhibit(false);
+
     if (enable_mlock) {
         if (os_mlock() < 0) {
             error_report("mlock: %s", strerror(errno));
@@ -780,6 +783,12 @@ int postcopy_ram_enable_notify(MigrationIncomingState *mis)
         return -1;
     }
 
+    /*
+     * Ballooning can mark pages as absent while we're postcopying
+     * that would cause false userfaults.
+     */
+    qemu_balloon_inhibit(true);
+
     trace_postcopy_ram_enable_notify();
 
     return 0;
Signature · 1 line
2.1.0
#178 lore raw

Re: [Qemu-devel] [PATCH v5 45/45] Inhibit ballooning during postcopy

Quoted 8 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

The userfault mechanism used for postcopy generates faults for us on pages that are 'not present', inflating a balloon in the guest causes host pages to be marked as 'not present'; doing this during a postcopy, as potentially the same pages were being received from the source, would confuse the state of the received page -> disable ballooning during postcopy.

That is a ludicrously long sentence, which I have great difficulty parsing.

Quoted 5 lines

When disabled we drop balloon requests from the guest. Since ballooning is generally initiated by the host, the management system should avoid initiating any balloon instructions to the guest during migration, although it's not possible to know how long it would take a guest to process a request made prior to the start of migration.

Yeah :/. It would be nice if it could queue the guest actions, instead of dropping them.

Quoted 94 lines
---
 balloon.c                  | 11 +++++++++++
 hw/virtio/virtio-balloon.c |  4 +++-
 include/sysemu/balloon.h   |  2 ++
 migration/postcopy-ram.c   |  9 +++++++++
 4 files changed, 25 insertions(+), 1 deletion(-)
balloon.c +11 -0
index dea19a4..faedb60 100644
@@ -35,6 +35,17 @@
 static QEMUBalloonEvent *balloon_event_fn;
 static QEMUBalloonStatus *balloon_stat_fn;
 static void *balloon_opaque;
+static bool balloon_inhibited;
+
+bool qemu_balloon_is_inhibited(void)
+{
+    return balloon_inhibited;
+}
+
+void qemu_balloon_inhibit(bool state)
+{
+    balloon_inhibited = state;
+}
 
 static bool have_ballon(Error **errp)
 {
hw/virtio/virtio-balloon.c +3 -1
index 7bfbb75..b0e94ee 100644
@@ -36,9 +36,11 @@
 static void balloon_page(void *addr, int deflate)
 {
 #if defined(__linux__)
-    if (!kvm_enabled() || kvm_has_sync_mmu())
+    if (!qemu_balloon_is_inhibited() && (!kvm_enabled() ||
+                                         kvm_has_sync_mmu())) {
         qemu_madvise(addr, TARGET_PAGE_SIZE,
                 deflate ? QEMU_MADV_WILLNEED : QEMU_MADV_DONTNEED);
+    }
 #endif
 }
 
include/sysemu/balloon.h +2 -0
index 0345e01..6851d99 100644
@@ -23,5 +23,7 @@ typedef void (QEMUBalloonStatus)(void *opaque, BalloonInfo *info);
 int qemu_add_balloon_handler(QEMUBalloonEvent *event_func,
 			     QEMUBalloonStatus *stat_func, void *opaque);
 void qemu_remove_balloon_handler(void *opaque);
+bool qemu_balloon_is_inhibited(void);
+void qemu_balloon_inhibit(bool state);
 
 #endif
migration/postcopy-ram.c +9 -0
index d8f5ccd..b9f5848 100644
@@ -24,6 +24,7 @@
 #include "migration/migration.h"
 #include "migration/postcopy-ram.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/balloon.h"
 #include "qemu/bitmap.h"
 #include "qemu/error-report.h"
 #include "trace.h"
@@ -531,6 +532,8 @@ int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
         mis->have_fault_thread = false;
     }
 
+    qemu_balloon_inhibit(false);
+
     if (enable_mlock) {
         if (os_mlock() < 0) {
             error_report("mlock: %s", strerror(errno));
@@ -780,6 +783,12 @@ int postcopy_ram_enable_notify(MigrationIncomingState *mis)
         return -1;
     }
 
+    /*
+     * Ballooning can mark pages as absent while we're postcopying
+     * that would cause false userfaults.
+     */
+    qemu_balloon_inhibit(true);
+
     trace_postcopy_ram_enable_notify();
 
     return 0;
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
#179 lore raw

Re: [Qemu-devel] [PATCH v5 45/45] Inhibit ballooning during postcopy

Quoted 11 lines · * David Gibson ([email protected]) wrote:
Quoted 8 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

The userfault mechanism used for postcopy generates faults for us on pages that are 'not present', inflating a balloon in the guest causes host pages to be marked as 'not present'; doing this during a postcopy, as potentially the same pages were being received from the source, would confuse the state of the received page -> disable ballooning during postcopy.

That is a ludicrously long sentence, which I have great difficulty parsing.

OK, how about:

-----
Postcopy detects accesses to pages that haven't been transferred yet using userfaultfd, and it causes exceptions on pages that are 'not present'. Ballooning also causes pages to be marked as 'not present' when the guest inflates the balloon.
Potentially a balloon could be inflated to discard pages that are currently inflight during postcopy and that may be arriving at about the same time.

To avoid this confusion, disable ballooning during postcopy.

-----

Quoted 8 lines
Quoted 5 lines

When disabled we drop balloon requests from the guest. Since ballooning is generally initiated by the host, the management system should avoid initiating any balloon instructions to the guest during migration, although it's not possible to know how long it would take a guest to process a request made prior to the start of migration.

Yeah :/. It would be nice if it could queue the guest actions, instead of dropping them.

Yes, I did look at that briefly; it's not trivial; for
example consider the situation where the guest discards some pages by inflating, and then later deflates, it expects to lose that data but then starts accessing that physical page again.
If you replay that sequence at the end then you've lost newly accessed pages. So you have to filter out inflates that have been deflated later, and have to order those correctly with the sense of changes made to those pages after the deflation occurs.

Dave

Quoted 94 lines
Quoted 94 lines
---
 balloon.c                  | 11 +++++++++++
 hw/virtio/virtio-balloon.c |  4 +++-
 include/sysemu/balloon.h   |  2 ++
 migration/postcopy-ram.c   |  9 +++++++++
 4 files changed, 25 insertions(+), 1 deletion(-)
balloon.c +11 -0
index dea19a4..faedb60 100644
@@ -35,6 +35,17 @@
 static QEMUBalloonEvent *balloon_event_fn;
 static QEMUBalloonStatus *balloon_stat_fn;
 static void *balloon_opaque;
+static bool balloon_inhibited;
+
+bool qemu_balloon_is_inhibited(void)
+{
+    return balloon_inhibited;
+}
+
+void qemu_balloon_inhibit(bool state)
+{
+    balloon_inhibited = state;
+}
 
 static bool have_ballon(Error **errp)
 {
hw/virtio/virtio-balloon.c +3 -1
index 7bfbb75..b0e94ee 100644
@@ -36,9 +36,11 @@
 static void balloon_page(void *addr, int deflate)
 {
 #if defined(__linux__)
-    if (!kvm_enabled() || kvm_has_sync_mmu())
+    if (!qemu_balloon_is_inhibited() && (!kvm_enabled() ||
+                                         kvm_has_sync_mmu())) {
         qemu_madvise(addr, TARGET_PAGE_SIZE,
                 deflate ? QEMU_MADV_WILLNEED : QEMU_MADV_DONTNEED);
+    }
 #endif
 }
 
include/sysemu/balloon.h +2 -0
index 0345e01..6851d99 100644
@@ -23,5 +23,7 @@ typedef void (QEMUBalloonStatus)(void *opaque, BalloonInfo *info);
 int qemu_add_balloon_handler(QEMUBalloonEvent *event_func,
 			     QEMUBalloonStatus *stat_func, void *opaque);
 void qemu_remove_balloon_handler(void *opaque);
+bool qemu_balloon_is_inhibited(void);
+void qemu_balloon_inhibit(bool state);
 
 #endif
migration/postcopy-ram.c +9 -0
index d8f5ccd..b9f5848 100644
@@ -24,6 +24,7 @@
 #include "migration/migration.h"
 #include "migration/postcopy-ram.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/balloon.h"
 #include "qemu/bitmap.h"
 #include "qemu/error-report.h"
 #include "trace.h"
@@ -531,6 +532,8 @@ int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
         mis->have_fault_thread = false;
     }
 
+    qemu_balloon_inhibit(false);
+
     if (enable_mlock) {
         if (os_mlock() < 0) {
             error_report("mlock: %s", strerror(errno));
@@ -780,6 +783,12 @@ int postcopy_ram_enable_notify(MigrationIncomingState *mis)
         return -1;
     }
 
+    /*
+     * Ballooning can mark pages as absent while we're postcopying
+     * that would cause false userfaults.
+     */
+    qemu_balloon_inhibit(true);
+
     trace_postcopy_ram_enable_notify();
 
Quoted 7 lines
Quoted 1 line
migration/postcopy-ram.c +0 -0
     return 0;
Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#180 lore raw

Re: [Qemu-devel] [PATCH v5 45/45] Inhibit ballooning during postcopy

Quoted 23 lines · Dr. David Alan Gilbert
Quoted 11 lines · * David Gibson ([email protected]) wrote:
Quoted 8 lines · Dr. David Alan Gilbert (git)

From: "Dr. David Alan Gilbert" <[email protected]>

The userfault mechanism used for postcopy generates faults for us on pages that are 'not present', inflating a balloon in the guest causes host pages to be marked as 'not present'; doing this during a postcopy, as potentially the same pages were being received from the source, would confuse the state of the received page -> disable ballooning during postcopy.

That is a ludicrously long sentence, which I have great difficulty parsing.

OK, how about:

-----
Postcopy detects accesses to pages that haven't been transferred yet using userfaultfd, and it causes exceptions on pages that are 'not present'. Ballooning also causes pages to be marked as 'not present' when the guest inflates the balloon.
Potentially a balloon could be inflated to discard pages that are currently inflight during postcopy and that may be arriving at about the same time.

Quoted 1 line

To avoid this confusion, disable ballooning during postcopy.

Better, thanks.

Quoted 11 lines

-----

Quoted 8 lines
Quoted 5 lines

When disabled we drop balloon requests from the guest. Since ballooning is generally initiated by the host, the management system should avoid initiating any balloon instructions to the guest during migration, although it's not possible to know how long it would take a guest to process a request made prior to the start of migration.

Yeah :/. It would be nice if it could queue the guest actions, instead of dropping them.

Quoted 8 lines

Yes, I did look at that briefly; it's not trivial; for
example consider the situation where the guest discards some pages by inflating, and then later deflates, it expects to lose that data but then starts accessing that physical page again.
If you replay that sequence at the end then you've lost newly accessed pages. So you have to filter out inflates that have been deflated later, and have to order those correctly with the sense of changes made to those pages after the deflation occurs.

Ah, yes, I see.

Signature · 4 lines
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson