Skip to contentSkip to conversation

migration: defer a post_load which only rearranges memory

PATCH In review Denis V. Lunev 3 participants 15 messages Sep 11 – Nov 5

lore
Share & tools
lore
#0 lore raw

cover migration: defer a post_load which only rearranges memory

Restoring a big Windows guest spends most of its destination-side time in post_load hooks which do nothing but move memory regions around. Each one ends a memory transaction, and a transaction commit re-renders every flatview it touches at a cost which grows with the number of regions in the machine. A hook which runs once per vCPU therefore pays that render once per vCPU, and the machine gets slower to migrate the bigger it is.

The Hyper-V SynIC is the case that hurts: restoring the synthetic interrupt controller maps a message page and an event page per vCPU, so a 64-vCPU guest forces 128 remaps, each with its own rebuild, while the rest of the stream is still being read.

Patch 1 adds post_load_deferrable. A vmsd which sets it has its hook queued during the load and run once the stream has been consumed, in the order the hooks would have fired, with the whole drain sharing one memory transaction. Patch 2 sets it on the SynIC subsection.

It is opt-in rather than automatic, and the three preconditions are spelled out on the field: the hook must not fail, nothing later in the load may depend on what it does, and it must not read guest memory or resolve an address space. A hook which breaks the first is fatal rather than silently reported, because by drain time the source may already have been told the migration succeeded.

Deferring is not free in general, which is the other reason it is opt-in. Deferring the APIC post_load, whose cost is a synchronous run_on_cpu per vCPU rather than a memory remap, moves 3 ms out of the section walk and pays about 9 ms of drain for it. Deferral helps a hook which repeats topology work; it makes a hook which does cross-thread work worse.

Measurements
------------

Destination-side non-iterable load, ie. the sum of vmstate_downtime_load over non-iterable sections, on a guest which has actually programmed its Hyper-V state. Five interleaved rounds per point on an otherwise idle host, twice; medians, with the spread across all ten rounds.

  upstream                          377 ms   (363-400)
  + pci mapping transactions        247 ms   (242-255)
  + this series                      96 ms   (86-97)

Two postings against one problem, so the whole ladder is shown. The first step is a pci pair which batches a device's BAR and bridge window updates into a single transaction, posted separately and now queued in Michael's tree:

https://lore.kernel.org/qemu-devel/[email protected]/

Those two are listed because they change what a rebuild costs, and so change what this series is worth. Together the postings take the load from 377 ms to 96 ms; this series is the 247 ms to 96 ms step.

Where it goes: the cpu sections fall from 154 ms to 1.3 ms. The deferred hooks themselves cost 77 us at the drain, so the work is removed rather than moved somewhere the per-section metric cannot see.

The saving scales with vCPU count, since that is how many times the remap repeats, and with the number of memory regions in the machine, since that is what a rebuild costs.

Guest under test
----------------

Windows Server 2022, installed unattended, idle at the console:

-machine q35,accel=kvm
-cpu host,hv-synic,hv-stimer,hv-stimer-direct,hv-vapic,hv-runtime,

       hv-time,hv-ipi,hv-crash,hv-reset,hv-frequencies,hv-vpindex,
       hv-spinlocks=0x1fff

-smp 64,sockets=2,cores=32,threads=1
-m 4G
65 pcie-root-ports, 9 virtio devices behind them, qxl

Host: AMD EPYC 7443P, 24 cores / 48 threads.

hv-synic is the flag that matters. Without it the guest never programs the SynIC pages and the effect under test does not exist.

Measured with a save/restore harness rather than a live migration: a restore from a captured stream walks the same qemu_loadvm_state_main() path a destination does, which removes libvirt, the network and the second host from the measurement.

CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Paolo Bonzini <[email protected]>
CC Zhao Liu <[email protected]>

Denis V. Lunev (2):
migration: let a vmstate defer its post_load to end of stream target/i386: defer the Hyper-V SynIC post_load

 include/migration/vmstate.h |  40 +++++++++++++
 migration/savevm.c          |  23 ++++++++
 migration/vmstate.c         |  67 +++++++++++++++++++++-
 target/i386/machine.c       |   1 +
 tests/unit/test-vmstate.c   | 111 ++++++++++++++++++++++++++++++++++++
 5 files changed, 240 insertions(+), 2 deletions(-)
Signature · 1 line
2.53.0
#1 lore raw

PATCH 1/2 migration: let a vmstate defer its post_load to end of stream

From: Denis V. Lunev <[email protected]>

A post_load hook which only rearranges the memory topology forces a flatview rebuild as its section is read, and the cost of a rebuild grows with the number of regions in the machine. A device which does this once per vCPU therefore scales badly on the destination.

Add post_load_deferrable. A vmsd which sets it has its hook queued during the load and run once the stream has been consumed, in the order the hooks would have fired, with the whole drain sharing one memory transaction.

Opt-in, because deferral is not free in general. A hook which can fail must not be deferred: failing after the stream is consumed means the source has already been told the migration succeeded, and may release a guest the destination never started. A hook which reads guest memory must not be deferred either, since the drain runs with the topology in flux. Postcopy is excluded because its listen thread walks the same stream concurrently.

CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Paolo Bonzini <[email protected]>
CC Zhao Liu <[email protected]>
---
 include/migration/vmstate.h |  40 +++++++++++++
 migration/savevm.c          |  23 ++++++++
 migration/vmstate.c         |  67 +++++++++++++++++++++-
 tests/unit/test-vmstate.c   | 111 ++++++++++++++++++++++++++++++++++++
 4 files changed, 239 insertions(+), 2 deletions(-)
include/migration/vmstate.h +40 -0
index e72c3fae9a..16045319d5 100644
@@ -303,6 +303,29 @@ struct VMStateDescription {
     bool (*pre_load_errp)(void *opaque, Error **errp);
     int (*post_load)(void *opaque, int version_id);
     bool (*post_load_errp)(void *opaque, int version_id, Error **errp);
+
+    /*
+     * Run .post_load() once the whole stream has been loaded rather than
+     * as this section is read, so that it sees a machine whose devices
+     * have all been restored, and so that several of them can share the
+     * work they would each repeat.
+     *
+     * Three things must hold of a hook before it may be deferred.
+     *
+     * It must not fail. By the time the queue is drained the stream has
+     * been consumed, so a source may already have been told the migration
+     * succeeded and may have released the guest; there is nothing left to
+     * report a failure to. A hook which fails here is a bug in its vmsd
+     * and is fatal.
+     *
+     * Nothing else in the load may depend on what it does. The hooks run
+     * after every section has been read, so anything a later section needs
+     * to observe must not be produced here.
+     *
+     * It must not read guest memory or resolve an address space, because
+     * the drain runs as one batch with the memory topology in flux.
+     */
+    bool post_load_deferrable;
     int (*pre_save)(void *opaque);
     bool (*pre_save_errp)(void *opaque, Error **errp);
 
@@ -1299,6 +1322,23 @@ bool vmstate_save_vmsd(QEMUFile *f, const VMStateDescription *vmsd,
 
 bool vmstate_section_needed(const VMStateDescription *vmsd, void *opaque);
 
+/**
+ * vmstate_post_load_defer_begin: Queue deferrable post_load hooks
+ *
+ * Between this and vmstate_post_load_defer_finish(), a post_load hook whose
+ * vmsd sets post_load_deferrable is recorded rather than called. Hooks are
+ * queued in the order they would have run.
+ */
+void vmstate_post_load_defer_begin(void);
+
+/**
+ * vmstate_post_load_defer_finish: Stop deferring and drain the queue
+ * @run: run the queued hooks, in order; when false, discard them
+ *
+ * Returns false if a hook failed, in which case the rest are discarded.
+ */
+bool vmstate_post_load_defer_finish(bool run, Error **errp);
+
 #define  VMSTATE_INSTANCE_ID_ANY  -1
 
 /* Returns: 0 on success, -1 on failure */
migration/savevm.c +23 -0
index 4b590ea672..2352dcf684 100644
@@ -3128,6 +3128,7 @@ int qemu_loadvm_state(QEMUFile *f, Error **errp)
 {
     MigrationState *s = migrate_get_current();
     MigrationIncomingState *mis = migration_incoming_get_current();
+    bool defer_post_load;
     int ret;
 
     if (qemu_savevm_state_blocked(errp)) {
@@ -3147,7 +3148,29 @@ int qemu_loadvm_state(QEMUFile *f, Error **errp)
 
     cpu_synchronize_all_pre_loadvm();
 
+    /*
+     * The postcopy listen thread walks the same stream concurrently, so the
+     * queue would need locking and a defined owner for the drain.
+     */
+    defer_post_load = !migrate_postcopy_ram();
+    if (defer_post_load) {
+        vmstate_post_load_defer_begin();
+    }
+
     ret = qemu_loadvm_state_main(f, mis, errp);
+
+    if (defer_post_load) {
+        /*
+         * A deferrable hook only rearranges the memory topology, so the
+         * whole drain can share one flatview rebuild.
+         */
+        memory_region_transaction_begin();
+        if (!vmstate_post_load_defer_finish(ret == 0, errp)) {
+            ret = -EINVAL;
+        }
+        memory_region_transaction_commit();
+    }
+
     qemu_event_set(&mis->main_thread_load_event);
 
     trace_qemu_loadvm_state_post_main(ret);
migration/vmstate.c +65 -2

79 lines not on this page · raw message

tests/unit/test-vmstate.c +111 -0

123 lines not on this page · raw message

Signature · 1 line
2.53.0
#2 lore raw

Re: [PATCH 1/2] migration: let a vmstate defer its post_load to end of stream

Quoted 103 lines · Denis V. Lunev

From: Denis V. Lunev <[email protected]>

A post_load hook which only rearranges the memory topology forces a flatview rebuild as its section is read, and the cost of a rebuild grows with the number of regions in the machine. A device which does this once per vCPU therefore scales badly on the destination.

Add post_load_deferrable. A vmsd which sets it has its hook queued during the load and run once the stream has been consumed, in the order the hooks would have fired, with the whole drain sharing one memory transaction.

Opt-in, because deferral is not free in general. A hook which can fail must not be deferred: failing after the stream is consumed means the source has already been told the migration succeeded, and may release a guest the destination never started. A hook which reads guest memory must not be deferred either, since the drain runs with the topology in flux. Postcopy is excluded because its listen thread walks the same stream concurrently.

CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Paolo Bonzini <[email protected]>
CC Zhao Liu <[email protected]>
---
 include/migration/vmstate.h |  40 +++++++++++++
 migration/savevm.c          |  23 ++++++++
 migration/vmstate.c         |  67 +++++++++++++++++++++-
 tests/unit/test-vmstate.c   | 111 ++++++++++++++++++++++++++++++++++++
 4 files changed, 239 insertions(+), 2 deletions(-)
include/migration/vmstate.h +40 -0
index e72c3fae9a..16045319d5 100644
@@ -303,6 +303,29 @@ struct VMStateDescription {
     bool (*pre_load_errp)(void *opaque, Error **errp);
     int (*post_load)(void *opaque, int version_id);
     bool (*post_load_errp)(void *opaque, int version_id, Error **errp);
+
+    /*
+     * Run .post_load() once the whole stream has been loaded rather than
+     * as this section is read, so that it sees a machine whose devices
+     * have all been restored, and so that several of them can share the
+     * work they would each repeat.
+     *
+     * Three things must hold of a hook before it may be deferred.
+     *
+     * It must not fail. By the time the queue is drained the stream has
+     * been consumed, so a source may already have been told the migration
+     * succeeded and may have released the guest; there is nothing left to
+     * report a failure to. A hook which fails here is a bug in its vmsd
+     * and is fatal.
+     *
+     * Nothing else in the load may depend on what it does. The hooks run
+     * after every section has been read, so anything a later section needs
+     * to observe must not be produced here.
+     *
+     * It must not read guest memory or resolve an address space, because
+     * the drain runs as one batch with the memory topology in flux.
+     */
+    bool post_load_deferrable;
     int (*pre_save)(void *opaque);
     bool (*pre_save_errp)(void *opaque, Error **errp);
 
@@ -1299,6 +1322,23 @@ bool vmstate_save_vmsd(QEMUFile *f, const VMStateDescription *vmsd,
 
 bool vmstate_section_needed(const VMStateDescription *vmsd, void *opaque);
 
+/**
+ * vmstate_post_load_defer_begin: Queue deferrable post_load hooks
+ *
+ * Between this and vmstate_post_load_defer_finish(), a post_load hook whose
+ * vmsd sets post_load_deferrable is recorded rather than called. Hooks are
+ * queued in the order they would have run.
+ */
+void vmstate_post_load_defer_begin(void);
+
+/**
+ * vmstate_post_load_defer_finish: Stop deferring and drain the queue
+ * @run: run the queued hooks, in order; when false, discard them
+ *
+ * Returns false if a hook failed, in which case the rest are discarded.
+ */
+bool vmstate_post_load_defer_finish(bool run, Error **errp);
+
 #define  VMSTATE_INSTANCE_ID_ANY  -1
 
 /* Returns: 0 on success, -1 on failure */
migration/savevm.c +1 -0
index 4b590ea672..2352dcf684 100644
@@ -3128,6 +3128,7 @@ int qemu_loadvm_state(QEMUFile *f, Error **errp)
 {
     MigrationState *s = migrate_get_current();
     MigrationIncomingState *mis = migration_incoming_get_current();
+    bool defer_post_load;
     int ret;
 
     if (qemu_savevm_state_blocked(errp)) {

migration/savevm.c int qemu_loadvm_state(QEMUFile *f, Error **errp) · line 3155

Quoted 8 lines
migration/savevm.c +5 -0
@@ -3147,7 +3148,29 @@ int qemu_loadvm_state(QEMUFile *f, Error **errp)
 
     cpu_synchronize_all_pre_loadvm();
 
+    /*
+     * The postcopy listen thread walks the same stream concurrently, so the
+     * queue would need locking and a defined owner for the drain.
+     */
+    defer_post_load = !migrate_postcopy_ram();

Just to mention we have two other paths that will enable this too:

qmp_xen_load_devices_state
load_snapshot

It looks all fine at least considering the hyper-v scope, but still raise this in case it's not expected.

The other thing is, IMHO we should enable this feature for both precopy and postcopy. Postcopy loads that in the package, please kindly share more on the above comment on disabling it; I didn't directly get that part.

migration/savevm.c int qemu_loadvm_state(QEMUFile *f, Error **errp) · line 3167

Quoted 12 lines
migration/savevm.c +11 -0
+    if (defer_post_load) {
+        vmstate_post_load_defer_begin();
+    }
+
     ret = qemu_loadvm_state_main(f, mis, errp);
+
+    if (defer_post_load) {
+        /*
+         * A deferrable hook only rearranges the memory topology, so the
+         * whole drain can share one flatview rebuild.
+         */
+        memory_region_transaction_begin();

IMHO we should document this behavior in the "deferrable" interface above, this is important knowledge to know that the whole deferred vmsd loads are wrapped with boosted transaction depths and all memory access is illegal.

AFAIU, that partly supplement my other reply, that the whole thing is not about "defer" or not, but about "batching MR update". It can still be at the end of course, but it's not the major goal, the major goal is about memory updates.

Thanks,

Quoted 5 lines
migration/savevm.c +5 -0
+        if (!vmstate_post_load_defer_finish(ret == 0, errp)) {
+            ret = -EINVAL;
+        }
+        memory_region_transaction_commit();
+    }
Signature · 1 line
Peter Xu
#3 lore raw

PATCH 2/2 target/i386: defer the Hyper-V SynIC post_load

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

hyperv_synic_post_load() maps the SynIC message and event pages, and a guest which has programmed the SynIC carries the subsection on every vCPU, so restoring one rebuilds the flatview per vCPU rather than once.

The hook cannot fail and does not read guest memory, so it can run with the rest of the deferred hooks once the stream has been consumed. The saving scales with vCPU count.

CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Paolo Bonzini <[email protected]>
CC Zhao Liu <[email protected]>
---
 target/i386/machine.c | 1 +
 1 file changed, 1 insertion(+)
target/i386/machine.c +1 -0
index 8d69d7e25e..eae74e33de 100644
@@ -873,6 +873,7 @@ static const VMStateDescription vmstate_msr_hyperv_synic = {
     .minimum_version_id = 1,
     .needed = hyperv_synic_enable_needed,
     .post_load = hyperv_synic_post_load,
+    .post_load_deferrable = true,
     .fields = (const VMStateField[]) {
         VMSTATE_UINT64(env.msr_hv_synic_control, X86CPU),
         VMSTATE_UINT64(env.msr_hv_synic_evt_page, X86CPU),
Signature · 1 line
2.53.0
#4 lore raw
In reply to Denis V. Lunev
Quoted 94 lines · Denis V. Lunev

Restoring a big Windows guest spends most of its destination-side time in post_load hooks which do nothing but move memory regions around. Each one ends a memory transaction, and a transaction commit re-renders every flatview it touches at a cost which grows with the number of regions in the machine. A hook which runs once per vCPU therefore pays that render once per vCPU, and the machine gets slower to migrate the bigger it is.

The Hyper-V SynIC is the case that hurts: restoring the synthetic interrupt controller maps a message page and an event page per vCPU, so a 64-vCPU guest forces 128 remaps, each with its own rebuild, while the rest of the stream is still being read.

Patch 1 adds post_load_deferrable. A vmsd which sets it has its hook queued during the load and run once the stream has been consumed, in the order the hooks would have fired, with the whole drain sharing one memory transaction. Patch 2 sets it on the SynIC subsection.

It is opt-in rather than automatic, and the three preconditions are spelled out on the field: the hook must not fail, nothing later in the load may depend on what it does, and it must not read guest memory or resolve an address space. A hook which breaks the first is fatal rather than silently reported, because by drain time the source may already have been told the migration succeeded.

Deferring is not free in general, which is the other reason it is opt-in. Deferring the APIC post_load, whose cost is a synchronous run_on_cpu per vCPU rather than a memory remap, moves 3 ms out of the section walk and pays about 9 ms of drain for it. Deferral helps a hook which repeats topology work; it makes a hook which does cross-thread work worse.

Measurements
------------

Destination-side non-iterable load, ie. the sum of vmstate_downtime_load over non-iterable sections, on a guest which has actually programmed its Hyper-V state. Five interleaved rounds per point on an otherwise idle host, twice; medians, with the spread across all ten rounds.

  upstream                          377 ms   (363-400)
  + pci mapping transactions        247 ms   (242-255)
  + this series                      96 ms   (86-97)

Two postings against one problem, so the whole ladder is shown. The first step is a pci pair which batches a device's BAR and bridge window updates into a single transaction, posted separately and now queued in Michael's tree:

https://lore.kernel.org/qemu-devel/[email protected]/

Those two are listed because they change what a rebuild costs, and so change what this series is worth. Together the postings take the load from 377 ms to 96 ms; this series is the 247 ms to 96 ms step.

Where it goes: the cpu sections fall from 154 ms to 1.3 ms. The deferred hooks themselves cost 77 us at the drain, so the work is removed rather than moved somewhere the per-section metric cannot see.

The saving scales with vCPU count, since that is how many times the remap repeats, and with the number of memory regions in the machine, since that is what a rebuild costs.

Guest under test
----------------

Windows Server 2022, installed unattended, idle at the console:

-machine q35,accel=kvm
-cpu host,hv-synic,hv-stimer,hv-stimer-direct,hv-vapic,hv-runtime,

       hv-time,hv-ipi,hv-crash,hv-reset,hv-frequencies,hv-vpindex,
       hv-spinlocks=0x1fff

-smp 64,sockets=2,cores=32,threads=1
-m 4G
65 pcie-root-ports, 9 virtio devices behind them, qxl

Host: AMD EPYC 7443P, 24 cores / 48 threads.

hv-synic is the flag that matters. Without it the guest never programs the SynIC pages and the effect under test does not exist.

Measured with a save/restore harness rather than a live migration: a restore from a captured stream walks the same qemu_loadvm_state_main() path a destination does, which removes libvirt, the network and the second host from the measurement.

CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Paolo Bonzini <[email protected]>
CC Zhao Liu <[email protected]>

Denis V. Lunev (2):
migration: let a vmstate defer its post_load to end of stream target/i386: defer the Hyper-V SynIC post_load

Quoted 7 lines
 include/migration/vmstate.h |  40 +++++++++++++
 migration/savevm.c          |  23 ++++++++
 migration/vmstate.c         |  67 +++++++++++++++++++++-
 target/i386/machine.c       |   1 +
 tests/unit/test-vmstate.c   | 111 ++++++++++++++++++++++++++++++++++++
 5 files changed, 240 insertions(+), 2 deletions(-)

please disregard this for now. I'll come back with v2 which will put as around 30 ms.

Flatview rebuild should be optimized.

Sorry for noise,
    Den

#5 lore raw
In reply to Denis V. Lunev
Quoted 11 lines · Denis V. Lunev

Restoring a big Windows guest spends most of its destination-side time in post_load hooks which do nothing but move memory regions around. Each one ends a memory transaction, and a transaction commit re-renders every flatview it touches at a cost which grows with the number of regions in the machine. A hook which runs once per vCPU therefore pays that render once per vCPU, and the machine gets slower to migrate the bigger it is.

The Hyper-V SynIC is the case that hurts: restoring the synthetic interrupt controller maps a message page and an event page per vCPU, so a 64-vCPU guest forces 128 remaps, each with its own rebuild, while the rest of the stream is still being read.

This is partly a known issue, not from Hyper-V, but from virtio mmio regions.. please see:

https://wiki.qemu.org/ToDo/LiveMigration#Optimize_memory_updates_for_non-iterative_vmstates
https://lore.kernel.org/r/[email protected]

I believe we also thought about do MR update per-device, so batching but smaller scale, easier to make sure no illegal access to a stale flatview.

So in general, I agree this approach might be the right way to do, which is to shrink the transaction to be smaller than "batch everything".. as what Chuang used to do. I still have some pure questions inline.

Quoted 2 lines

Patch 1 adds post_load_deferrable. A vmsd which sets it has its hook

Nit, IMHO if so it needs to be called "deferred", as "deferrable" implies the defer is optional.

Quoted 6 lines

queued during the load and run once the stream has been consumed, in the order the hooks would have fired, with the whole drain sharing one memory transaction. Patch 2 sets it on the SynIC subsection.

It is opt-in rather than automatic, and the three preconditions are spelled out on the field: the hook must not fail, nothing later in the

Actually, I _think_ maybe it can still fail.. IIUC source QEMU only dies if it receives shut from migrate_send_rp_shut(), which is after the deferred loads at least with the current change. Worth check..

Quoted 2 lines

load may depend on what it does, and it must not read guest memory or resolve an address space.

Yes, but I think this is partial of the whole picture: IIUC if this deferred hook may inject some MRs that may be accessed by other VMSD loaders, or anything (including hard-coded loading process), I think it's an issue too.

So personally I don't like this API very much yet on how it was defined; it'll be very hard to be used right unless we fully understand what will happen..

I wonder if there's better way to define the API to be clearer.

Since all the known issues about this is about MR updates: virtio MMIO regions, hyper-v, pci bar/bridge (mentioned below), I wonder if this can be something dedicated to MR updates, and maybe it doesn't need to be "deferred", just grouped together properly into one transaction, which can happen in the middle too or maybe it doesn't matter much. Then it applies some form of limitation to what can be split out from normal VMSD flow. The current API relies on allowing to defer anything, which is fine but very hard to control, and we may face tricky bugs if users grows but when they're not used right..

Quoted 8 lines

A hook which breaks the first is fatal rather
than silently reported, because by drain time the source may already have been told the migration succeeded.

Deferring is not free in general, which is the other reason it is opt-in. Deferring the APIC post_load, whose cost is a synchronous run_on_cpu per vCPU rather than a memory remap, moves 3 ms out of the section walk and pays about 9 ms of drain for it. Deferral helps a hook which repeats

I'm just curious: why something will take 9ms if deferred, even if it used to take 3ms? I think I misread something, but I can't tell myself.

Quoted 5 lines

topology work; it makes a hook which does cross-thread work worse.

Measurements
------------

Quoted 8 lines

Destination-side non-iterable load, ie. the sum of vmstate_downtime_load over non-iterable sections, on a guest which has actually programmed its Hyper-V state. Five interleaved rounds per point on an otherwise idle host, twice; medians, with the spread across all ten rounds.

  upstream                          377 ms   (363-400)
  + pci mapping transactions        247 ms   (242-255)
  + this series                      96 ms   (86-97)

Definitely a great improvement. I think we need this, just one way or another. I may have some other trivial comments later in the patch. Thanks for working on it.

Quoted 63 lines

Two postings against one problem, so the whole ladder is shown. The first step is a pci pair which batches a device's BAR and bridge window updates into a single transaction, posted separately and now queued in Michael's tree:

https://lore.kernel.org/qemu-devel/[email protected]/

Those two are listed because they change what a rebuild costs, and so change what this series is worth. Together the postings take the load from 377 ms to 96 ms; this series is the 247 ms to 96 ms step.

Where it goes: the cpu sections fall from 154 ms to 1.3 ms. The deferred hooks themselves cost 77 us at the drain, so the work is removed rather than moved somewhere the per-section metric cannot see.

The saving scales with vCPU count, since that is how many times the remap repeats, and with the number of memory regions in the machine, since that is what a rebuild costs.

Guest under test
----------------

Windows Server 2022, installed unattended, idle at the console:

-machine q35,accel=kvm
-cpu host,hv-synic,hv-stimer,hv-stimer-direct,hv-vapic,hv-runtime,

       hv-time,hv-ipi,hv-crash,hv-reset,hv-frequencies,hv-vpindex,
       hv-spinlocks=0x1fff

-smp 64,sockets=2,cores=32,threads=1
-m 4G
65 pcie-root-ports, 9 virtio devices behind them, qxl

Host: AMD EPYC 7443P, 24 cores / 48 threads.

hv-synic is the flag that matters. Without it the guest never programs the SynIC pages and the effect under test does not exist.

Measured with a save/restore harness rather than a live migration: a restore from a captured stream walks the same qemu_loadvm_state_main() path a destination does, which removes libvirt, the network and the second host from the measurement.

CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Paolo Bonzini <[email protected]>
CC Zhao Liu <[email protected]>

Denis V. Lunev (2):
migration: let a vmstate defer its post_load to end of stream target/i386: defer the Hyper-V SynIC post_load

 include/migration/vmstate.h |  40 +++++++++++++
 migration/savevm.c          |  23 ++++++++
 migration/vmstate.c         |  67 +++++++++++++++++++++-
 target/i386/machine.c       |   1 +
 tests/unit/test-vmstate.c   | 111 ++++++++++++++++++++++++++++++++++++
 5 files changed, 240 insertions(+), 2 deletions(-)
Signature · 1 line
2.53.0
Signature · 1 line
Peter Xu
#6 lore raw
Quoted 83 lines · Peter Xu
Quoted 11 lines · Denis V. Lunev

Restoring a big Windows guest spends most of its destination-side time in post_load hooks which do nothing but move memory regions around. Each one ends a memory transaction, and a transaction commit re-renders every flatview it touches at a cost which grows with the number of regions in the machine. A hook which runs once per vCPU therefore pays that render once per vCPU, and the machine gets slower to migrate the bigger it is.

The Hyper-V SynIC is the case that hurts: restoring the synthetic interrupt controller maps a message page and an event page per vCPU, so a 64-vCPU guest forces 128 remaps, each with its own rebuild, while the rest of the stream is still being read.

This is partly a known issue, not from Hyper-V, but from virtio mmio regions.. please see:

https://wiki.qemu.org/ToDo/LiveMigration#Optimize_memory_updates_for_non-iterative_vmstates
https://lore.kernel.org/r/[email protected]

I believe we also thought about do MR update per-device, so batching but smaller scale, easier to make sure no illegal access to a stale flatview.

So in general, I agree this approach might be the right way to do, which is to shrink the transaction to be smaller than "batch everything".. as what Chuang used to do. I still have some pure questions inline.

Quoted 1 line

Patch 1 adds post_load_deferrable. A vmsd which sets it has its hook

Nit, IMHO if so it needs to be called "deferred", as "deferrable" implies the defer is optional.

Quoted 6 lines

queued during the load and run once the stream has been consumed, in the order the hooks would have fired, with the whole drain sharing one memory transaction. Patch 2 sets it on the SynIC subsection.

It is opt-in rather than automatic, and the three preconditions are spelled out on the field: the hook must not fail, nothing later in the

Actually, I _think_ maybe it can still fail.. IIUC source QEMU only dies if it receives shut from migrate_send_rp_shut(), which is after the deferred loads at least with the current change. Worth check..

Quoted 2 lines

load may depend on what it does, and it must not read guest memory or resolve an address space.

Yes, but I think this is partial of the whole picture: IIUC if this deferred hook may inject some MRs that may be accessed by other VMSD loaders, or anything (including hard-coded loading process), I think it's an issue too.

So personally I don't like this API very much yet on how it was defined; it'll be very hard to be used right unless we fully understand what will happen..

I wonder if there's better way to define the API to be clearer.

Since all the known issues about this is about MR updates: virtio MMIO regions, hyper-v, pci bar/bridge (mentioned below), I wonder if this can be something dedicated to MR updates, and maybe it doesn't need to be "deferred", just grouped together properly into one transaction, which can happen in the middle too or maybe it doesn't matter much. Then it applies some form of limitation to what can be split out from normal VMSD flow. The current API relies on allowing to defer anything, which is fine but very hard to control, and we may face tricky bugs if users grows but when they're not used right..

Quoted 8 lines

A hook which breaks the first is fatal rather
than silently reported, because by drain time the source may already have been told the migration succeeded.

Deferring is not free in general, which is the other reason it is opt-in. Deferring the APIC post_load, whose cost is a synchronous run_on_cpu per vCPU rather than a memory remap, moves 3 ms out of the section walk and pays about 9 ms of drain for it. Deferral helps a hook which repeats

I'm just curious: why something will take 9ms if deferred, even if it used to take 3ms? I think I misread something, but I can't tell myself.

Quoted 10 lines

topology work; it makes a hook which does cross-thread work worse.

Measurements
------------

Destination-side non-iterable load, ie. the sum of vmstate_downtime_load over non-iterable sections, on a guest which has actually programmed its Hyper-V state. Five interleaved rounds per point on an otherwise idle host, twice; medians, with the spread across all ten rounds.

Quoted 6 lines
Quoted 3 lines
  upstream                          377 ms   (363-400)
  + pci mapping transactions        247 ms   (242-255)
  + this series                      96 ms   (86-97)

Definitely a great improvement. I think we need this, just one way or another. I may have some other trivial comments later in the patch. Thanks for working on it.

Right now I have series staying at 32 ms with boost to ordinary QEMU startup, that is why I have said that I'll send follow up. This patch will be included along as flatview rebuild on startup.

Anyway, right now I need to understand and eat your notes to send v2. This just intersects with upcoming release of downstream, but this change is in my priority list and I hope to finish v2 early next week.

Thank you for you time,
    Den

#7 lore raw
Quoted 8 lines · Denis V. Lunev

Right now I have series staying at 32 ms with boost to ordinary QEMU startup, that is why I have said that I'll send follow up. This patch will be included along as flatview rebuild on startup.

Anyway, right now I need to understand and eat your notes to send v2. This just intersects with upcoming release of downstream, but this change is in my priority list and I hope to finish v2 early next week.

Ah I didn't notice the other email when replying... Take your time, feel free to take whatever comments still makes sense to you, thanks.

Signature · 1 line
Peter Xu
#8 lore raw

PATCH v2 1/6 memory: publish a dispatch tree only once it is complete

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

generate_memory_topology() assigns view->dispatch and then fills the tree through it, because flatview_add_to_dispatch() reaches the dispatch back through the view. Nothing can observe the half-built tree today, since the view is not published to an address space until the render returns, but the ordering is there to trip over the moment anything builds a tree for a view which is already visible.

Pass the dispatch down instead of routing it through the view, and store it into the view once it is built. Extract the build into flatview_build_dispatch() while doing so, since that is the natural unit to publish.

CC Paolo Bonzini <[email protected]>
CC Peter Xu <[email protected]>
CC Philippe Mathieu-Daude <[email protected]>
CC Fabiano Rosas <[email protected]>
---
 system/memory-internal.h |  4 +++-
 system/memory.c          | 27 +++++++++++++++++++--------
 system/physmem.c         | 16 ++++++++--------
 3 files changed, 30 insertions(+), 17 deletions(-)
system/memory-internal.h +3 -1
index b2b9b5b0c5..d06c136744 100644
@@ -32,7 +32,9 @@ void flatview_unref(FlatView *view);
 
 extern const MemoryRegionOps unassigned_mem_ops;
 
-void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section);
+void flatview_build_dispatch(FlatView *fv);
+void flatview_add_to_dispatch(FlatView *fv, AddressSpaceDispatch *d,
+                              MemoryRegionSection *section);
 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv);
 void address_space_dispatch_compact(AddressSpaceDispatch *d);
 void address_space_dispatch_free(AddressSpaceDispatch *d);
system/memory.c +19 -8
index 56c5dd6c8a..33bd97c9a3 100644
@@ -745,10 +745,27 @@ static MemoryRegion *memory_region_get_flatview_root(MemoryRegion *mr)
     return NULL;
 }
 
+void flatview_build_dispatch(FlatView *view)
+{
+    AddressSpaceDispatch *d;
+    int i;
+
+    assert(!view->dispatch);
+
+    d = address_space_dispatch_new(view);
+    for (i = 0; i < view->nr; i++) {
+        MemoryRegionSection mrs =
+            section_from_flat_range(&view->ranges[i], view);
+        flatview_add_to_dispatch(view, d, &mrs);
+    }
+    address_space_dispatch_compact(d);
+
+    qatomic_rcu_set(&view->dispatch, d);
+}
+
 /* Render a memory topology into a list of disjoint absolute ranges. */
 static FlatView *generate_memory_topology(MemoryRegion *mr)
 {
-    int i;
     FlatView *view;
 
     view = flatview_new(mr);
@@ -760,13 +777,7 @@ static FlatView *generate_memory_topology(MemoryRegion *mr)
     }
     flatview_simplify(view);
 
-    view->dispatch = address_space_dispatch_new(view);
-    for (i = 0; i < view->nr; i++) {
-        MemoryRegionSection mrs =
-            section_from_flat_range(&view->ranges[i], view);
-        flatview_add_to_dispatch(view, &mrs);
-    }
-    address_space_dispatch_compact(view->dispatch);
+    flatview_build_dispatch(view);
     g_hash_table_replace(flat_views, mr, view);
 
     return view;
system/physmem.c +8 -8
index a7300bb9d9..2cfdb1e6b4 100644
@@ -1350,9 +1350,9 @@ static void phys_sections_free(PhysPageMap *map)
     g_free(map->nodes);
 }
 
-static void register_subpage(FlatView *fv, MemoryRegionSection *section)
+static void register_subpage(FlatView *fv, AddressSpaceDispatch *d,
+                             MemoryRegionSection *section)
 {
-    AddressSpaceDispatch *d = flatview_to_dispatch(fv);
     subpage_t *subpage;
     hwaddr base = section->offset_within_address_space
         & TARGET_PAGE_MASK;
@@ -1381,10 +1381,9 @@ static void register_subpage(FlatView *fv, MemoryRegionSection *section)
 }
 
 
-static void register_multipage(FlatView *fv,
+static void register_multipage(FlatView *fv, AddressSpaceDispatch *d,
                                MemoryRegionSection *section)
 {
-    AddressSpaceDispatch *d = flatview_to_dispatch(fv);
     hwaddr start_addr = section->offset_within_address_space;
     uint16_t section_index = phys_section_add(&d->map, section);
     uint64_t num_pages = int128_get64(int128_rshift(section->size,
@@ -1401,7 +1400,8 @@ static void register_multipage(FlatView *fv,
  *
  * where s stands for subpage and P for page.
  */
-void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
+void flatview_add_to_dispatch(FlatView *fv, AddressSpaceDispatch *d,
+                              MemoryRegionSection *section)
 {
     MemoryRegionSection remain = *section;
     Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
@@ -1413,7 +1413,7 @@ void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
 
         MemoryRegionSection now = remain;
         now.size = int128_min(int128_make64(left), now.size);
-        register_subpage(fv, &now);
+        register_subpage(fv, d, &now);
         if (int128_eq(remain.size, now.size)) {
             return;
         }
@@ -1426,7 +1426,7 @@ void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
     if (int128_ge(remain.size, page_size)) {
         MemoryRegionSection now = remain;
         now.size = int128_and(now.size, int128_neg(page_size));
-        register_multipage(fv, &now);
+        register_multipage(fv, d, &now);
         if (int128_eq(remain.size, now.size)) {
             return;
         }
@@ -1436,7 +1436,7 @@ void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
     }
 
     /* register last subpage */
-    register_subpage(fv, &remain);
+    register_subpage(fv, d, &remain);
 }
 
 void qemu_flush_coalesced_mmio_buffer(void)
Signature · 1 line
2.53.0
#9 lore raw

PATCH v2 2/6 physmem: pass the FlatView to address_space_translate_internal

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

address_space_translate_internal() takes the dispatch, so every caller resolves the view to its tree first and the tree is the only structure a lookup can go through. Take the view instead and let the lookup reach the tree, so that a view which answers some other way is expressible.

No functional change: every caller already had the view, or an address space to take it from.

CC Paolo Bonzini <[email protected]>
CC Peter Xu <[email protected]>
CC Philippe Mathieu-Daude <[email protected]>
CC Fabiano Rosas <[email protected]>
---
 system/memory-internal.h | 11 -----------
 system/physmem.c         | 25 ++++++++++++-------------
 2 files changed, 12 insertions(+), 24 deletions(-)
system/memory-internal.h +0 -11
index d06c136744..d81881ba54 100644
@@ -16,17 +16,6 @@
 
 void machine_memory_init(void);
 
-static inline AddressSpaceDispatch *flatview_to_dispatch(FlatView *fv)
-{
-    return fv->dispatch;
-}
-
-static inline
-AddressSpaceDispatch *address_space_to_dispatch(const AddressSpace *as)
-{
-    return flatview_to_dispatch(address_space_to_flatview(as));
-}
-
 FlatView *address_space_get_flatview(const AddressSpace *as);
 void flatview_unref(FlatView *view);
 
system/physmem.c +12 -13
index 2cfdb1e6b4..6f11e31799 100644
@@ -361,14 +361,14 @@ static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
 
 /* Called from RCU critical section */
 static MemoryRegionSection *
-address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
+address_space_translate_internal(FlatView *fv, hwaddr addr, hwaddr *xlat,
                                  hwaddr *plen, bool resolve_subpage)
 {
     MemoryRegionSection *section;
     MemoryRegion *mr;
     Int128 diff;
 
-    section = address_space_lookup_region(d, addr, resolve_subpage);
+    section = address_space_lookup_region(fv->dispatch, addr, resolve_subpage);
     /* Compute offset within MemoryRegionSection */
     addr -= section->offset_within_address_space;
 
@@ -453,7 +453,7 @@ static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iomm
         *target_as = iotlb.target_as;
 
         section = address_space_translate_internal(
-                address_space_to_dispatch(iotlb.target_as), addr, xlat,
+                address_space_to_flatview(iotlb.target_as), addr, xlat,
                 plen_out, is_mmio);
 
         iommu_mr = memory_region_get_iommu(section->mr);
@@ -506,9 +506,8 @@ static MemoryRegionSection flatview_do_translate(FlatView *fv,
         plen_out = &plen;
     }
 
-    section = address_space_translate_internal(
-            flatview_to_dispatch(fv), addr, xlat,
-            plen_out, is_mmio);
+    section = address_space_translate_internal(fv, addr, xlat,
+                                               plen_out, is_mmio);
 
     iommu_mr = memory_region_get_iommu(section->mr);
     if (unlikely(iommu_mr)) {
@@ -691,10 +690,11 @@ address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr orig_addr,
     IOMMUTLBEntry iotlb;
     int iommu_idx;
     hwaddr addr = orig_addr;
-    AddressSpaceDispatch *d = address_space_to_dispatch(cpu->cpu_ases[asidx].as);
+    FlatView *fv = address_space_to_flatview(cpu->cpu_ases[asidx].as);
 
     for (;;) {
-        section = address_space_translate_internal(d, addr, &addr, plen, false);
+        section = address_space_translate_internal(fv, addr, &addr, plen,
+                                                   false);
 
         iommu_mr = memory_region_get_iommu(section->mr);
         if (!iommu_mr) {
@@ -726,7 +726,7 @@ address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr orig_addr,
             goto translate_fail;
         }
 
-        d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
+        fv = address_space_to_flatview(iotlb.target_as);
     }
 
     assert(!memory_region_is_iommu(section->mr));
@@ -744,7 +744,7 @@ translate_fail:
      */
     assert((orig_addr & ~TARGET_PAGE_MASK) == 0);
     *xlat = orig_addr;
-    return &d->map.sections[PHYS_SECTION_UNASSIGNED];
+    return &fv->dispatch->map.sections[PHYS_SECTION_UNASSIGNED];
 }
 
 #endif /* CONFIG_TCG */
@@ -3886,7 +3886,6 @@ int64_t address_space_cache_init(MemoryRegionCache *cache,
                                  hwaddr len,
                                  bool is_write)
 {
-    AddressSpaceDispatch *d;
     hwaddr l;
     MemoryRegion *mr;
     Int128 diff;
@@ -3895,8 +3894,8 @@ int64_t address_space_cache_init(MemoryRegionCache *cache,
 
     l = len;
     cache->fv = address_space_get_flatview(as);
-    d = flatview_to_dispatch(cache->fv);
-    cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
+    cache->mrs = *address_space_translate_internal(cache->fv, addr,
+                                                   &cache->xlat, &l, true);
 
     /*
      * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
Signature · 1 line
2.53.0
#10 lore raw

PATCH v2 3/6 memory: stop building dispatch trees before the machine runs

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

Regenerating a flatview spends most of its time building the radix tree used to translate addresses through it, not rendering the view. Nothing translates through a tree until a vCPU runs, and by then the topology has been rebuilt hundreds of times: once per device that claims a region while the machine is created, and once more per device that moves a BAR or a window while an incoming vmstate stream is read. Nearly all of those trees are discarded unbuilt upon.

Do not build them until a vCPU can run. A view rendered before that keeps a flat array of the sections the render already produced, and a lookup binary searches it. vm_prepare_start() builds a tree for every view still in use, which is the last point at which nothing has run yet.

The array answers the question the tree does except for one caller: a lookup which asks for the page a subpage container stands for, rather than the range covering the address, still needs the tree and builds it. That is the softmmu TLB fill and the iotlb entry lookup.

Building asserts the BQL, because two builders racing on one view would leak a tree. That holds every caller which can reach a view without one to running while the guest does, and by then no view an address space still publishes is missing its tree: a reader which picked one up during the window keeps it afterwards, and a view superseded meanwhile never gets a tree at all. Before a vCPU runs, the paths which translate without the BQL either do not run or ask for a range rather than a page.

A load which follows a run reopens the window, so a snapshot restore gets the same treatment as an incoming migration; vm_prepare_start() closes it again. Postcopy needs no exception, because it starts the guest through the same path.

A tree is now published once it is complete rather than while it is being filled, so a reader finds the tree or the array, never a half-built tree. io_mem_unassigned loses its static so the array can carry the same unassigned section the tree does.

CC Paolo Bonzini <[email protected]>
CC Peter Xu <[email protected]>
CC Philippe Mathieu-Daude <[email protected]>
CC Fabiano Rosas <[email protected]>
---
 include/system/memory.h  | 19 ++++++++
 migration/savevm.c       | 10 +++++
 system/memory-internal.h |  2 +
 system/memory.c          | 96 +++++++++++++++++++++++++++++++++++++++-
 system/physmem.c         | 41 +++++++++++++++--
 system/runstate.c        |  3 ++
 system/trace-events      |  1 +
 7 files changed, 167 insertions(+), 5 deletions(-)
include/system/memory.h +19 -0
index 027ca81bd2..d620bee90e 100644
@@ -940,6 +940,13 @@ struct FlatView {
     unsigned nr;
     unsigned nr_allocated;
     struct AddressSpaceDispatch *dispatch;
+    /*
+     * Stands in for @dispatch, one entry per range plus an unassigned entry
+     * at index 0. Built instead of the tree while dispatch building is
+     * deferred, and then kept for the life of the view, because a reader may
+     * still hold a pointer into it.
+     */
+    MemoryRegionSection *sections;
     MemoryRegion *root;
 };
 
@@ -2334,6 +2341,18 @@ void memory_region_transaction_begin(void);
  */
 void memory_region_transaction_commit(void);
 
+/**
+ * flatview_dispatch_defer_begin: Stop building dispatch trees
+ *
+ * For a window in which the topology is rebuilt repeatedly and translated
+ * through rarely, such as loading a migration stream. A view rendered in
+ * the window answers lookups from its range array instead, and gets its
+ * tree once the window closes. Must be closed with
+ * flatview_dispatch_defer_end() before the guest runs again.
+ */
+void flatview_dispatch_defer_begin(void);
+void flatview_dispatch_defer_end(void);
+
 /**
  * memory_listener_register: register callbacks to be called when memory
  *                           sections are mapped or unmapped into an address
migration/savevm.c +10 -0
index fe94ba96e4..ac48db7754 100644
@@ -3147,7 +3147,17 @@ int qemu_loadvm_state(QEMUFile *f, Error **errp)
 
     cpu_synchronize_all_pre_loadvm();
 
+    /*
+     * A load which follows a run, such as a snapshot, starts with the window
+     * already closed. Reopen it: the guest is stopped for the whole load, and
+     * vm_prepare_start() closes it again before anything runs.
+     */
+    flatview_dispatch_defer_begin();
+
     ret = qemu_loadvm_state_main(f, mis, errp);
+
+    flatview_dispatch_defer_end();
+
     qemu_event_set(&mis->main_thread_load_event);
 
     trace_qemu_loadvm_state_post_main(ret);
system/memory-internal.h +2 -0
index d81881ba54..3d9f92185d 100644
@@ -20,8 +20,10 @@ FlatView *address_space_get_flatview(const AddressSpace *as);
 void flatview_unref(FlatView *view);
 
 extern const MemoryRegionOps unassigned_mem_ops;
+extern MemoryRegion io_mem_unassigned;
 
 void flatview_build_dispatch(FlatView *fv);
+MemoryRegionSection *flatview_lookup_section(FlatView *fv, hwaddr addr);
 void flatview_add_to_dispatch(FlatView *fv, AddressSpaceDispatch *d,
                               MemoryRegionSection *section);
 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv);
system/memory.c +94 -2

130 lines not on this page · raw message

system/physmem.c +38 -3

65 lines not on this page · raw message

system/runstate.c +3 -0
index 56bfc5b07d..bae8ce9a96 100644
@@ -59,6 +59,7 @@
 #include "system/replay.h"
 #include "system/reset.h"
 #include "system/runstate.h"
+#include "system/memory.h"
 #include "system/runstate-action.h"
 #include "system/confidential-guest-support.h"
 #include "system/system.h"
@@ -508,6 +509,8 @@ int vm_prepare_start(bool step_pending)
         return -1;
     }
 
+    flatview_dispatch_defer_end();
+
     /*
      * WHPX accelerator needs to know whether we are going to step
      * any CPUs, before starting the first one.
system/trace-events +1 -0
index 38ad0be8a9..3542b6b2c4 100644
@@ -26,6 +26,7 @@ flatview_destroy(void *view, void *root) "%p (root %p)"
 flatview_destroy_rcu(void *view, void *root) "%p (root %p)"
 global_dirty_changed(unsigned int bitmask) "bitmask 0x%"PRIx32
 memory_region_finalize(const char* name) "mr %s"
+flatview_dispatch_drain(unsigned n_fv, unsigned n_ranges) "flatviews %u ranges %u"
 
 # physmem.c
 address_space_map(void *as, uint64_t addr, uint64_t len, bool is_write, uint32_t attrs) "as:%p addr 0x%"PRIx64":%"PRIx64" write:%d attrs:0x%x"
Signature · 1 line
2.53.0
#11 lore raw

PATCH v2 4/6 migration: add post_load_mr_update to batch region remaps on load

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

A post_load hook which maps or unmaps a memory region commits a memory transaction, and each commit regenerates the flatviews it touches at a cost which grows with the number of regions in the machine. A device which remaps per vCPU, as the Hyper-V SynIC does, pays that once per vCPU on the destination.

Add a post_load_mr_update callback, called after post_load, which only brings the device's memory regions in line with the state post_load restored. During a load the calls are queued and made in stream order inside one memory transaction, once the device state has been read and before the guest can start: at the end of qemu_loadvm_state() for precopy, snapshot and xen loads, and for postcopy in the POSTCOPY_RUN handler, before the bottom half which starts the guest is scheduled. The queue is run even when the load fails, as the calls would have been made inline.

The update is a callback of its own rather than a way to defer post_load, so that only the region work moves and the device state other sections read is restored where it always was. What may go in it is then checkable by reading it: nothing else in the load may depend on the regions it maps, and a lookup made during the batch resolves against the topology from before it. It cannot fail, so error reporting of the load is unchanged.

The batch spans the load rather than one device because a remap which repeats per vCPU sits in a per-vCPU section, and no smaller unit of the stream covers the repeats.

Only the thread which opened the batch queues. The postcopy listen thread, which reads the stream while the package is processed, makes any call it reaches at once.

CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Paolo Bonzini <[email protected]>
CC Zhao Liu <[email protected]>
---
 include/migration/vmstate.h |  30 ++++++++++
 migration/savevm.c          |  12 ++++
 migration/vmstate.c         |  50 +++++++++++++++++
 tests/unit/test-vmstate.c   | 109 ++++++++++++++++++++++++++++++++++++
 4 files changed, 201 insertions(+)
include/migration/vmstate.h +30 -0
index 2901877308..9f7ae1a224 100644
@@ -305,6 +305,19 @@ struct VMStateDescription {
     bool (*pre_load_errp)(void *opaque, Error **errp);
     int (*post_load)(void *opaque, int version_id);
     bool (*post_load_errp)(void *opaque, int version_id, Error **errp);
+
+    /*
+     * Maps, unmaps or moves the device's memory regions to match the state
+     * restored by .post_load() or .post_load_errp(), and does nothing else.
+     *
+     * Called after the post_load hook. During a load the calls are batched:
+     * they run once the device state has been read and before the guest can
+     * start, in stream order, inside one memory transaction, so the load
+     * rebuilds the topology once rather than once per call. Nothing else in
+     * the load may depend on the regions mapped here, and a lookup made
+     * during the batch resolves against the topology from before it.
+     */
+    void (*post_load_mr_update)(void *opaque);
     int (*pre_save)(void *opaque);
     bool (*pre_save_errp)(void *opaque, Error **errp);
 
@@ -1291,6 +1304,23 @@ bool vmstate_save_vmsd(QEMUFile *f, const VMStateDescription *vmsd,
 
 bool vmstate_section_needed(const VMStateDescription *vmsd, void *opaque);
 
+/**
+ * vmstate_mr_update_batch_begin: Batch post_load_mr_update calls
+ *
+ * Until vmstate_mr_update_batch_end(), a post_load_mr_update call reached
+ * from the calling thread is queued rather than made. Other threads still
+ * make it at once.
+ */
+void vmstate_mr_update_batch_begin(void);
+
+/**
+ * vmstate_mr_update_batch_end: Make the queued post_load_mr_update calls
+ *
+ * Makes them in the order they were queued. Does nothing if no batch is
+ * open.
+ */
+void vmstate_mr_update_batch_end(void);
+
 #define  VMSTATE_INSTANCE_ID_ANY  -1
 
 /* Returns: 0 on success, -1 on failure */
migration/savevm.c +12 -0
index ac48db7754..910199b868 100644
@@ -2226,6 +2226,13 @@ static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis,
     return rc;
 }
 
+static void loadvm_run_mr_updates(void)
+{
+    memory_region_transaction_begin();
+    vmstate_mr_update_batch_end();
+    memory_region_transaction_commit();
+}
+
 static void loadvm_postcopy_handle_run_bh(void *opaque)
 {
     MigrationIncomingState *mis = opaque;
@@ -2276,6 +2283,8 @@ static int loadvm_postcopy_handle_run(MigrationIncomingState *mis, Error **errp)
         return -1;
     }
 
+    loadvm_run_mr_updates();
+
     /* We might be already in POSTCOPY_ACTIVE if there is no return path */
     if (mis->state == MIGRATION_STATUS_POSTCOPY_DEVICE) {
         migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_DEVICE,
@@ -3153,9 +3162,12 @@ int qemu_loadvm_state(QEMUFile *f, Error **errp)
      * vm_prepare_start() closes it again before anything runs.
      */
     flatview_dispatch_defer_begin();
+    vmstate_mr_update_batch_begin();
 
     ret = qemu_loadvm_state_main(f, mis, errp);
 
+    loadvm_run_mr_updates();
+
     flatview_dispatch_defer_end();
 
     qemu_event_set(&mis->main_thread_load_event);
migration/vmstate.c +50 -0

68 lines not on this page · raw message

tests/unit/test-vmstate.c +109 -0

127 lines not on this page · raw message

Signature · 1 line
2.53.0
#12 lore raw

v2 cover migration: cut destination-side downtime on a big guest

In reply to Denis V. Lunev

v1 deferred the Hyper-V SynIC post_load so that it stopped forcing a flatview rebuild per vCPU. Measuring it showed the rebuild itself was the larger target: most of it is building the dispatch tree, which nothing translates through until a vCPU runs. Patches 1 to 3 stop building trees until the machine is about to run, for machine creation and an incoming stream alike. Patches 4 to 6 are v1 reworked after Peter's review: a device gets a separate post_load_mr_update callback which only maps or unmaps its regions, and a load batches those calls into one memory transaction after the device state has been read and before the guest can start.

The split is a correctness fix, not only an API change. v1 deferred the whole SynIC post_load, including the control bit VMBus reads in its own post_load to decide whether a SINT route gets a GSI. With a vmbus-bridge the destination would create the route without one, and the guest would get no further VMBus interrupts. Patch 5 separates state from mapping, patch 6 batches only the mapping.

The batch spans the whole load rather than one device, the alternative Chuang's series and the ToDo item point towards: a remap which repeats per vCPU sits in a per-vCPU section, so per-device batching would still rebuild once per vCPU. Unlike that series, the stream is not loaded inside the transaction: only callbacks which by contract resolve nothing share it, so no loader sees a stale view.

Measured on a 24-core EPYC 7443P restoring a captured stream of a Windows Server 2022 guest, median of three interleaved rounds. The metric is the sum of vmstate_downtime_load over the non-iterable sections plus everything deferred past the last section, so work moved to the end is not mistaken for work removed:

64 vCPU, 65 ports 4 vCPU, 16 ports
upstream 175 ms 25 ms
after patch 3 50 ms 10 ms
after patch 6 29 ms 9 ms

Patch 3 helps every guest; its saving tracks device count. Patch 6 scales with vCPUs: 21 ms on the large guest, 1 ms on the small one. Both guests map only the SynIC message page; one which also maps the event page saves about twice as much.

Patches 1 to 3 rest on no vCPU having run, so only the thread creating the machine or loading the stream, under the BQL, can reach a view without a tree; building one asserts the BQL. Postcopy starts the guest through vm_prepare_start() like any other start.

Tested on x86_64 with make check-unit, check-qtest-x86_64 and migration-test --full under KVM and forced onto TCG, where the subpage path runs; both include the postcopy cases. A guest which programs the SynIC from its boot sector comes back from save and restore with both pages mapped where they were.

v1: https://lore.kernel.org/qemu-devel/[email protected]/
Chuang Xu: https://lore.kernel.org/r/[email protected]
ToDo: https://wiki.qemu.org/ToDo/LiveMigration#Optimize_memory_updates_for_non-iterative_vmstates

Changes in v2:
- added patches 1 to 3, the dispatch-tree work; the batch runs inside the window patch 3 opens
- post_load_deferrable replaced by post_load_mr_update, a callback for region updates only (Peter)
- SynIC post_load split, patch 5, so VMBus still sees the SynIC state
- postcopy covered: the batch is made in the POSTCOPY_RUN handler before the bottom half which starts the guest is scheduled (Peter); the listen thread is not batched
- snapshot and xen loads batched the same way, COLO checkpoints not (Peter)
- the callback cannot fail; the abort on a failing hook is gone (Peter)
- documentation says the batch is one transaction and a lookup during it sees the old topology (Peter)
- APIC example dropped; the new callback cannot carry cross-thread work

CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Paolo Bonzini <[email protected]>
CC Philippe Mathieu-Daude <[email protected]>
CC Zhao Liu <[email protected]>
CC Marcelo Tosatti <[email protected]>
CC Maciej S. Szmigiero <[email protected]>

Denis V. Lunev (6):
memory: publish a dispatch tree only once it is complete
physmem: pass the FlatView to address_space_translate_internal
memory: stop building dispatch trees before the machine runs
migration: add post_load_mr_update to batch region remaps on load hw/hyperv: split the SynIC page mapping from its state update target/i386: batch the Hyper-V SynIC page remaps on load

 hw/hyperv/hyperv.c            |  70 ++++++++++++++------
 include/hw/hyperv/hyperv.h    |   3 +
 include/migration/vmstate.h   |  30 +++++++++
 include/system/memory.h       |  19 ++++++
 migration/savevm.c            |  22 +++++++
 migration/vmstate.c           |  50 ++++++++++++++
 system/memory-internal.h      |  17 ++---
 system/memory.c               | 119 +++++++++++++++++++++++++++++++---
 system/physmem.c              |  78 +++++++++++++++-------
 system/runstate.c             |   3 +
 system/trace-events           |   1 +
 target/i386/kvm/hyperv-stub.c |   8 +++
 target/i386/kvm/hyperv.c      |  16 ++++-
 target/i386/kvm/hyperv.h      |   2 +
 target/i386/machine.c         |   8 ++-
 tests/unit/test-vmstate.c     | 109 +++++++++++++++++++++++++++++++
 16 files changed, 489 insertions(+), 66 deletions(-)
Signature · 1 line
2.53.0
#13 lore raw

PATCH v2 5/6 hw/hyperv: split the SynIC page mapping from its state update

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

synic_update() records the SynIC control bit and page addresses and maps the message and event pages at those addresses in one go. Loading the SynIC wants the two apart: VMBus creates its SINT routes from the control bit in its own post_load, so the state must be restored with the CPU section, while the mapping can wait.

Add hyperv_synic_update_state() and hyperv_synic_update_mr(), with x86 wrappers. hyperv_synic_update() keeps doing both. The mapping now compares where the page is mapped with the recorded address, rather than the old recorded address with the new one, which is the same thing while both are updated together.

No functional change.

CC Paolo Bonzini <[email protected]>
CC Marcelo Tosatti <[email protected]>
CC Maciej S. Szmigiero <[email protected]>
CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Zhao Liu <[email protected]>
---
 hw/hyperv/hyperv.c            | 70 ++++++++++++++++++++++++-----------
 include/hw/hyperv/hyperv.h    |  3 ++
 target/i386/kvm/hyperv-stub.c |  8 ++++
 target/i386/kvm/hyperv.c      | 16 +++++++-
 target/i386/kvm/hyperv.h      |  2 +
 5 files changed, 76 insertions(+), 23 deletions(-)
hw/hyperv/hyperv.c +49 -21
index 900ff80213..307e7a40ad 100644
@@ -65,33 +65,61 @@ bool hyperv_is_synic_present(CPUState *cs)
     return get_synic(cs);
 }
 
+static void synic_map_page(MemoryRegion *mr, hwaddr addr)
+{
+    if (memory_region_is_mapped(mr)) {
+        if (mr->addr == addr) {
+            return;
+        }
+        memory_region_del_subregion(get_system_memory(), mr);
+    }
+    if (addr) {
+        memory_region_add_subregion(get_system_memory(), addr, mr);
+    }
+}
+
+static void synic_update_mr(SynICState *synic)
+{
+    synic_map_page(&synic->msg_page_mr, synic->msg_page_addr);
+    synic_map_page(&synic->event_page_mr, synic->event_page_addr);
+}
+
+static void synic_set_state(SynICState *synic, bool sctl_enable,
+                            hwaddr msg_page_addr, hwaddr event_page_addr)
+{
+    synic->sctl_enabled = sctl_enable;
+    synic->msg_page_addr = msg_page_addr;
+    synic->event_page_addr = event_page_addr;
+}
+
 static void synic_update(SynICState *synic, bool sctl_enable,
                          hwaddr msg_page_addr, hwaddr event_page_addr)
 {
+    synic_set_state(synic, sctl_enable, msg_page_addr, event_page_addr);
+    synic_update_mr(synic);
+}
 
-    synic->sctl_enabled = sctl_enable;
-    if (synic->msg_page_addr != msg_page_addr) {
-        if (synic->msg_page_addr) {
-            memory_region_del_subregion(get_system_memory(),
-                                        &synic->msg_page_mr);
-        }
-        if (msg_page_addr) {
-            memory_region_add_subregion(get_system_memory(), msg_page_addr,
-                                        &synic->msg_page_mr);
-        }
-        synic->msg_page_addr = msg_page_addr;
+void hyperv_synic_update_state(CPUState *cs, bool sctl_enable,
+                               hwaddr msg_page_addr, hwaddr event_page_addr)
+{
+    SynICState *synic = get_synic(cs);
+
+    if (!synic) {
+        return;
     }
-    if (synic->event_page_addr != event_page_addr) {
-        if (synic->event_page_addr) {
-            memory_region_del_subregion(get_system_memory(),
-                                        &synic->event_page_mr);
-        }
-        if (event_page_addr) {
-            memory_region_add_subregion(get_system_memory(), event_page_addr,
-                                        &synic->event_page_mr);
-        }
-        synic->event_page_addr = event_page_addr;
+
+    synic_set_state(synic, sctl_enable, msg_page_addr, event_page_addr);
+}
+
+void hyperv_synic_update_mr(CPUState *cs)
+{
+    SynICState *synic = get_synic(cs);
+
+    if (!synic) {
+        return;
     }
+
+    synic_update_mr(synic);
 }
 
 void hyperv_synic_update(CPUState *cs, bool sctl_enable,
include/hw/hyperv/hyperv.h +3 -0
index 23091301d0..fcad9efb5b 100644
@@ -80,6 +80,9 @@ void hyperv_synic_add(CPUState *cs);
 void hyperv_synic_reset(CPUState *cs);
 void hyperv_synic_update(CPUState *cs, bool enable,
                          hwaddr msg_page_addr, hwaddr event_page_addr);
+void hyperv_synic_update_state(CPUState *cs, bool enable,
+                               hwaddr msg_page_addr, hwaddr event_page_addr);
+void hyperv_synic_update_mr(CPUState *cs);
 bool hyperv_is_synic_enabled(void);
 bool hyperv_is_synic_present(CPUState *cs);
 
target/i386/kvm/hyperv-stub.c +8 -0
index 767a4c7e1a..c4d18f2cf5 100644
@@ -53,6 +53,14 @@ void hyperv_x86_synic_update(X86CPU *cpu)
 {
 }
 
+void hyperv_x86_synic_update_state(X86CPU *cpu)
+{
+}
+
+void hyperv_x86_synic_update_mr(X86CPU *cpu)
+{
+}
+
 void hyperv_x86_set_vmbus_recommended_features_enabled(void)
 {
 }
target/i386/kvm/hyperv.c +14 -2
index 420c76b5ff..08001b26c5 100644
@@ -42,7 +42,7 @@ void hyperv_x86_synic_reset(X86CPU *cpu)
     hyperv_synic_reset(CPU(cpu));
 }
 
-void hyperv_x86_synic_update(X86CPU *cpu)
+void hyperv_x86_synic_update_state(X86CPU *cpu)
 {
     CPUX86State *env = &cpu->env;
     bool enable = env->msr_hv_synic_control & HV_SYNIC_ENABLE;
@@ -50,7 +50,19 @@ void hyperv_x86_synic_update(X86CPU *cpu)
         (env->msr_hv_synic_msg_page & TARGET_PAGE_MASK) : 0;
     hwaddr event_page_addr = (env->msr_hv_synic_evt_page & HV_SIEFP_ENABLE) ?
         (env->msr_hv_synic_evt_page & TARGET_PAGE_MASK) : 0;
-    hyperv_synic_update(CPU(cpu), enable, msg_page_addr, event_page_addr);
+    hyperv_synic_update_state(CPU(cpu), enable, msg_page_addr,
+                              event_page_addr);
+}
+
+void hyperv_x86_synic_update_mr(X86CPU *cpu)
+{
+    hyperv_synic_update_mr(CPU(cpu));
+}
+
+void hyperv_x86_synic_update(X86CPU *cpu)
+{
+    hyperv_x86_synic_update_state(cpu);
+    hyperv_x86_synic_update_mr(cpu);
 }
 
 static void async_synic_update(CPUState *cs, run_on_cpu_data data)
target/i386/kvm/hyperv.h +2 -0
index a393a5d428..a0aee0cff3 100644
@@ -26,6 +26,8 @@ int hyperv_x86_synic_add(X86CPU *cpu);
 int hyperv_enable_synic(X86CPU *cpu);
 void hyperv_x86_synic_reset(X86CPU *cpu);
 void hyperv_x86_synic_update(X86CPU *cpu);
+void hyperv_x86_synic_update_state(X86CPU *cpu);
+void hyperv_x86_synic_update_mr(X86CPU *cpu);
 
 void hyperv_x86_set_vmbus_recommended_features_enabled(void);
 
Signature · 1 line
2.53.0
#14 lore raw

PATCH v2 6/6 target/i386: batch the Hyper-V SynIC page remaps on load

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

Restoring a guest which has programmed the SynIC maps its message and event pages once per vCPU, and each map rebuilds the flatview, so the cpu sections cost vCPU count times the number of regions in the machine.

Keep restoring the control bit and page addresses in post_load, and move only the mapping to post_load_mr_update. VMBus still finds the control bit set when its post_load creates SINT routes, and nothing in the load reaches the pages through the address space. The saving scales with vCPU count.

CC Peter Xu <[email protected]>
CC Fabiano Rosas <[email protected]>
CC Paolo Bonzini <[email protected]>
CC Marcelo Tosatti <[email protected]>
CC Maciej S. Szmigiero <[email protected]>
CC Zhao Liu <[email protected]>
---
 target/i386/machine.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
target/i386/machine.c +7 -1
index b5c6b127c9..ebfba102f8 100644
@@ -863,16 +863,22 @@ static bool hyperv_synic_enable_needed(void *opaque)
 static int hyperv_synic_post_load(void *opaque, int version_id)
 {
     X86CPU *cpu = opaque;
-    hyperv_x86_synic_update(cpu);
+    hyperv_x86_synic_update_state(cpu);
     return 0;
 }
 
+static void hyperv_synic_post_load_mr_update(void *opaque)
+{
+    hyperv_x86_synic_update_mr(opaque);
+}
+
 static const VMStateDescription vmstate_msr_hyperv_synic = {
     .name = "cpu/msr_hyperv_synic",
     .version_id = 1,
     .minimum_version_id = 1,
     .needed = hyperv_synic_enable_needed,
     .post_load = hyperv_synic_post_load,
+    .post_load_mr_update = hyperv_synic_post_load_mr_update,
     .fields = (const VMStateField[]) {
         VMSTATE_UINT64(env.msr_hv_synic_control, X86CPU),
         VMSTATE_UINT64(env.msr_hv_synic_evt_page, X86CPU),
Signature · 1 line
2.53.0