Skip to contentSkip to conversation

Multifd 🔀 device state transfer support with VFIO consumer

PATCH Superseded Maciej S. Szmigiero 6 participants 128 messages Aug 27, 2024 – Oct 15, 2024 Page 1 of 2

Subsystems (3)

v2 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v2 cover Multifd 🔀 device state transfer support with VFIO consumer

From: "Maciej S. Szmigiero" <[email protected]>

This is an updated v2 patch series of the v1 series located here:
https://lore.kernel.org/qemu-devel/[email protected]/

Changes from v1:
* Extended the QEMU thread-pool with non-AIO (generic) pool support, implemented automatic memory management support for its work element function argument.

* Introduced a multifd device state save thread pool, ported the VFIO multifd device state save implementation to use this thread pool instead of VFIO internally managed individual threads.

* Re-implemented on top of Fabiano's v4 multifd sender refactor patch set from
https://lore.kernel.org/qemu-devel/[email protected]/

* Moved device state related multifd code to new multifd-device-state.c file where it made sense.

* Implemented a max in-flight VFIO device state buffer count limit to allow capping the maximum recipient memory usage.

* Removed unnecessary explicit memory barriers from multifd_send().

* A few small changes like updated comments, code formatting, fixed zero-copy RAM multifd bytes transferred counter under-counting, etc.

For convenience, this patch set is also available as a git tree:
https://github.com/maciejsszmigiero/qemu/tree/multifd-device-state-transfer-vfio

Based-on: <[email protected]>

Maciej S. Szmigiero (17):
vfio/migration: Add save_{iterate,complete_precopy}_started trace
events
migration/ram: Add load start trace event migration/multifd: Zero p->flags before starting filling a packet
thread-pool: Add a DestroyNotify parameter to

    thread_pool_submit{,_aio)()

thread-pool: Implement non-AIO (generic) pool support
migration: Add save_live_complete_precopy_{begin,end} handlers
migration: Add qemu_loadvm_load_state_buffer() and its handler
migration: Add load_finish handler and associated functions migration/multifd: Device state transfer support - receive side migration/multifd: Convert multifd_send()::next_channel to atomic migration/multifd: Add an explicit MultiFDSendData destructor migration/multifd: Device state transfer support - send side migration/multifd: Add migration_has_device_state_support()
migration: Add save_live_complete_precopy_thread handler vfio/migration: Multifd device state transfer support - receive side vfio/migration: Add x-migration-multifd-transfer VFIO property vfio/migration: Multifd device state transfer support - send side

 backends/tpm/tpm_backend.c       |   2 +-
 block/file-win32.c               |   2 +-
 hw/9pfs/coth.c                   |   3 +-
 hw/ppc/spapr_nvdimm.c            |   4 +-
 hw/vfio/migration.c              | 520 ++++++++++++++++++++++++++++++-
 hw/vfio/pci.c                    |   9 +
 hw/vfio/trace-events             |  14 +-
 hw/virtio/virtio-pmem.c          |   2 +-
 include/block/thread-pool.h      |  12 +-
 include/hw/vfio/vfio-common.h    |  22 ++
 include/migration/misc.h         |  15 +
 include/migration/register.h     |  97 ++++++
 include/qemu/typedefs.h          |   4 +
 migration/meson.build            |   1 +
 migration/migration.c            |   6 +
 migration/migration.h            |   3 +
 migration/multifd-device-state.c | 193 ++++++++++++
 migration/multifd-nocomp.c       |   9 +-
 migration/multifd-qpl.c          |   2 +-
 migration/multifd-uadk.c         |   2 +-
 migration/multifd-zlib.c         |   2 +-
 migration/multifd-zstd.c         |   2 +-
 migration/multifd.c              | 249 ++++++++++++---
 migration/multifd.h              |  65 +++-
 migration/ram.c                  |   1 +
 migration/savevm.c               | 152 ++++++++-
 migration/savevm.h               |   7 +
 migration/trace-events           |   1 +
 tests/unit/test-thread-pool.c    |   8 +-
 util/thread-pool.c               |  83 ++++-
 30 files changed, 1406 insertions(+), 86 deletions(-)
 create mode 100644 migration/multifd-device-state.c
#1 lore raw

PATCH v2 1/17 vfio/migration: Add save_{iterate, complete_precopy}_started trace events

From: "Maciej S. Szmigiero" <[email protected]>

This way both the start and end points of migrating a particular VFIO device are known.

Add also a vfio_save_iterate_empty_hit trace event so it is known when there's no more data to send for that device.

---
 hw/vfio/migration.c           | 13 +++++++++++++
 hw/vfio/trace-events          |  3 +++
 include/hw/vfio/vfio-common.h |  3 +++
 3 files changed, 19 insertions(+)
hw/vfio/migration.c +13 -0
index 262d42a46e58..24679d8c5034 100644
@@ -472,6 +472,9 @@ static int vfio_save_setup(QEMUFile *f, void *opaque, Error **errp)
         return -ENOMEM;
     }
 
+    migration->save_iterate_run = false;
+    migration->save_iterate_empty_hit = false;
+
     if (vfio_precopy_supported(vbasedev)) {
         switch (migration->device_state) {
         case VFIO_DEVICE_STATE_RUNNING:
@@ -605,9 +608,17 @@ static int vfio_save_iterate(QEMUFile *f, void *opaque)
     VFIOMigration *migration = vbasedev->migration;
     ssize_t data_size;
 
+    if (!migration->save_iterate_run) {
+        trace_vfio_save_iterate_started(vbasedev->name);
+        migration->save_iterate_run = true;
+    }
+
     data_size = vfio_save_block(f, migration);
     if (data_size < 0) {
         return data_size;
+    } else if (data_size == 0 && !migration->save_iterate_empty_hit) {
+        trace_vfio_save_iterate_empty_hit(vbasedev->name);
+        migration->save_iterate_empty_hit = true;
     }
 
     vfio_update_estimated_pending_data(migration, data_size);
@@ -633,6 +644,8 @@ static int vfio_save_complete_precopy(QEMUFile *f, void *opaque)
     int ret;
     Error *local_err = NULL;
 
+    trace_vfio_save_complete_precopy_started(vbasedev->name);
+
     /* We reach here with device state STOP or STOP_COPY only */
     ret = vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_STOP_COPY,
                                    VFIO_DEVICE_STATE_STOP, &local_err);
hw/vfio/trace-events +3 -0
index 98bd4dcceadc..013c602f30fa 100644
@@ -159,8 +159,11 @@ vfio_migration_state_notifier(const char *name, int state) " (%s) state %d"
 vfio_save_block(const char *name, int data_size) " (%s) data_size %d"
 vfio_save_cleanup(const char *name) " (%s)"
 vfio_save_complete_precopy(const char *name, int ret) " (%s) ret %d"
+vfio_save_complete_precopy_started(const char *name) " (%s)"
 vfio_save_device_config_state(const char *name) " (%s)"
 vfio_save_iterate(const char *name, uint64_t precopy_init_size, uint64_t precopy_dirty_size) " (%s) precopy initial size 0x%"PRIx64" precopy dirty size 0x%"PRIx64
+vfio_save_iterate_started(const char *name) " (%s)"
+vfio_save_iterate_empty_hit(const char *name) " (%s)"
 vfio_save_setup(const char *name, uint64_t data_buffer_size) " (%s) data buffer size 0x%"PRIx64
 vfio_state_pending_estimate(const char *name, uint64_t precopy, uint64_t postcopy, uint64_t precopy_init_size, uint64_t precopy_dirty_size) " (%s) precopy 0x%"PRIx64" postcopy 0x%"PRIx64" precopy initial size 0x%"PRIx64" precopy dirty size 0x%"PRIx64
 vfio_state_pending_exact(const char *name, uint64_t precopy, uint64_t postcopy, uint64_t stopcopy_size, uint64_t precopy_init_size, uint64_t precopy_dirty_size) " (%s) precopy 0x%"PRIx64" postcopy 0x%"PRIx64" stopcopy size 0x%"PRIx64" precopy initial size 0x%"PRIx64" precopy dirty size 0x%"PRIx64
include/hw/vfio/vfio-common.h +3 -0
index fed499b199f0..32d58e3e025b 100644
@@ -73,6 +73,9 @@ typedef struct VFIOMigration {
     uint64_t precopy_init_size;
     uint64_t precopy_dirty_size;
     bool initial_data_sent;
+
+    bool save_iterate_run;
+    bool save_iterate_empty_hit;
 } VFIOMigration;
 
 struct VFIOGroup;
#2 lore raw

Re: [PATCH v2 01/17] vfio/migration: Add save_{iterate,complete_precopy}_started trace events

Hi Maciej,

Quoted 10 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

This way both the start and end points of migrating a particular VFIO device are known.

Add also a vfio_save_iterate_empty_hit trace event so it is known when there's no more data to send for that device.

Out of curiosity, what are these traces used for?

Quoted 23 lines
---
  hw/vfio/migration.c           | 13 +++++++++++++
  hw/vfio/trace-events          |  3 +++
  include/hw/vfio/vfio-common.h |  3 +++
  3 files changed, 19 insertions(+)
hw/vfio/migration.c +3 -0
index 262d42a46e58..24679d8c5034 100644
@@ -472,6 +472,9 @@ static int vfio_save_setup(QEMUFile *f, void *opaque, Error **errp)
          return -ENOMEM;
      }
 
+    migration->save_iterate_run = false;
+    migration->save_iterate_empty_hit = false;
+
      if (vfio_precopy_supported(vbasedev)) {
          switch (migration->device_state) {
          case VFIO_DEVICE_STATE_RUNNING:

hw/vfio/migration.c static int vfio_save_iterate(QEMUFile *f, void *opaque) · line 613

Quoted 6 lines
hw/vfio/migration.c +3 -0
@@ -605,9 +608,17 @@ static int vfio_save_iterate(QEMUFile *f, void *opaque)
      VFIOMigration *migration = vbasedev->migration;
      ssize_t data_size;
 
+    if (!migration->save_iterate_run) {
+        trace_vfio_save_iterate_started(vbasedev->name);
+        migration->save_iterate_run = true;

Maybe rename save_iterate_run to save_iterate_started so it's aligned with trace_vfio_save_iterate_started and trace_vfio_save_complete_precopy_started?

hw/vfio/migration.c static int vfio_save_iterate(QEMUFile *f, void *opaque) · line 621

Quoted 8 lines
hw/vfio/migration.c +5 -0
+    }
+
      data_size = vfio_save_block(f, migration);
      if (data_size < 0) {
          return data_size;
+    } else if (data_size == 0 && !migration->save_iterate_empty_hit) {
+        trace_vfio_save_iterate_empty_hit(vbasedev->name);
+        migration->save_iterate_empty_hit = true;

During precopy we could hit empty multiple times. Any reason why only the first time should be traced?

Quoted 17 lines
hw/vfio/migration.c +2 -0
      }
 
      vfio_update_estimated_pending_data(migration, data_size);
@@ -633,6 +644,8 @@ static int vfio_save_complete_precopy(QEMUFile *f, void *opaque)
      int ret;
      Error *local_err = NULL;
 
+    trace_vfio_save_complete_precopy_started(vbasedev->name);
+
      /* We reach here with device state STOP or STOP_COPY only */
      ret = vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_STOP_COPY,
                                     VFIO_DEVICE_STATE_STOP, &local_err);
hw/vfio/trace-events +0 -0
index 98bd4dcceadc..013c602f30fa 100644

hw/vfio/trace-events vfio_migration_state_notifier(const char *name, int state) " (%s) state %d" · line 166

Quoted 8 lines
hw/vfio/trace-events +3 -0
@@ -159,8 +159,11 @@ vfio_migration_state_notifier(const char *name, int state) " (%s) state %d"
  vfio_save_block(const char *name, int data_size) " (%s) data_size %d"
  vfio_save_cleanup(const char *name) " (%s)"
  vfio_save_complete_precopy(const char *name, int ret) " (%s) ret %d"
+vfio_save_complete_precopy_started(const char *name) " (%s)"
  vfio_save_device_config_state(const char *name) " (%s)"
  vfio_save_iterate(const char *name, uint64_t precopy_init_size, uint64_t precopy_dirty_size) " (%s) precopy initial size 0x%"PRIx64" precopy dirty size 0x%"PRIx64
+vfio_save_iterate_started(const char *name) " (%s)"
+vfio_save_iterate_empty_hit(const char *name) " (%s)"

Let's keep it sorted in alphabetical order.

Thanks.

Quoted 17 lines
hw/vfio/trace-events +0 -0
  vfio_save_setup(const char *name, uint64_t data_buffer_size) " (%s) data buffer size 0x%"PRIx64
  vfio_state_pending_estimate(const char *name, uint64_t precopy, uint64_t postcopy, uint64_t precopy_init_size, uint64_t precopy_dirty_size) " (%s) precopy 0x%"PRIx64" postcopy 0x%"PRIx64" precopy initial size 0x%"PRIx64" precopy dirty size 0x%"PRIx64
  vfio_state_pending_exact(const char *name, uint64_t precopy, uint64_t postcopy, uint64_t stopcopy_size, uint64_t precopy_init_size, uint64_t precopy_dirty_size) " (%s) precopy 0x%"PRIx64" postcopy 0x%"PRIx64" stopcopy size 0x%"PRIx64" precopy initial size 0x%"PRIx64" precopy dirty size 0x%"PRIx64
include/hw/vfio/vfio-common.h +3 -0
index fed499b199f0..32d58e3e025b 100644
@@ -73,6 +73,9 @@ typedef struct VFIOMigration {
      uint64_t precopy_init_size;
      uint64_t precopy_dirty_size;
      bool initial_data_sent;
+
+    bool save_iterate_run;
+    bool save_iterate_empty_hit;
  } VFIOMigration;
 
  struct VFIOGroup;
#3 lore raw

Re: [PATCH v2 01/17] vfio/migration: Add save_{iterate,complete_precopy}_started trace events

Quoted 8 lines · Avihai Horon

Hi Maciej,

Quoted 5 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

Quoted 7 lines
Quoted 5 lines

This way both the start and end points of migrating a particular VFIO device are known.

Add also a vfio_save_iterate_empty_hit trace event so it is known when there's no more data to send for that device.

Out of curiosity, what are these traces used for?

Just for benchmarking, collecting these data makes it easier to reason where possible bottlenecks may be.

Quoted 26 lines
Quoted 26 lines

---
  hw/vfio/migration.c           | 13 +++++++++++++ hw/vfio/trace-events          |  3 +++ include/hw/vfio/vfio-common.h |  3 +++

  3 files changed, 19 insertions(+)
hw/vfio/migration.c +3 -0
index 262d42a46e58..24679d8c5034 100644
@@ -472,6 +472,9 @@ static int vfio_save_setup(QEMUFile *f, void *opaque, Error **errp)
           return -ENOMEM;
       }
 
+    migration->save_iterate_run = false;
+    migration->save_iterate_empty_hit = false;
+
       if (vfio_precopy_supported(vbasedev)) {
           switch (migration->device_state) {

          case VFIO_DEVICE_STATE_RUNNING:

hw/vfio/migration.c +0 -0
@@ -605,9 +608,17 @@ static int vfio_save_iterate(QEMUFile *f, void *opaque)
       VFIOMigration *migration = vbasedev->migration;
       ssize_t data_size;
 
Quoted 5 lines

hw/vfio/migration.c static int vfio_save_iterate(QEMUFile *f, void *opaque) · line 613

Quoted 3 lines
hw/vfio/migration.c +3 -0
+    if (!migration->save_iterate_run) {
+        trace_vfio_save_iterate_started(vbasedev->name);
+        migration->save_iterate_run = true;

Maybe rename save_iterate_run to save_iterate_started so it's aligned with trace_vfio_save_iterate_started and trace_vfio_save_complete_precopy_started?

Will do.

Quoted 10 lines

hw/vfio/migration.c static int vfio_save_iterate(QEMUFile *f, void *opaque) · line 621

Quoted 8 lines
hw/vfio/migration.c +5 -0
+    }
+
       data_size = vfio_save_block(f, migration);
       if (data_size < 0) {
           return data_size;
+    } else if (data_size == 0 && !migration->save_iterate_empty_hit) {
+        trace_vfio_save_iterate_empty_hit(vbasedev->name);
+        migration->save_iterate_empty_hit = true;

During precopy we could hit empty multiple times. Any reason why only the first time should be traced?

This trace point is supposed to indicate whether the device state transfer during the time the VM was still running likely has exhausted the amount of data that can be transferred during that phase.

In other words, the stopped-time device state transfer likely only had to transfer the data which the device does not support transferring during the live VM phase (with just a small possible residual accrued since that trace point was hit).

If that trace point was hit then delaying the switch over point further likely wouldn't help the device transfer less data during the downtime.

Quoted 19 lines
Quoted 19 lines
hw/vfio/migration.c +2 -0
       }
 
       vfio_update_estimated_pending_data(migration, data_size);
@@ -633,6 +644,8 @@ static int vfio_save_complete_precopy(QEMUFile *f, void *opaque)
       int ret;
       Error *local_err = NULL;
 
+    trace_vfio_save_complete_precopy_started(vbasedev->name);
+
       /* We reach here with device state STOP or STOP_COPY only */
       ret = vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_STOP_COPY,
                                      VFIO_DEVICE_STATE_STOP, &local_err);
hw/vfio/trace-events +0 -0
index 98bd4dcceadc..013c602f30fa 100644
@@ -159,8 +159,11 @@ vfio_migration_state_notifier(const char *name, int state) " (%s) state %d"

  vfio_save_block(const char *name, int data_size) " (%s) data_size %d" vfio_save_cleanup(const char *name) " (%s)"

Quoted 8 lines

hw/vfio/trace-events vfio_migration_state_notifier(const char *name, int state) " (%s) state %d" · line 166

Quoted 6 lines

  vfio_save_complete_precopy(const char *name, int ret) " (%s) ret %d"
+vfio_save_complete_precopy_started(const char *name) " (%s)"
  vfio_save_device_config_state(const char *name) " (%s)"
  vfio_save_iterate(const char *name, uint64_t precopy_init_size, uint64_t precopy_dirty_size) " (%s) precopy initial size 0x%"PRIx64" precopy dirty size 0x%"PRIx64

hw/vfio/trace-events +2 -0
+vfio_save_iterate_started(const char *name) " (%s)"
+vfio_save_iterate_empty_hit(const char *name) " (%s)"

Let's keep it sorted in alphabetical order.

Ack.

Quoted 1 line

Thanks.

Thanks,
Maciej

#4 lore raw

Re: [PATCH v2 01/17] vfio/migration: Add save_{iterate,complete_precopy}_started trace events

Quoted 75 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

Quoted 8 lines · Avihai Horon

Hi Maciej,

Quoted 5 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

Quoted 7 lines
Quoted 5 lines

This way both the start and end points of migrating a particular VFIO device are known.

Add also a vfio_save_iterate_empty_hit trace event so it is known when there's no more data to send for that device.

Out of curiosity, what are these traces used for?

Just for benchmarking, collecting these data makes it easier to reason where possible bottlenecks may be.

Quoted 28 lines
Quoted 28 lines

---
  hw/vfio/migration.c           | 13 +++++++++++++ hw/vfio/trace-events          |  3 +++ include/hw/vfio/vfio-common.h |  3 +++

  3 files changed, 19 insertions(+)
hw/vfio/migration.c +3 -0
index 262d42a46e58..24679d8c5034 100644
@@ -472,6 +472,9 @@ static int vfio_save_setup(QEMUFile *f, void 
 *opaque, Error **errp)
           return -ENOMEM;
       }
 
+    migration->save_iterate_run = false;
+    migration->save_iterate_empty_hit = false;
+
       if (vfio_precopy_supported(vbasedev)) {
           switch (migration->device_state) {

          case VFIO_DEVICE_STATE_RUNNING:

hw/vfio/migration.c +0 -0
@@ -605,9 +608,17 @@ static int vfio_save_iterate(QEMUFile *f, void 
 *opaque)
       VFIOMigration *migration = vbasedev->migration;
       ssize_t data_size;
 
Quoted 5 lines

hw/vfio/migration.c static int vfio_save_iterate(QEMUFile *f, void *opaque) · line 613

Quoted 3 lines
hw/vfio/migration.c +3 -0
+    if (!migration->save_iterate_run) {
+        trace_vfio_save_iterate_started(vbasedev->name);
+        migration->save_iterate_run = true;

Maybe rename save_iterate_run to save_iterate_started so it's aligned with trace_vfio_save_iterate_started and trace_vfio_save_complete_precopy_started?

Will do.

Quoted 10 lines

hw/vfio/migration.c static int vfio_save_iterate(QEMUFile *f, void *opaque) · line 621

Quoted 8 lines
hw/vfio/migration.c +5 -0
+    }
+
       data_size = vfio_save_block(f, migration);
       if (data_size < 0) {
           return data_size;
+    } else if (data_size == 0 && !migration->save_iterate_empty_hit) {
+        trace_vfio_save_iterate_empty_hit(vbasedev->name);
+        migration->save_iterate_empty_hit = true;

During precopy we could hit empty multiple times. Any reason why only the first time should be traced?

This trace point is supposed to indicate whether the device state transfer during the time the VM was still running likely has exhausted the amount of data that can be transferred during that phase.

Quoted 8 lines

In other words, the stopped-time device state transfer likely only had to transfer the data which the device does not support transferring during the live VM phase (with just a small possible residual accrued since that trace point was hit).

If that trace point was hit then delaying the switch over point further likely wouldn't help the device transfer less data during the downtime.

Ah, I see.

Can we achieve the same goal by using trace_vfio_state_pending_exact() instead?

Thanks.

#5 lore raw

PATCH v2 2/17 migration/ram: Add load start trace event

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

There's a RAM load complete trace event but there wasn't its start equivalent.

---
 migration/ram.c        | 1 +
 migration/trace-events | 1 +
 2 files changed, 2 insertions(+)
migration/ram.c +1 -0
index 67ca3d5d51a1..7997bd830b9c 100644
@@ -4127,6 +4127,7 @@ static int ram_load_precopy(QEMUFile *f)
                           RAM_SAVE_FLAG_ZERO);
     }
 
+    trace_ram_load_start();
     while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
         ram_addr_t addr;
         void *host = NULL, *host_bak = NULL;
migration/trace-events +1 -0
index c65902f042bd..2a99a7baaea6 100644
@@ -115,6 +115,7 @@ colo_flush_ram_cache_end(void) ""
 save_xbzrle_page_skipping(void) ""
 save_xbzrle_page_overflow(void) ""
 ram_save_iterate_big_wait(uint64_t milliconds, int iterations) "big wait: %" PRIu64 " milliseconds, %d iterations"
+ram_load_start(void) ""
 ram_load_complete(int ret, uint64_t seq_iter) "exit_code %d seq iteration %" PRIu64
 ram_write_tracking_ramblock_start(const char *block_id, size_t page_size, void *addr, size_t length) "%s: page_size: %zu addr: %p length: %zu"
 ram_write_tracking_ramblock_stop(const char *block_id, size_t page_size, void *addr, size_t length) "%s: page_size: %zu addr: %p length: %zu"
#6 lore raw

Re: [PATCH v2 02/17] migration/ram: Add load start trace event

Quoted 15 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

There's a RAM load complete trace event but there wasn't its start equivalent.

---
 migration/ram.c        | 1 +
 migration/trace-events | 1 +
 2 files changed, 2 insertions(+)
migration/ram.c +0 -0
index 67ca3d5d51a1..7997bd830b9c 100644

migration/ram.c static int ram_load_precopy(QEMUFile *f) · line 4130

Quoted 4 lines
migration/ram.c +1 -0
@@ -4127,6 +4127,7 @@ static int ram_load_precopy(QEMUFile *f)
                           RAM_SAVE_FLAG_ZERO);
     }
 
+    trace_ram_load_start();

This would fit better at ram_load() paired with trace_ram_load_complete(), no?

Quoted 15 lines
migration/ram.c +0 -0
     while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
         ram_addr_t addr;
         void *host = NULL, *host_bak = NULL;
migration/trace-events +1 -0
index c65902f042bd..2a99a7baaea6 100644
@@ -115,6 +115,7 @@ colo_flush_ram_cache_end(void) ""
 save_xbzrle_page_skipping(void) ""
 save_xbzrle_page_overflow(void) ""
 ram_save_iterate_big_wait(uint64_t milliconds, int iterations) "big wait: %" PRIu64 " milliseconds, %d iterations"
+ram_load_start(void) ""
 ram_load_complete(int ret, uint64_t seq_iter) "exit_code %d seq iteration %" PRIu64
 ram_write_tracking_ramblock_start(const char *block_id, size_t page_size, void *addr, size_t length) "%s: page_size: %zu addr: %p length: %zu"
 ram_write_tracking_ramblock_stop(const char *block_id, size_t page_size, void *addr, size_t length) "%s: page_size: %zu addr: %p length: %zu"
#7 lore raw

Re: [PATCH v2 02/17] migration/ram: Add load start trace event

Quoted 20 lines · Fabiano Rosas
Quoted 18 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

There's a RAM load complete trace event but there wasn't its start equivalent.

---
  migration/ram.c        | 1 +
  migration/trace-events | 1 +
  2 files changed, 2 insertions(+)
migration/ram.c +0 -0
index 67ca3d5d51a1..7997bd830b9c 100644
@@ -4127,6 +4127,7 @@ static int ram_load_precopy(QEMUFile *f)
                            RAM_SAVE_FLAG_ZERO);
      }
 
Quoted 4 lines

migration/ram.c static int ram_load_precopy(QEMUFile *f) · line 4130

Quoted 1 line
migration/ram.c +1 -0
+    trace_ram_load_start();

This would fit better at ram_load() paired with trace_ram_load_complete(), no?

Right - will move it there in the next version of this patch set.

Thanks,
Maciej

#8 lore raw

PATCH v2 3/17 migration/multifd: Zero p->flags before starting filling a packet

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This way there aren't stale flags there.

p->flags can't contain SYNC to be sent at the next RAM packet since syncs are now handled separately in multifd_send_thread.

---
 migration/multifd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
migration/multifd.c +1 -1
index 0c07a2040ba8..b06a9fab500e 100644
@@ -601,6 +601,7 @@ static void *multifd_send_thread(void *opaque)
          * qatomic_store_release() in multifd_send().
          */
         if (qatomic_load_acquire(&p->pending_job)) {
+            p->flags = 0;
             p->iovs_num = 0;
             assert(!multifd_payload_empty(p->data));
 
@@ -652,7 +653,6 @@ static void *multifd_send_thread(void *opaque)
                 }
                 /* p->next_packet_size will always be zero for a SYNC packet */
                 stat64_add(&mig_stats.multifd_bytes, p->packet_len);
-                p->flags = 0;
             }
 
             qatomic_set(&p->pending_sync, false);
Reviewed-by on v2 3/17
#9 lore raw

Re: [PATCH v2 03/17] migration/multifd: Zero p->flags before starting filling a packet

Quoted 8 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This way there aren't stale flags there.

p->flags can't contain SYNC to be sent at the next RAM packet since syncs are now handled separately in multifd_send_thread.

Reviewed-by on v2 3/17
#10 lore raw

Re: [PATCH v2 03/17] migration/multifd: Zero p->flags before starting filling a packet

In reply to Maciej S. Szmigiero
Quoted 8 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This way there aren't stale flags there.

p->flags can't contain SYNC to be sent at the next RAM packet since syncs are now handled separately in multifd_send_thread.

Signature · 1 line
Peter Xu
#11 lore raw

PATCH v2 4/17 thread-pool: Add a DestroyNotify parameter to thread_pool_submit{, _aio)()

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Automatic memory management is less prone to mistakes or confusion who is responsible for freeing the memory backing the "arg" parameter or dropping a strong reference to object pointed by this parameter.

---
 backends/tpm/tpm_backend.c    |  2 +-
 block/file-win32.c            |  2 +-
 hw/9pfs/coth.c                |  3 ++-
 hw/ppc/spapr_nvdimm.c         |  4 ++--
 hw/virtio/virtio-pmem.c       |  2 +-
 include/block/thread-pool.h   |  6 ++++--
 tests/unit/test-thread-pool.c |  8 ++++----
 util/thread-pool.c            | 16 ++++++++++++----
 8 files changed, 27 insertions(+), 16 deletions(-)
backends/tpm/tpm_backend.c +1 -1
index 485a20b9e09f..65ef961b59ae 100644
@@ -107,7 +107,7 @@ void tpm_backend_deliver_request(TPMBackend *s, TPMBackendCmd *cmd)
 
     s->cmd = cmd;
     object_ref(OBJECT(s));
-    thread_pool_submit_aio(tpm_backend_worker_thread, s,
+    thread_pool_submit_aio(tpm_backend_worker_thread, s, NULL,
                            tpm_backend_request_completed, s);
 }
 
block/file-win32.c +1 -1
index 7e1baa1ece6a..9b99ae2f89e1 100644
@@ -167,7 +167,7 @@ static BlockAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
     acb->aio_offset = offset;
 
     trace_file_paio_submit(acb, opaque, offset, count, type);
-    return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
+    return thread_pool_submit_aio(aio_worker, acb, NULL, cb, opaque);
 }
 
 int qemu_ftruncate64(int fd, int64_t length)
hw/9pfs/coth.c +2 -1
index 598f46add993..fe5bfa6920fe 100644
@@ -41,5 +41,6 @@ static int coroutine_enter_func(void *arg)
 void co_run_in_worker_bh(void *opaque)
 {
     Coroutine *co = opaque;
-    thread_pool_submit_aio(coroutine_enter_func, co, coroutine_enter_cb, co);
+    thread_pool_submit_aio(coroutine_enter_func, co, NULL,
+                           coroutine_enter_cb, co);
 }
hw/ppc/spapr_nvdimm.c +2 -2
index 7d2dfe5e3d2f..f9ee45935d1d 100644
@@ -517,7 +517,7 @@ static int spapr_nvdimm_flush_post_load(void *opaque, int version_id)
     }
 
     QLIST_FOREACH(state, &s_nvdimm->pending_nvdimm_flush_states, node) {
-        thread_pool_submit_aio(flush_worker_cb, state,
+        thread_pool_submit_aio(flush_worker_cb, state, NULL,
                                spapr_nvdimm_flush_completion_cb, state);
     }
 
@@ -698,7 +698,7 @@ static target_ulong h_scm_flush(PowerPCCPU *cpu, SpaprMachineState *spapr,
 
         state->drcidx = drc_index;
 
-        thread_pool_submit_aio(flush_worker_cb, state,
+        thread_pool_submit_aio(flush_worker_cb, state, NULL,
                                spapr_nvdimm_flush_completion_cb, state);
 
         continue_token = state->continue_token;
hw/virtio/virtio-pmem.c +1 -1
index c3512c2dae3f..f1331c03f474 100644
@@ -87,7 +87,7 @@ static void virtio_pmem_flush(VirtIODevice *vdev, VirtQueue *vq)
     req_data->fd   = memory_region_get_fd(&backend->mr);
     req_data->pmem = pmem;
     req_data->vdev = vdev;
-    thread_pool_submit_aio(worker_cb, req_data, done_cb, req_data);
+    thread_pool_submit_aio(worker_cb, req_data, NULL, done_cb, req_data);
 }
 
 static void virtio_pmem_get_config(VirtIODevice *vdev, uint8_t *config)
include/block/thread-pool.h +4 -2
index 948ff5f30c31..b484c4780ea6 100644
@@ -33,10 +33,12 @@ void thread_pool_free(ThreadPool *pool);
  * thread_pool_submit* API: submit I/O requests in the thread's
  * current AioContext.
  */
-BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, void *arg,
+BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
+                                   void *arg, GDestroyNotify arg_destroy,
                                    BlockCompletionFunc *cb, void *opaque);
 int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg);
-void thread_pool_submit(ThreadPoolFunc *func, void *arg);
+void thread_pool_submit(ThreadPoolFunc *func,
+                        void *arg, GDestroyNotify arg_destroy);
 
 void thread_pool_update_params(ThreadPool *pool, struct AioContext *ctx);
 
tests/unit/test-thread-pool.c +4 -4
index 1483e53473db..e4afb9e36292 100644
@@ -46,7 +46,7 @@ static void done_cb(void *opaque, int ret)
 static void test_submit(void)
 {
     WorkerTestData data = { .n = 0 };
-    thread_pool_submit(worker_cb, &data);
+    thread_pool_submit(worker_cb, &data, NULL);
     while (data.n == 0) {
         aio_poll(ctx, true);
     }
@@ -56,7 +56,7 @@ static void test_submit(void)
 static void test_submit_aio(void)
 {
     WorkerTestData data = { .n = 0, .ret = -EINPROGRESS };
-    data.aiocb = thread_pool_submit_aio(worker_cb, &data,
+    data.aiocb = thread_pool_submit_aio(worker_cb, &data, NULL,
                                         done_cb, &data);
 
     /* The callbacks are not called until after the first wait.  */
@@ -121,7 +121,7 @@ static void test_submit_many(void)
     for (i = 0; i < 100; i++) {
         data[i].n = 0;
         data[i].ret = -EINPROGRESS;
-        thread_pool_submit_aio(worker_cb, &data[i], done_cb, &data[i]);
+        thread_pool_submit_aio(worker_cb, &data[i], NULL, done_cb, &data[i]);
     }
 
     active = 100;
@@ -149,7 +149,7 @@ static void do_test_cancel(bool sync)
     for (i = 0; i < 100; i++) {
         data[i].n = 0;
         data[i].ret = -EINPROGRESS;
-        data[i].aiocb = thread_pool_submit_aio(long_cb, &data[i],
+        data[i].aiocb = thread_pool_submit_aio(long_cb, &data[i], NULL,
                                                done_cb, &data[i]);
     }
 
util/thread-pool.c +12 -4
index 27eb777e855b..69a87ee79252 100644
@@ -38,6 +38,7 @@ struct ThreadPoolElement {
     ThreadPool *pool;
     ThreadPoolFunc *func;
     void *arg;
+    GDestroyNotify arg_destroy;
 
     /* Moving state out of THREAD_QUEUED is protected by lock.  After
      * that, only the worker thread can write to it.  Reads and writes
@@ -188,6 +189,10 @@ restart:
                                    elem->ret);
         QLIST_REMOVE(elem, all);
 
+        if (elem->arg_destroy) {
+            elem->arg_destroy(elem->arg);
+        }
+
         if (elem->common.cb) {
             /* Read state before ret.  */
             smp_rmb();
@@ -238,7 +243,8 @@ static const AIOCBInfo thread_pool_aiocb_info = {
     .cancel_async       = thread_pool_cancel,
 };
 
-BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, void *arg,
+BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
+                                   void *arg, GDestroyNotify arg_destroy,
                                    BlockCompletionFunc *cb, void *opaque)
 {
     ThreadPoolElement *req;
@@ -251,6 +257,7 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, void *arg,
     req = qemu_aio_get(&thread_pool_aiocb_info, NULL, cb, opaque);
     req->func = func;
     req->arg = arg;
+    req->arg_destroy = arg_destroy;
     req->state = THREAD_QUEUED;
     req->pool = pool;
 
@@ -285,14 +292,15 @@ int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg)
 {
     ThreadPoolCo tpc = { .co = qemu_coroutine_self(), .ret = -EINPROGRESS };
     assert(qemu_in_coroutine());
-    thread_pool_submit_aio(func, arg, thread_pool_co_cb, &tpc);
+    thread_pool_submit_aio(func, arg, NULL, thread_pool_co_cb, &tpc);
     qemu_coroutine_yield();
     return tpc.ret;
 }
 
-void thread_pool_submit(ThreadPoolFunc *func, void *arg)
+void thread_pool_submit(ThreadPoolFunc *func,
+                        void *arg, GDestroyNotify arg_destroy)
 {
-    thread_pool_submit_aio(func, arg, NULL, NULL);
+    thread_pool_submit_aio(func, arg, arg_destroy, NULL, NULL);
 }
 
 void thread_pool_update_params(ThreadPool *pool, AioContext *ctx)
#12 lore raw

PATCH v2 5/17 thread-pool: Implement non-AIO (generic) pool support

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

---
 include/block/thread-pool.h   | 10 ++++-
 tests/unit/test-thread-pool.c |  2 +-
 util/thread-pool.c            | 77 ++++++++++++++++++++++++++++++-----
 3 files changed, 76 insertions(+), 13 deletions(-)
include/block/thread-pool.h +8 -2
index b484c4780ea6..1769496056cd 100644
@@ -37,9 +37,15 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
                                    void *arg, GDestroyNotify arg_destroy,
                                    BlockCompletionFunc *cb, void *opaque);
 int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg);
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy);
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque);
 
+void thread_pool_join(ThreadPool *pool);
+void thread_pool_poll(ThreadPool *pool);
+
+void thread_pool_set_minmax_threads(ThreadPool *pool,
+                                    int min_threads, int max_threads);
 void thread_pool_update_params(ThreadPool *pool, struct AioContext *ctx);
 
 #endif
tests/unit/test-thread-pool.c +1 -1
index e4afb9e36292..469c0f7057b6 100644
@@ -46,7 +46,7 @@ static void done_cb(void *opaque, int ret)
 static void test_submit(void)
 {
     WorkerTestData data = { .n = 0 };
-    thread_pool_submit(worker_cb, &data, NULL);
+    thread_pool_submit(NULL, worker_cb, &data, NULL, NULL, NULL);
     while (data.n == 0) {
         aio_poll(ctx, true);
     }
util/thread-pool.c +67 -10

146 lines not on this page · raw message

#13 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 35 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

---
 include/block/thread-pool.h   | 10 ++++-
 tests/unit/test-thread-pool.c |  2 +-
 util/thread-pool.c            | 77 ++++++++++++++++++++++++++++++-----
 3 files changed, 76 insertions(+), 13 deletions(-)
include/block/thread-pool.h +0 -0
index b484c4780ea6..1769496056cd 100644

include/block/thread-pool.h BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, · line 42

Quoted 8 lines
include/block/thread-pool.h +3 -2
@@ -37,9 +37,15 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
                                    void *arg, GDestroyNotify arg_destroy,
                                    BlockCompletionFunc *cb, void *opaque);
 int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg);
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy);
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque);

These kinds of changes (create wrappers, change signatures, etc), could be in their own patch as it's just code motion that should not have functional impact. The "no_requests" stuff would be better discussed in a separate patch.

Quoted 35 lines
include/block/thread-pool.h +5 -0
+void thread_pool_join(ThreadPool *pool);
+void thread_pool_poll(ThreadPool *pool);
+
+void thread_pool_set_minmax_threads(ThreadPool *pool,
+                                    int min_threads, int max_threads);
 void thread_pool_update_params(ThreadPool *pool, struct AioContext *ctx);
 
 #endif
tests/unit/test-thread-pool.c +1 -1
index e4afb9e36292..469c0f7057b6 100644
@@ -46,7 +46,7 @@ static void done_cb(void *opaque, int ret)
 static void test_submit(void)
 {
     WorkerTestData data = { .n = 0 };
-    thread_pool_submit(worker_cb, &data, NULL);
+    thread_pool_submit(NULL, worker_cb, &data, NULL, NULL, NULL);
     while (data.n == 0) {
         aio_poll(ctx, true);
     }
util/thread-pool.c +1 -0
index 69a87ee79252..2bf3be875a51 100644
@@ -60,6 +60,7 @@ struct ThreadPool {
     QemuMutex lock;
     QemuCond worker_stopped;
     QemuCond request_cond;
+    QemuCond no_requests_cond;
     QEMUBH *new_thread_bh;
 
     /* The following variables are only accessed from one AioContext. */

util/thread-pool.c struct ThreadPool { · line 77

Quoted 4 lines
util/thread-pool.c +1 -0
@@ -73,6 +74,7 @@ struct ThreadPool {
     int pending_threads; /* threads created but not running yet */
     int min_threads;
     int max_threads;
+    size_t requests_executing;

What's with size_t? Should this be a uint32_t instead?

Quoted 16 lines
util/thread-pool.c +4 -0
 };
 
 static void *worker_thread(void *opaque)
@@ -107,6 +109,10 @@ static void *worker_thread(void *opaque)
         req = QTAILQ_FIRST(&pool->request_list);
         QTAILQ_REMOVE(&pool->request_list, req, reqs);
         req->state = THREAD_ACTIVE;
+
+        assert(pool->requests_executing < SIZE_MAX);
+        pool->requests_executing++;
+
         qemu_mutex_unlock(&pool->lock);
 
         ret = req->func(req->arg);
@@ -118,6 +124,14 @@ static void *worker_thread(void *opaque)
 

util/thread-pool.c static void *worker_thread(void *opaque) · line 134

Quoted 10 lines
util/thread-pool.c +8 -0
         qemu_bh_schedule(pool->completion_bh);
         qemu_mutex_lock(&pool->lock);
+
+        assert(pool->requests_executing > 0);
+        pool->requests_executing--;
+
+        if (pool->requests_executing == 0 &&
+            QTAILQ_EMPTY(&pool->request_list)) {
+            qemu_cond_signal(&pool->no_requests_cond);
+        }

An empty requests list and no request in flight means the worker will now exit after the timeout, no? Can you just kick the worker out of the wait and use pool->worker_stopped instead of the new condition variable?

Quoted 11 lines
util/thread-pool.c +1 -3
     }
 
     pool->cur_threads--;
@@ -243,13 +257,16 @@ static const AIOCBInfo thread_pool_aiocb_info = {
     .cancel_async       = thread_pool_cancel,
 };
 
-BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
-                                   void *arg, GDestroyNotify arg_destroy,
-                                   BlockCompletionFunc *cb, void *opaque)
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,

util/thread-pool.c static const AIOCBInfo thread_pool_aiocb_info = { · line 269

Quoted 10 lines
util/thread-pool.c +6 -1
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque)
 {
     ThreadPoolElement *req;
     AioContext *ctx = qemu_get_current_aio_context();
-    ThreadPool *pool = aio_get_thread_pool(ctx);
+
+    if (!pool) {
+        pool = aio_get_thread_pool(ctx);
+    }

I'd go for a separate implementation to really drive the point that this new usage is different. See the code snippet below.

It seems we're a short step away to being able to use this implementation in a general way. Is there something that can be done with the 'common' field in the ThreadPoolElement?

========
static void thread_pool_submit_request(ThreadPool *pool, ThreadPoolElement *req)

{
    req->state = THREAD_QUEUED;
    req->pool = pool;

    QLIST_INSERT_HEAD(&pool->head, req, all);

    trace_thread_pool_submit(pool, req, req->arg);

    qemu_mutex_lock(&pool->lock);
    if (pool->idle_threads == 0 && pool->cur_threads < pool->max_threads) {
        spawn_thread(pool);
    }
    QTAILQ_INSERT_TAIL(&pool->request_list, req, reqs);
    qemu_mutex_unlock(&pool->lock);
    qemu_cond_signal(&pool->request_cond);
}

BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, void *arg,
BlockCompletionFunc *cb, void *opaque)

{
    ThreadPoolElement *req;
    AioContext *ctx = qemu_get_current_aio_context();
    ThreadPool *pool = aio_get_thread_pool(ctx);

    /* Assert that the thread submitting work is the same running the pool */
    assert(pool->ctx == qemu_get_current_aio_context());

    req = qemu_aio_get(&thread_pool_aiocb_info, NULL, cb, opaque);
    req->func = func;
    req->arg = arg;

    thread_pool_submit_request(pool, req);
    return &req->common;
}

void thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func, void *arg)

{
    ThreadPoolElement *req;

    req = g_malloc(sizeof(ThreadPoolElement));
    req->func = func;
    req->arg = arg;

    thread_pool_submit_request(pool, req);
}

=================

Quoted 23 lines
util/thread-pool.c +12 -0
     /* Assert that the thread submitting work is the same running the pool */
     assert(pool->ctx == qemu_get_current_aio_context());
@@ -275,6 +292,18 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
     return &req->common;
 }
 
+BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
+                                   void *arg, GDestroyNotify arg_destroy,
+                                   BlockCompletionFunc *cb, void *opaque)
+{
+    return thread_pool_submit(NULL, func, arg, arg_destroy, cb, opaque);
+}
+
+void thread_pool_poll(ThreadPool *pool)
+{
+    aio_bh_poll(pool->ctx);
+}
+
 typedef struct ThreadPoolCo {
     Coroutine *co;
     int ret;

util/thread-pool.c int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg) · line 329

Quoted 6 lines
util/thread-pool.c +1 -2
@@ -297,18 +326,38 @@ int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg)
     return tpc.ret;
 }
 
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy)
+void thread_pool_join(ThreadPool *pool)

This is misleading because it's about the requests, not the threads in the pool. Compare with what thread_pool_free does:

    /* Wait for worker threads to terminate */
    pool->max_threads = 0;
    qemu_cond_broadcast(&pool->request_cond);
    while (pool->cur_threads > 0) {
        qemu_cond_wait(&pool->worker_stopped, &pool->lock);
    }
Quoted 67 lines
util/thread-pool.c +33 -4
 {
-    thread_pool_submit_aio(func, arg, arg_destroy, NULL, NULL);
+    /* Assert that the thread waiting is the same running the pool */
+    assert(pool->ctx == qemu_get_current_aio_context());
+
+    qemu_mutex_lock(&pool->lock);
+
+    if (pool->requests_executing > 0 ||
+        !QTAILQ_EMPTY(&pool->request_list)) {
+        qemu_cond_wait(&pool->no_requests_cond, &pool->lock);
+    }
+    assert(pool->requests_executing == 0 &&
+           QTAILQ_EMPTY(&pool->request_list));
+
+    qemu_mutex_unlock(&pool->lock);
+
+    aio_bh_poll(pool->ctx);
+
+    assert(QLIST_EMPTY(&pool->head));
 }
 
-void thread_pool_update_params(ThreadPool *pool, AioContext *ctx)
+void thread_pool_set_minmax_threads(ThreadPool *pool,
+                                    int min_threads, int max_threads)
 {
+    assert(min_threads >= 0);
+    assert(max_threads > 0);
+    assert(max_threads >= min_threads);
+
     qemu_mutex_lock(&pool->lock);
 
-    pool->min_threads = ctx->thread_pool_min;
-    pool->max_threads = ctx->thread_pool_max;
+    pool->min_threads = min_threads;
+    pool->max_threads = max_threads;
 
     /*
      * We either have to:
@@ -330,6 +379,12 @@ void thread_pool_update_params(ThreadPool *pool, AioContext *ctx)
     qemu_mutex_unlock(&pool->lock);
 }
 
+void thread_pool_update_params(ThreadPool *pool, AioContext *ctx)
+{
+    thread_pool_set_minmax_threads(pool,
+                                   ctx->thread_pool_min, ctx->thread_pool_max);
+}
+
 static void thread_pool_init_one(ThreadPool *pool, AioContext *ctx)
 {
     if (!ctx) {
@@ -342,6 +397,7 @@ static void thread_pool_init_one(ThreadPool *pool, AioContext *ctx)
     qemu_mutex_init(&pool->lock);
     qemu_cond_init(&pool->worker_stopped);
     qemu_cond_init(&pool->request_cond);
+    qemu_cond_init(&pool->no_requests_cond);
     pool->new_thread_bh = aio_bh_new(ctx, spawn_thread_bh_fn, pool);
 
     QLIST_INIT(&pool->head);
@@ -382,6 +438,7 @@ void thread_pool_free(ThreadPool *pool)
     qemu_mutex_unlock(&pool->lock);
 
     qemu_bh_delete(pool->completion_bh);
+    qemu_cond_destroy(&pool->no_requests_cond);
     qemu_cond_destroy(&pool->request_cond);
     qemu_cond_destroy(&pool->worker_stopped);
     qemu_mutex_destroy(&pool->lock);
#14 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 42 lines · Fabiano Rosas
Quoted 40 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

---
  include/block/thread-pool.h   | 10 ++++-
  tests/unit/test-thread-pool.c |  2 +-
  util/thread-pool.c            | 77 ++++++++++++++++++++++++++++++-----
  3 files changed, 76 insertions(+), 13 deletions(-)
include/block/thread-pool.h +0 -2
index b484c4780ea6..1769496056cd 100644
@@ -37,9 +37,15 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
                                     void *arg, GDestroyNotify arg_destroy,
                                     BlockCompletionFunc *cb, void *opaque);
  int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg);
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy);
Quoted 8 lines

include/block/thread-pool.h BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, · line 42

Quoted 3 lines
include/block/thread-pool.h +3 -0
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque);

These kinds of changes (create wrappers, change signatures, etc), could be in their own patch as it's just code motion that should not have functional impact. The "no_requests" stuff would be better discussed in a separate patch.

These changes *all* should have no functional impact on existing callers.

But I get your overall point, will try to separate these really trivial parts.

Quoted 33 lines
Quoted 33 lines
include/block/thread-pool.h +5 -0
+void thread_pool_join(ThreadPool *pool);
+void thread_pool_poll(ThreadPool *pool);
+
+void thread_pool_set_minmax_threads(ThreadPool *pool,
+                                    int min_threads, int max_threads);
  void thread_pool_update_params(ThreadPool *pool, struct AioContext *ctx);
 
  #endif
tests/unit/test-thread-pool.c +1 -1
index e4afb9e36292..469c0f7057b6 100644
@@ -46,7 +46,7 @@ static void done_cb(void *opaque, int ret)
  static void test_submit(void)
  {
      WorkerTestData data = { .n = 0 };
-    thread_pool_submit(worker_cb, &data, NULL);
+    thread_pool_submit(NULL, worker_cb, &data, NULL, NULL, NULL);
      while (data.n == 0) {
          aio_poll(ctx, true);
      }
util/thread-pool.c +1 -0
index 69a87ee79252..2bf3be875a51 100644
@@ -60,6 +60,7 @@ struct ThreadPool {
      QemuMutex lock;
      QemuCond worker_stopped;
      QemuCond request_cond;
+    QemuCond no_requests_cond;
      QEMUBH *new_thread_bh;
 
Quoted 8 lines

util/thread-pool.c struct ThreadPool { · line 77

Quoted 6 lines
util/thread-pool.c +1 -0
      /* The following variables are only accessed from one AioContext. */
@@ -73,6 +74,7 @@ struct ThreadPool {
      int pending_threads; /* threads created but not running yet */
      int min_threads;
      int max_threads;
+    size_t requests_executing;

What's with size_t? Should this be a uint32_t instead?

Sizes of objects are normally size_t, since otherwise bad things happen if objects are bigger than 4 GiB.

Considering that the minimum object size is 1 byte the max count of distinct objects also needs a size_t to not risk an overflow.

I think that while 2^32 requests executing seems unlikely saving 4 bytes seems not worth worrying that someone will find a vulnerability triggered by overflowing a 32-bit variable (not necessary in the migration code but in some other thread pool user).

Quoted 16 lines
Quoted 16 lines
util/thread-pool.c +4 -0
  };
 
  static void *worker_thread(void *opaque)
@@ -107,6 +109,10 @@ static void *worker_thread(void *opaque)
          req = QTAILQ_FIRST(&pool->request_list);
          QTAILQ_REMOVE(&pool->request_list, req, reqs);
          req->state = THREAD_ACTIVE;
+
+        assert(pool->requests_executing < SIZE_MAX);
+        pool->requests_executing++;
+
          qemu_mutex_unlock(&pool->lock);
 
          ret = req->func(req->arg);
@@ -118,6 +124,14 @@ static void *worker_thread(void *opaque)
 
Quoted 14 lines

util/thread-pool.c static void *worker_thread(void *opaque) · line 134

Quoted 10 lines
util/thread-pool.c +8 -0
          qemu_bh_schedule(pool->completion_bh);
          qemu_mutex_lock(&pool->lock);
+
+        assert(pool->requests_executing > 0);
+        pool->requests_executing--;
+
+        if (pool->requests_executing == 0 &&
+            QTAILQ_EMPTY(&pool->request_list)) {
+            qemu_cond_signal(&pool->no_requests_cond);
+        }

An empty requests list and no request in flight means the worker will now exit after the timeout, no? Can you just kick the worker out of the wait and use pool->worker_stopped instead of the new condition variable?

First, all threads won't terminate if either min_threads or max_threads isn't 0.
It might be in the migration thread pool case but we are adding a generic thread pool so it should be as universal as possible. thread_pool_free() can get away with overwriting these values since it is destroying the pool anyway.

Also, the *_join() (or whatever its final name will be) operation is about waiting for all requests / work items to finish, not about waiting for threads to terminate.
It's essentially a synchronization point for a thread pool, not a cleanup.

Quoted 16 lines
Quoted 16 lines
util/thread-pool.c +3 -3
      }
 
      pool->cur_threads--;
@@ -243,13 +257,16 @@ static const AIOCBInfo thread_pool_aiocb_info = {
      .cancel_async       = thread_pool_cancel,
  };
 
-BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
-                                   void *arg, GDestroyNotify arg_destroy,
-                                   BlockCompletionFunc *cb, void *opaque)
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque)
  {
      ThreadPoolElement *req;
      AioContext *ctx = qemu_get_current_aio_context();
Quoted 8 lines

util/thread-pool.c static const AIOCBInfo thread_pool_aiocb_info = { · line 269

Quoted 5 lines
util/thread-pool.c +4 -1
-    ThreadPool *pool = aio_get_thread_pool(ctx);
+
+    if (!pool) {
+        pool = aio_get_thread_pool(ctx);
+    }

I'd go for a separate implementation to really drive the point that this new usage is different. See the code snippet below.

I see your point there - will split these implementations.

Quoted 3 lines

It seems we're a short step away to being able to use this implementation in a general way. Is there something that can be done with the 'common' field in the ThreadPoolElement?

The non-AIO request flow still need the completion callback from BlockAIOCB (and its argument pointer) so removing the "common" field from these requests would need introducing two "flavors" of ThreadPoolElement.

Not sure memory saving here are worth the increase in code complexity.

Quoted 82 lines

========
static void thread_pool_submit_request(ThreadPool *pool, ThreadPoolElement *req)

{
     req->state = THREAD_QUEUED;
     req->pool = pool;

     QLIST_INSERT_HEAD(&pool->head, req, all);

     trace_thread_pool_submit(pool, req, req->arg);

     qemu_mutex_lock(&pool->lock);
     if (pool->idle_threads == 0 && pool->cur_threads < pool->max_threads) {
         spawn_thread(pool);
     }
     QTAILQ_INSERT_TAIL(&pool->request_list, req, reqs);
     qemu_mutex_unlock(&pool->lock);
     qemu_cond_signal(&pool->request_cond);
}

BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, void *arg,
BlockCompletionFunc *cb, void *opaque)

{
     ThreadPoolElement *req;
     AioContext *ctx = qemu_get_current_aio_context();
     ThreadPool *pool = aio_get_thread_pool(ctx);

     /* Assert that the thread submitting work is the same running the pool */
     assert(pool->ctx == qemu_get_current_aio_context());

     req = qemu_aio_get(&thread_pool_aiocb_info, NULL, cb, opaque);
     req->func = func;
     req->arg = arg;

     thread_pool_submit_request(pool, req);
     return &req->common;
}

void thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func, void *arg)

{
     ThreadPoolElement *req;

     req = g_malloc(sizeof(ThreadPoolElement));
     req->func = func;
     req->arg = arg;

     thread_pool_submit_request(pool, req);
}

=================

Quoted 23 lines
util/thread-pool.c +12 -0
      /* Assert that the thread submitting work is the same running the pool */
      assert(pool->ctx == qemu_get_current_aio_context());
@@ -275,6 +292,18 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
      return &req->common;
  }
 
+BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
+                                   void *arg, GDestroyNotify arg_destroy,
+                                   BlockCompletionFunc *cb, void *opaque)
+{
+    return thread_pool_submit(NULL, func, arg, arg_destroy, cb, opaque);
+}
+
+void thread_pool_poll(ThreadPool *pool)
+{
+    aio_bh_poll(pool->ctx);
+}
+
  typedef struct ThreadPoolCo {
      Coroutine *co;
      int ret;

util/thread-pool.c int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg) · line 329

Quoted 6 lines
util/thread-pool.c +1 -2
@@ -297,18 +326,38 @@ int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg)
      return tpc.ret;
  }
 
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy)
+void thread_pool_join(ThreadPool *pool)

This is misleading because it's about the requests, not the threads in the pool. Compare with what thread_pool_free does:

Quoted 7 lines
     /* Wait for worker threads to terminate */
     pool->max_threads = 0;
     qemu_cond_broadcast(&pool->request_cond);
     while (pool->cur_threads > 0) {
         qemu_cond_wait(&pool->worker_stopped, &pool->lock);
     }

I'm open to thread_pool_join() better naming proposals.

Thanks,
Maciej

#15 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 52 lines · Maciej S. Szmigiero
Quoted 42 lines · Fabiano Rosas
Quoted 40 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

---
  include/block/thread-pool.h   | 10 ++++-
  tests/unit/test-thread-pool.c |  2 +-
  util/thread-pool.c            | 77 ++++++++++++++++++++++++++++++-----
  3 files changed, 76 insertions(+), 13 deletions(-)
include/block/thread-pool.h +0 -2
index b484c4780ea6..1769496056cd 100644
@@ -37,9 +37,15 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
                                     void *arg, GDestroyNotify arg_destroy,
                                     BlockCompletionFunc *cb, void *opaque);
  int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg);
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy);
Quoted 8 lines

include/block/thread-pool.h BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, · line 42

Quoted 3 lines
include/block/thread-pool.h +3 -0
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque);

These kinds of changes (create wrappers, change signatures, etc), could be in their own patch as it's just code motion that should not have functional impact. The "no_requests" stuff would be better discussed in a separate patch.

Quoted 4 lines

These changes *all* should have no functional impact on existing callers.

But I get your overall point, will try to separate these really trivial parts.

Yeah, I guess I meant that one set of changes has a larger potential for introducing a bug while the other is clearly harmless.

Quoted 43 lines
Quoted 34 lines
Quoted 34 lines
include/block/thread-pool.h +5 -0
+void thread_pool_join(ThreadPool *pool);
+void thread_pool_poll(ThreadPool *pool);
+
+void thread_pool_set_minmax_threads(ThreadPool *pool,
+                                    int min_threads, int max_threads);
  void thread_pool_update_params(ThreadPool *pool, struct AioContext *ctx);
 
  #endif
tests/unit/test-thread-pool.c +1 -1
index e4afb9e36292..469c0f7057b6 100644
@@ -46,7 +46,7 @@ static void done_cb(void *opaque, int ret)
  static void test_submit(void)
  {
      WorkerTestData data = { .n = 0 };
-    thread_pool_submit(worker_cb, &data, NULL);
+    thread_pool_submit(NULL, worker_cb, &data, NULL, NULL, NULL);
      while (data.n == 0) {
          aio_poll(ctx, true);
      }
util/thread-pool.c +1 -0
index 69a87ee79252..2bf3be875a51 100644
@@ -60,6 +60,7 @@ struct ThreadPool {
      QemuMutex lock;
      QemuCond worker_stopped;
      QemuCond request_cond;
+    QemuCond no_requests_cond;
      QEMUBH *new_thread_bh;
 
Quoted 8 lines

util/thread-pool.c struct ThreadPool { · line 77

Quoted 6 lines
util/thread-pool.c +1 -0
      /* The following variables are only accessed from one AioContext. */
@@ -73,6 +74,7 @@ struct ThreadPool {
      int pending_threads; /* threads created but not running yet */
      int min_threads;
      int max_threads;
+    size_t requests_executing;

What's with size_t? Should this be a uint32_t instead?

Quoted 2 lines

Sizes of objects are normally size_t, since otherwise bad things happen if objects are bigger than 4 GiB.

Ok, but requests_executing is not the size of an object. It's the number of objects in a linked list that satisfy a certain predicate. There are no address space size considerations here.

Quoted 4 lines

Considering that the minimum object size is 1 byte the max count of distinct objects also needs a size_t to not risk an overflow.

I'm not sure I get you, there's no overflow since you're bounds checking with the assert. Or is this a more abstract line of thought about how many ThreadPoolElements can be present in memory at a time and you'd like a type that's certain to fit the theoretical amount of objects?

Quoted 38 lines

I think that while 2^32 requests executing seems unlikely saving 4 bytes seems not worth worrying that someone will find a vulnerability triggered by overflowing a 32-bit variable (not necessary in the migration code but in some other thread pool user).

Quoted 16 lines
Quoted 16 lines
util/thread-pool.c +4 -0
  };
 
  static void *worker_thread(void *opaque)
@@ -107,6 +109,10 @@ static void *worker_thread(void *opaque)
          req = QTAILQ_FIRST(&pool->request_list);
          QTAILQ_REMOVE(&pool->request_list, req, reqs);
          req->state = THREAD_ACTIVE;
+
+        assert(pool->requests_executing < SIZE_MAX);
+        pool->requests_executing++;
+
          qemu_mutex_unlock(&pool->lock);
 
          ret = req->func(req->arg);
@@ -118,6 +124,14 @@ static void *worker_thread(void *opaque)
 
Quoted 14 lines

util/thread-pool.c static void *worker_thread(void *opaque) · line 134

Quoted 10 lines
util/thread-pool.c +8 -0
          qemu_bh_schedule(pool->completion_bh);
          qemu_mutex_lock(&pool->lock);
+
+        assert(pool->requests_executing > 0);
+        pool->requests_executing--;
+
+        if (pool->requests_executing == 0 &&
+            QTAILQ_EMPTY(&pool->request_list)) {
+            qemu_cond_signal(&pool->no_requests_cond);
+        }

An empty requests list and no request in flight means the worker will now exit after the timeout, no? Can you just kick the worker out of the wait and use pool->worker_stopped instead of the new condition variable?

Quoted 2 lines

First, all threads won't terminate if either min_threads or max_threads isn't 0.

Ah I overlooked the break condition, nevermind.

Quoted 8 lines

It might be in the migration thread pool case but we are adding a generic thread pool so it should be as universal as possible. thread_pool_free() can get away with overwriting these values since it is destroying the pool anyway.

Also, the *_join() (or whatever its final name will be) operation is about waiting for all requests / work items to finish, not about waiting for threads to terminate.

Right, but the idea was to piggyback on the thread termination to infer (the obvious) requests service termination. We cannot do that, as you've explained, fine.

Quoted 33 lines

It's essentially a synchronization point for a thread pool, not a cleanup.

Quoted 16 lines
Quoted 16 lines
util/thread-pool.c +3 -3
      }
 
      pool->cur_threads--;
@@ -243,13 +257,16 @@ static const AIOCBInfo thread_pool_aiocb_info = {
      .cancel_async       = thread_pool_cancel,
  };
 
-BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
-                                   void *arg, GDestroyNotify arg_destroy,
-                                   BlockCompletionFunc *cb, void *opaque)
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque)
  {
      ThreadPoolElement *req;
      AioContext *ctx = qemu_get_current_aio_context();
Quoted 8 lines

util/thread-pool.c static const AIOCBInfo thread_pool_aiocb_info = { · line 269

Quoted 5 lines
util/thread-pool.c +4 -1
-    ThreadPool *pool = aio_get_thread_pool(ctx);
+
+    if (!pool) {
+        pool = aio_get_thread_pool(ctx);
+    }

I'd go for a separate implementation to really drive the point that this new usage is different. See the code snippet below.

I see your point there - will split these implementations.

Quoted 3 lines

It seems we're a short step away to being able to use this implementation in a general way. Is there something that can be done with the 'common' field in the ThreadPoolElement?

Quoted 5 lines

The non-AIO request flow still need the completion callback from BlockAIOCB (and its argument pointer) so removing the "common" field from these requests would need introducing two "flavors" of ThreadPoolElement.

Not sure memory saving here are worth the increase in code complexity.

I'm not asking that of you, but I think it should be done eventually. The QEMU block layer is very particular and I wouldn't want the use-cases for the thread-pool to get confused. But I can't see a way out right now, so let's postpone this, see if anyone else has comments.

Quoted 91 lines
Quoted 83 lines

========
static void thread_pool_submit_request(ThreadPool *pool, ThreadPoolElement *req)

{
     req->state = THREAD_QUEUED;
     req->pool = pool;

     QLIST_INSERT_HEAD(&pool->head, req, all);

     trace_thread_pool_submit(pool, req, req->arg);

     qemu_mutex_lock(&pool->lock);
     if (pool->idle_threads == 0 && pool->cur_threads < pool->max_threads) {
         spawn_thread(pool);
     }
     QTAILQ_INSERT_TAIL(&pool->request_list, req, reqs);
     qemu_mutex_unlock(&pool->lock);
     qemu_cond_signal(&pool->request_cond);
}

BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, void *arg,
BlockCompletionFunc *cb, void *opaque)

{
     ThreadPoolElement *req;
     AioContext *ctx = qemu_get_current_aio_context();
     ThreadPool *pool = aio_get_thread_pool(ctx);

     /* Assert that the thread submitting work is the same running the pool */
     assert(pool->ctx == qemu_get_current_aio_context());

     req = qemu_aio_get(&thread_pool_aiocb_info, NULL, cb, opaque);
     req->func = func;
     req->arg = arg;

     thread_pool_submit_request(pool, req);
     return &req->common;
}

void thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func, void *arg)

{
     ThreadPoolElement *req;

     req = g_malloc(sizeof(ThreadPoolElement));
     req->func = func;
     req->arg = arg;

     thread_pool_submit_request(pool, req);
}

=================

Quoted 23 lines
util/thread-pool.c +12 -0
      /* Assert that the thread submitting work is the same running the pool */
      assert(pool->ctx == qemu_get_current_aio_context());
@@ -275,6 +292,18 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
      return &req->common;
  }
 
+BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
+                                   void *arg, GDestroyNotify arg_destroy,
+                                   BlockCompletionFunc *cb, void *opaque)
+{
+    return thread_pool_submit(NULL, func, arg, arg_destroy, cb, opaque);
+}
+
+void thread_pool_poll(ThreadPool *pool)
+{
+    aio_bh_poll(pool->ctx);
+}
+
  typedef struct ThreadPoolCo {
      Coroutine *co;
      int ret;

util/thread-pool.c int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg) · line 329

Quoted 6 lines
util/thread-pool.c +1 -2
@@ -297,18 +326,38 @@ int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg)
      return tpc.ret;
  }
 
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy)
+void thread_pool_join(ThreadPool *pool)

This is misleading because it's about the requests, not the threads in the pool. Compare with what thread_pool_free does:

Quoted 7 lines
     /* Wait for worker threads to terminate */
     pool->max_threads = 0;
     qemu_cond_broadcast(&pool->request_cond);
     while (pool->cur_threads > 0) {
         qemu_cond_wait(&pool->worker_stopped, &pool->lock);
     }
Quoted 1 line

I'm open to thread_pool_join() better naming proposals.

thread_pool_wait() might be better.

Quoted 3 lines

Thanks,
Maciej

#16 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 54 lines · Fabiano Rosas
Quoted 52 lines · Maciej S. Szmigiero
Quoted 50 lines · Fabiano Rosas
Quoted 35 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

---
   include/block/thread-pool.h   | 10 ++++-
   tests/unit/test-thread-pool.c |  2 +-
   util/thread-pool.c            | 77 ++++++++++++++++++++++++++++++-----
   3 files changed, 76 insertions(+), 13 deletions(-)
include/block/thread-pool.h +0 -0
index b484c4780ea6..1769496056cd 100644

include/block/thread-pool.h BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, · line 42

Quoted 8 lines
include/block/thread-pool.h +3 -2
@@ -37,9 +37,15 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
                                      void *arg, GDestroyNotify arg_destroy,
                                      BlockCompletionFunc *cb, void *opaque);
   int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg);
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy);
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque);

These kinds of changes (create wrappers, change signatures, etc), could be in their own patch as it's just code motion that should not have functional impact. The "no_requests" stuff would be better discussed in a separate patch.

Quoted 7 lines
Quoted 4 lines

These changes *all* should have no functional impact on existing callers.

But I get your overall point, will try to separate these really trivial parts.

Yeah, I guess I meant that one set of changes has a larger potential for introducing a bug while the other is clearly harmless.

I understand.

Quoted 43 lines
Quoted 43 lines
Quoted 42 lines
Quoted 36 lines
include/block/thread-pool.h +5 -0
+void thread_pool_join(ThreadPool *pool);
+void thread_pool_poll(ThreadPool *pool);
+
+void thread_pool_set_minmax_threads(ThreadPool *pool,
+                                    int min_threads, int max_threads);
   void thread_pool_update_params(ThreadPool *pool, struct AioContext *ctx);
 
   #endif
tests/unit/test-thread-pool.c +1 -1
index e4afb9e36292..469c0f7057b6 100644
@@ -46,7 +46,7 @@ static void done_cb(void *opaque, int ret)
   static void test_submit(void)
   {
       WorkerTestData data = { .n = 0 };
-    thread_pool_submit(worker_cb, &data, NULL);
+    thread_pool_submit(NULL, worker_cb, &data, NULL, NULL, NULL);
       while (data.n == 0) {
           aio_poll(ctx, true);
       }
util/thread-pool.c +1 -0
index 69a87ee79252..2bf3be875a51 100644
@@ -60,6 +60,7 @@ struct ThreadPool {
       QemuMutex lock;
       QemuCond worker_stopped;
       QemuCond request_cond;
+    QemuCond no_requests_cond;
       QEMUBH *new_thread_bh;
 
       /* The following variables are only accessed from one AioContext. */

util/thread-pool.c struct ThreadPool { · line 77

Quoted 4 lines
util/thread-pool.c +1 -0
@@ -73,6 +74,7 @@ struct ThreadPool {
       int pending_threads; /* threads created but not running yet */
       int min_threads;
       int max_threads;
+    size_t requests_executing;

What's with size_t? Should this be a uint32_t instead?

Quoted 6 lines
Quoted 2 lines

Sizes of objects are normally size_t, since otherwise bad things happen if objects are bigger than 4 GiB.

Ok, but requests_executing is not the size of an object. It's the number of objects in a linked list that satisfy a certain predicate. There are no address space size considerations here.

Max object count = Address space size / Min object size

If min object size = 1 then Max object count = Address space size

Quoted 9 lines
Quoted 4 lines

Considering that the minimum object size is 1 byte the max count of distinct objects also needs a size_t to not risk an overflow.

I'm not sure I get you, there's no overflow since you're bounds checking with the assert. Or is this a more abstract line of thought about how many ThreadPoolElements can be present in memory at a time and you'd like a type that's certain to fit the theoretical amount of objects?

It's more of theoretical thing (not to introduce an unnecessary limit) but you are right that assert() would cover any possible issues due to counter overflow, so I can change it to uint32_t indeed.

Quoted 93 lines
Quoted 38 lines

I think that while 2^32 requests executing seems unlikely saving 4 bytes seems not worth worrying that someone will find a vulnerability triggered by overflowing a 32-bit variable (not necessary in the migration code but in some other thread pool user).

Quoted 16 lines
Quoted 16 lines
util/thread-pool.c +4 -0
   };
 
   static void *worker_thread(void *opaque)
@@ -107,6 +109,10 @@ static void *worker_thread(void *opaque)
           req = QTAILQ_FIRST(&pool->request_list);
           QTAILQ_REMOVE(&pool->request_list, req, reqs);
           req->state = THREAD_ACTIVE;
+
+        assert(pool->requests_executing < SIZE_MAX);
+        pool->requests_executing++;
+
           qemu_mutex_unlock(&pool->lock);
 
           ret = req->func(req->arg);
@@ -118,6 +124,14 @@ static void *worker_thread(void *opaque)
 
Quoted 14 lines

util/thread-pool.c static void *worker_thread(void *opaque) · line 134

Quoted 10 lines
util/thread-pool.c +8 -0
           qemu_bh_schedule(pool->completion_bh);
           qemu_mutex_lock(&pool->lock);
+
+        assert(pool->requests_executing > 0);
+        pool->requests_executing--;
+
+        if (pool->requests_executing == 0 &&
+            QTAILQ_EMPTY(&pool->request_list)) {
+            qemu_cond_signal(&pool->no_requests_cond);
+        }

An empty requests list and no request in flight means the worker will now exit after the timeout, no? Can you just kick the worker out of the wait and use pool->worker_stopped instead of the new condition variable?

Quoted 2 lines

First, all threads won't terminate if either min_threads or max_threads isn't 0.

Ah I overlooked the break condition, nevermind.

Quoted 8 lines

It might be in the migration thread pool case but we are adding a generic thread pool so it should be as universal as possible. thread_pool_free() can get away with overwriting these values since it is destroying the pool anyway.

Also, the *_join() (or whatever its final name will be) operation is about waiting for all requests / work items to finish, not about waiting for threads to terminate.

Right, but the idea was to piggyback on the thread termination to infer (the obvious) requests service termination. We cannot do that, as you've explained, fine.

Quoted 37 lines

It's essentially a synchronization point for a thread pool, not a cleanup.

Quoted 16 lines
Quoted 16 lines
util/thread-pool.c +3 -3
       }
 
       pool->cur_threads--;
@@ -243,13 +257,16 @@ static const AIOCBInfo thread_pool_aiocb_info = {
       .cancel_async       = thread_pool_cancel,
   };
 
-BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
-                                   void *arg, GDestroyNotify arg_destroy,
-                                   BlockCompletionFunc *cb, void *opaque)
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque)
   {
       ThreadPoolElement *req;
       AioContext *ctx = qemu_get_current_aio_context();
Quoted 8 lines

util/thread-pool.c static const AIOCBInfo thread_pool_aiocb_info = { · line 269

Quoted 5 lines
util/thread-pool.c +4 -1
-    ThreadPool *pool = aio_get_thread_pool(ctx);
+
+    if (!pool) {
+        pool = aio_get_thread_pool(ctx);
+    }

I'd go for a separate implementation to really drive the point that this new usage is different. See the code snippet below.

I see your point there - will split these implementations.

Quoted 3 lines

It seems we're a short step away to being able to use this implementation in a general way. Is there something that can be done with the 'common' field in the ThreadPoolElement?

The non-AIO request flow still need the completion callback from BlockAIOCB (and its argument pointer) so removing the "common" field from these requests would need introducing two "flavors" of ThreadPoolElement.

Quoted 6 lines
Quoted 1 line

Not sure memory saving here are worth the increase in code complexity.

I'm not asking that of you, but I think it should be done eventually. The QEMU block layer is very particular and I wouldn't want the use-cases for the thread-pool to get confused. But I can't see a way out right now, so let's postpone this, see if anyone else has comments.

I understand.

Quoted 91 lines
Quoted 91 lines
Quoted 90 lines

========
static void thread_pool_submit_request(ThreadPool *pool, ThreadPoolElement *req)

{
      req->state = THREAD_QUEUED;
      req->pool = pool;

      QLIST_INSERT_HEAD(&pool->head, req, all);

      trace_thread_pool_submit(pool, req, req->arg);

      qemu_mutex_lock(&pool->lock);
      if (pool->idle_threads == 0 && pool->cur_threads < pool->max_threads) {
          spawn_thread(pool);
      }
      QTAILQ_INSERT_TAIL(&pool->request_list, req, reqs);
      qemu_mutex_unlock(&pool->lock);
      qemu_cond_signal(&pool->request_cond);
}

BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, void *arg,
BlockCompletionFunc *cb, void *opaque)

{
      ThreadPoolElement *req;
      AioContext *ctx = qemu_get_current_aio_context();
      ThreadPool *pool = aio_get_thread_pool(ctx);

      /* Assert that the thread submitting work is the same running the pool */
      assert(pool->ctx == qemu_get_current_aio_context());

      req = qemu_aio_get(&thread_pool_aiocb_info, NULL, cb, opaque);
      req->func = func;
      req->arg = arg;

      thread_pool_submit_request(pool, req);
      return &req->common;
}

void thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func, void *arg)

{
      ThreadPoolElement *req;

      req = g_malloc(sizeof(ThreadPoolElement));
      req->func = func;
      req->arg = arg;

      thread_pool_submit_request(pool, req);
}

=================

Quoted 23 lines
util/thread-pool.c +12 -0
       /* Assert that the thread submitting work is the same running the pool */
       assert(pool->ctx == qemu_get_current_aio_context());
@@ -275,6 +292,18 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
       return &req->common;
   }
 
+BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
+                                   void *arg, GDestroyNotify arg_destroy,
+                                   BlockCompletionFunc *cb, void *opaque)
+{
+    return thread_pool_submit(NULL, func, arg, arg_destroy, cb, opaque);
+}
+
+void thread_pool_poll(ThreadPool *pool)
+{
+    aio_bh_poll(pool->ctx);
+}
+
   typedef struct ThreadPoolCo {
       Coroutine *co;
       int ret;

util/thread-pool.c int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg) · line 329

Quoted 6 lines
util/thread-pool.c +1 -2
@@ -297,18 +326,38 @@ int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg)
       return tpc.ret;
   }
 
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy)
+void thread_pool_join(ThreadPool *pool)

This is misleading because it's about the requests, not the threads in the pool. Compare with what thread_pool_free does:

      /* Wait for worker threads to terminate */
      pool->max_threads = 0;
      qemu_cond_broadcast(&pool->request_cond);
      while (pool->cur_threads > 0) {
          qemu_cond_wait(&pool->worker_stopped, &pool->lock);
      }
Quoted 3 lines
Quoted 1 line

I'm open to thread_pool_join() better naming proposals.

thread_pool_wait() might be better.

Ack.

Thanks,
Maciej

#17 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

In reply to Maciej S. Szmigiero
Quoted 16 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

Quoted 7 lines

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

Did you consider glib's GThreadPool?
https://docs.gtk.org/glib/struct.ThreadPool.html

QEMU's thread pool is integrated into the QEMU event loop. If your goal is to bypass the QEMU event loop, then you may as well use the glib API instead.

thread_pool_join() and thread_pool_poll() will lead to code that blocks the event loop. QEMU's aio_poll() and nested event loops in general are a source of hangs and re-entrancy bugs. I would prefer not introducing these issues in the QEMU ThreadPool API.

Quoted 204 lines
---
 include/block/thread-pool.h   | 10 ++++-
 tests/unit/test-thread-pool.c |  2 +-
 util/thread-pool.c            | 77 ++++++++++++++++++++++++++++++-----
 3 files changed, 76 insertions(+), 13 deletions(-)
include/block/thread-pool.h +8 -2
index b484c4780ea6..1769496056cd 100644
@@ -37,9 +37,15 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
                                    void *arg, GDestroyNotify arg_destroy,
                                    BlockCompletionFunc *cb, void *opaque);
 int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg);
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy);
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque);
 
+void thread_pool_join(ThreadPool *pool);
+void thread_pool_poll(ThreadPool *pool);
+
+void thread_pool_set_minmax_threads(ThreadPool *pool,
+                                    int min_threads, int max_threads);
 void thread_pool_update_params(ThreadPool *pool, struct AioContext *ctx);
 
 #endif
tests/unit/test-thread-pool.c +1 -1
index e4afb9e36292..469c0f7057b6 100644
@@ -46,7 +46,7 @@ static void done_cb(void *opaque, int ret)
 static void test_submit(void)
 {
     WorkerTestData data = { .n = 0 };
-    thread_pool_submit(worker_cb, &data, NULL);
+    thread_pool_submit(NULL, worker_cb, &data, NULL, NULL, NULL);
     while (data.n == 0) {
         aio_poll(ctx, true);
     }
util/thread-pool.c +67 -10
index 69a87ee79252..2bf3be875a51 100644
@@ -60,6 +60,7 @@ struct ThreadPool {
     QemuMutex lock;
     QemuCond worker_stopped;
     QemuCond request_cond;
+    QemuCond no_requests_cond;
     QEMUBH *new_thread_bh;
 
     /* The following variables are only accessed from one AioContext. */
@@ -73,6 +74,7 @@ struct ThreadPool {
     int pending_threads; /* threads created but not running yet */
     int min_threads;
     int max_threads;
+    size_t requests_executing;
 };
 
 static void *worker_thread(void *opaque)
@@ -107,6 +109,10 @@ static void *worker_thread(void *opaque)
         req = QTAILQ_FIRST(&pool->request_list);
         QTAILQ_REMOVE(&pool->request_list, req, reqs);
         req->state = THREAD_ACTIVE;
+
+        assert(pool->requests_executing < SIZE_MAX);
+        pool->requests_executing++;
+
         qemu_mutex_unlock(&pool->lock);
 
         ret = req->func(req->arg);
@@ -118,6 +124,14 @@ static void *worker_thread(void *opaque)
 
         qemu_bh_schedule(pool->completion_bh);
         qemu_mutex_lock(&pool->lock);
+
+        assert(pool->requests_executing > 0);
+        pool->requests_executing--;
+
+        if (pool->requests_executing == 0 &&
+            QTAILQ_EMPTY(&pool->request_list)) {
+            qemu_cond_signal(&pool->no_requests_cond);
+        }
     }
 
     pool->cur_threads--;
@@ -243,13 +257,16 @@ static const AIOCBInfo thread_pool_aiocb_info = {
     .cancel_async       = thread_pool_cancel,
 };
 
-BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
-                                   void *arg, GDestroyNotify arg_destroy,
-                                   BlockCompletionFunc *cb, void *opaque)
+BlockAIOCB *thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func,
+                               void *arg, GDestroyNotify arg_destroy,
+                               BlockCompletionFunc *cb, void *opaque)
 {
     ThreadPoolElement *req;
     AioContext *ctx = qemu_get_current_aio_context();
-    ThreadPool *pool = aio_get_thread_pool(ctx);
+
+    if (!pool) {
+        pool = aio_get_thread_pool(ctx);
+    }
 
     /* Assert that the thread submitting work is the same running the pool */
     assert(pool->ctx == qemu_get_current_aio_context());
@@ -275,6 +292,18 @@ BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
     return &req->common;
 }
 
+BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func,
+                                   void *arg, GDestroyNotify arg_destroy,
+                                   BlockCompletionFunc *cb, void *opaque)
+{
+    return thread_pool_submit(NULL, func, arg, arg_destroy, cb, opaque);
+}
+
+void thread_pool_poll(ThreadPool *pool)
+{
+    aio_bh_poll(pool->ctx);
+}
+
 typedef struct ThreadPoolCo {
     Coroutine *co;
     int ret;
@@ -297,18 +326,38 @@ int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg)
     return tpc.ret;
 }
 
-void thread_pool_submit(ThreadPoolFunc *func,
-                        void *arg, GDestroyNotify arg_destroy)
+void thread_pool_join(ThreadPool *pool)
 {
-    thread_pool_submit_aio(func, arg, arg_destroy, NULL, NULL);
+    /* Assert that the thread waiting is the same running the pool */
+    assert(pool->ctx == qemu_get_current_aio_context());
+
+    qemu_mutex_lock(&pool->lock);
+
+    if (pool->requests_executing > 0 ||
+        !QTAILQ_EMPTY(&pool->request_list)) {
+        qemu_cond_wait(&pool->no_requests_cond, &pool->lock);
+    }
+    assert(pool->requests_executing == 0 &&
+           QTAILQ_EMPTY(&pool->request_list));
+
+    qemu_mutex_unlock(&pool->lock);
+
+    aio_bh_poll(pool->ctx);
+
+    assert(QLIST_EMPTY(&pool->head));
 }
 
-void thread_pool_update_params(ThreadPool *pool, AioContext *ctx)
+void thread_pool_set_minmax_threads(ThreadPool *pool,
+                                    int min_threads, int max_threads)
 {
+    assert(min_threads >= 0);
+    assert(max_threads > 0);
+    assert(max_threads >= min_threads);
+
     qemu_mutex_lock(&pool->lock);
 
-    pool->min_threads = ctx->thread_pool_min;
-    pool->max_threads = ctx->thread_pool_max;
+    pool->min_threads = min_threads;
+    pool->max_threads = max_threads;
 
     /*
      * We either have to:
@@ -330,6 +379,12 @@ void thread_pool_update_params(ThreadPool *pool, AioContext *ctx)
     qemu_mutex_unlock(&pool->lock);
 }
 
+void thread_pool_update_params(ThreadPool *pool, AioContext *ctx)
+{
+    thread_pool_set_minmax_threads(pool,
+                                   ctx->thread_pool_min, ctx->thread_pool_max);
+}
+
 static void thread_pool_init_one(ThreadPool *pool, AioContext *ctx)
 {
     if (!ctx) {
@@ -342,6 +397,7 @@ static void thread_pool_init_one(ThreadPool *pool, AioContext *ctx)
     qemu_mutex_init(&pool->lock);
     qemu_cond_init(&pool->worker_stopped);
     qemu_cond_init(&pool->request_cond);
+    qemu_cond_init(&pool->no_requests_cond);
     pool->new_thread_bh = aio_bh_new(ctx, spawn_thread_bh_fn, pool);
 
     QLIST_INIT(&pool->head);
@@ -382,6 +438,7 @@ void thread_pool_free(ThreadPool *pool)
     qemu_mutex_unlock(&pool->lock);
 
     qemu_bh_delete(pool->completion_bh);
+    qemu_cond_destroy(&pool->no_requests_cond);
     qemu_cond_destroy(&pool->request_cond);
     qemu_cond_destroy(&pool->worker_stopped);
     qemu_mutex_destroy(&pool->lock);
#18 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 29 lines · Stefan Hajnoczi
Quoted 16 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

Quoted 7 lines

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

Did you consider glib's GThreadPool?
https://docs.gtk.org/glib/struct.ThreadPool.html

Quoted 9 lines

QEMU's thread pool is integrated into the QEMU event loop. If your goal is to bypass the QEMU event loop, then you may as well use the glib API instead.

thread_pool_join() and thread_pool_poll() will lead to code that blocks the event loop. QEMU's aio_poll() and nested event loops in general are a source of hangs and re-entrancy bugs. I would prefer not introducing these issues in the QEMU ThreadPool API.

Unfortunately, the problem with the migration code is that it is synchronous - it does not return to the main event loop until the migration is done.

So the only way to handle things that need working event loop is to pump it manually from inside the migration code.

The reason why I used the QEMU thread pool in the first place in this patch set version is because Peter asked me to do so during the review of its previous iteration [1].

Peter also asked me previously to move to QEMU synchronization primitives from using the Glib ones in the early version of this patch set [2].

I personally would rather use something common to many applications, well tested and with more pairs of eyes looking at it rather to re-invent things in QEMU.

Looking at GThreadPool it seems that it lacks ability to wait until all queued work have finished, so this would need to be open-coded in the migration code.

@Peter, what's your opinion on using Glib's thread pool instead of QEMU's one, considering the above things?

Thanks,
Maciej

[1]: https://lore.kernel.org/qemu-devel/ZniFH14DT6ycjbrL@x1n/ point 5: "Worker thread model" [2]: https://lore.kernel.org/qemu-devel/Zi_9SyJy__8wJTou@x1n/

#19 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 60 lines · Maciej S. Szmigiero
Quoted 29 lines · Stefan Hajnoczi
Quoted 16 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

Quoted 7 lines

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

Did you consider glib's GThreadPool?
https://docs.gtk.org/glib/struct.ThreadPool.html

Quoted 9 lines

QEMU's thread pool is integrated into the QEMU event loop. If your goal is to bypass the QEMU event loop, then you may as well use the glib API instead.

thread_pool_join() and thread_pool_poll() will lead to code that blocks the event loop. QEMU's aio_poll() and nested event loops in general are a source of hangs and re-entrancy bugs. I would prefer not introducing these issues in the QEMU ThreadPool API.

Unfortunately, the problem with the migration code is that it is synchronous - it does not return to the main event loop until the migration is done.

So the only way to handle things that need working event loop is to pump it manually from inside the migration code.

The reason why I used the QEMU thread pool in the first place in this patch set version is because Peter asked me to do so during the review of its previous iteration [1].

Peter also asked me previously to move to QEMU synchronization primitives from using the Glib ones in the early version of this patch set [2].

I personally would rather use something common to many applications, well tested and with more pairs of eyes looking at it rather to re-invent things in QEMU.

Quoted 6 lines

Looking at GThreadPool it seems that it lacks ability to wait until all queued work have finished, so this would need to be open-coded in the migration code.

@Peter, what's your opinion on using Glib's thread pool instead of QEMU's one, considering the above things?

I'll add a bit more about my thinking:

Using QEMU's event-driven model is usually preferred because it makes integrating with the rest of QEMU easy and avoids having lots of single-purpose threads that are hard to observe/manage (e.g. through the QMP monitor).

When there is a genuine need to spawn a thread and write synchronous code (e.g. a blocking ioctl(2) call or something CPU-intensive), then it's okay to do that. Use QEMUBH, EventNotifier, or other QEMU APIs to synchronize between event loop threads and special-purpose synchronous threads.

I haven't looked at the patch series enough to have an opinion about whether this use case needs a special-purpose thread or not. I am assuming it really needs to be a special-purpose thread. Peter and you could discuss that further if you want.

I agree with Peter's request to use QEMU's synchronization primitives. They do not depend on the event loop so they can be used outside the event loop.

The issue I'm raising with this patch is that adding new join()/poll() APIs that shouldn't be called from the event loop is bug-prone. It will make the QEMU ThreadPool code harder to understand and maintain because now there are two different contexts where different subsets of this API can be used and mixing them leads to problems. To me the non-event loop case is beyond the scope of QEMU's ThreadPool. I have CCed Paolo, who wrote the thread pool in its current form in case he wants to participate in the discussion.

Using glib's ThreadPool solves the issue while still reusing an existing thread pool implementation. Waiting for all work to complete can be done using QemuSemaphore.

Thanks,
Stefan

Quoted 6 lines

Thanks,
Maciej

[1]: https://lore.kernel.org/qemu-devel/ZniFH14DT6ycjbrL@x1n/ point 5: "Worker thread model" [2]: https://lore.kernel.org/qemu-devel/Zi_9SyJy__8wJTou@x1n/

#20 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Hi, Stefan, Maciej,

Sorry to be slow on responding.

Quoted 71 lines · Stefan Hajnoczi
Quoted 60 lines · Maciej S. Szmigiero
Quoted 29 lines · Stefan Hajnoczi
Quoted 16 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

Quoted 7 lines

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

Did you consider glib's GThreadPool?
https://docs.gtk.org/glib/struct.ThreadPool.html

Quoted 9 lines

QEMU's thread pool is integrated into the QEMU event loop. If your goal is to bypass the QEMU event loop, then you may as well use the glib API instead.

thread_pool_join() and thread_pool_poll() will lead to code that blocks the event loop. QEMU's aio_poll() and nested event loops in general are a source of hangs and re-entrancy bugs. I would prefer not introducing these issues in the QEMU ThreadPool API.

Unfortunately, the problem with the migration code is that it is synchronous - it does not return to the main event loop until the migration is done.

So the only way to handle things that need working event loop is to pump it manually from inside the migration code.

The reason why I used the QEMU thread pool in the first place in this patch set version is because Peter asked me to do so during the review of its previous iteration [1].

Peter also asked me previously to move to QEMU synchronization primitives from using the Glib ones in the early version of this patch set [2].

I personally would rather use something common to many applications, well tested and with more pairs of eyes looking at it rather to re-invent things in QEMU.

Quoted 6 lines

Looking at GThreadPool it seems that it lacks ability to wait until all queued work have finished, so this would need to be open-coded in the migration code.

@Peter, what's your opinion on using Glib's thread pool instead of QEMU's one, considering the above things?

I'll add a bit more about my thinking:

Quoted 7 lines

Using QEMU's event-driven model is usually preferred because it makes integrating with the rest of QEMU easy and avoids having lots of single-purpose threads that are hard to observe/manage (e.g. through the QMP monitor).

When there is a genuine need to spawn a thread and write synchronous code (e.g. a blocking ioctl(2) call or something CPU-intensive), then

Right, AFAIU this is the current use case for VFIO, and anything beyond in migration context, where we want to use genuine threads with no need to integrate with the main even loop.

Currently the VFIO workfn should read() the VFIO fd in a blocked way, then dump them to multifd threads (further dump to migration channels), during which it can wait on a semaphore.

Quoted 22 lines

it's okay to do that. Use QEMUBH, EventNotifier, or other QEMU APIs to synchronize between event loop threads and special-purpose synchronous threads.

I haven't looked at the patch series enough to have an opinion about whether this use case needs a special-purpose thread or not. I am assuming it really needs to be a special-purpose thread. Peter and you could discuss that further if you want.

I agree with Peter's request to use QEMU's synchronization primitives. They do not depend on the event loop so they can be used outside the event loop.

The issue I'm raising with this patch is that adding new join()/poll() APIs that shouldn't be called from the event loop is bug-prone. It will make the QEMU ThreadPool code harder to understand and maintain because now there are two different contexts where different subsets of this API can be used and mixing them leads to problems. To me the non-event loop case is beyond the scope of QEMU's ThreadPool. I have CCed Paolo, who wrote the thread pool in its current form in case he wants to participate in the discussion.

Quoted 3 lines

Using glib's ThreadPool solves the issue while still reusing an existing thread pool implementation. Waiting for all work to complete can be done using QemuSemaphore.

Right. It's a pity that g_thread_pool_unprocessed() only monitors unqueuing of tasks, and looks like there's no g_thread_pool_flush().

Indeed the current thread poll is very aio-centric, and if we worry about misuse of the APIs we can switch to glib's threadpool. Sorry Maciej, looks like I routed you to a direction that I didn't see the side effects..

I think the fundamental request from my side (on behalf of migration) is we should avoid a specific vmstate handler managing threads on its own. E.g., any future devices (vdpa, vcpu, etc.) that may also be able to offload save() processes concurrently to threads (just like what VFIO can already do right now) should share the same pool of threads. As long as that can be achieved I am ok.

Thanks,

Signature · 1 line
Peter Xu
#21 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 125 lines · Peter Xu

Hi, Stefan, Maciej,

Sorry to be slow on responding.

Quoted 71 lines · Stefan Hajnoczi
Quoted 60 lines · Maciej S. Szmigiero
Quoted 29 lines · Stefan Hajnoczi
Quoted 16 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

Quoted 7 lines

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

Did you consider glib's GThreadPool?
https://docs.gtk.org/glib/struct.ThreadPool.html

Quoted 9 lines

QEMU's thread pool is integrated into the QEMU event loop. If your goal is to bypass the QEMU event loop, then you may as well use the glib API instead.

thread_pool_join() and thread_pool_poll() will lead to code that blocks the event loop. QEMU's aio_poll() and nested event loops in general are a source of hangs and re-entrancy bugs. I would prefer not introducing these issues in the QEMU ThreadPool API.

Unfortunately, the problem with the migration code is that it is synchronous - it does not return to the main event loop until the migration is done.

So the only way to handle things that need working event loop is to pump it manually from inside the migration code.

The reason why I used the QEMU thread pool in the first place in this patch set version is because Peter asked me to do so during the review of its previous iteration [1].

Peter also asked me previously to move to QEMU synchronization primitives from using the Glib ones in the early version of this patch set [2].

I personally would rather use something common to many applications, well tested and with more pairs of eyes looking at it rather to re-invent things in QEMU.

Quoted 6 lines

Looking at GThreadPool it seems that it lacks ability to wait until all queued work have finished, so this would need to be open-coded in the migration code.

@Peter, what's your opinion on using Glib's thread pool instead of QEMU's one, considering the above things?

I'll add a bit more about my thinking:

Quoted 7 lines

Using QEMU's event-driven model is usually preferred because it makes integrating with the rest of QEMU easy and avoids having lots of single-purpose threads that are hard to observe/manage (e.g. through the QMP monitor).

When there is a genuine need to spawn a thread and write synchronous code (e.g. a blocking ioctl(2) call or something CPU-intensive), then

Right, AFAIU this is the current use case for VFIO, and anything beyond in migration context, where we want to use genuine threads with no need to integrate with the main even loop.

Currently the VFIO workfn should read() the VFIO fd in a blocked way, then dump them to multifd threads (further dump to migration channels), during which it can wait on a semaphore.

Quoted 22 lines

it's okay to do that. Use QEMUBH, EventNotifier, or other QEMU APIs to synchronize between event loop threads and special-purpose synchronous threads.

I haven't looked at the patch series enough to have an opinion about whether this use case needs a special-purpose thread or not. I am assuming it really needs to be a special-purpose thread. Peter and you could discuss that further if you want.

I agree with Peter's request to use QEMU's synchronization primitives. They do not depend on the event loop so they can be used outside the event loop.

The issue I'm raising with this patch is that adding new join()/poll() APIs that shouldn't be called from the event loop is bug-prone. It will make the QEMU ThreadPool code harder to understand and maintain because now there are two different contexts where different subsets of this API can be used and mixing them leads to problems. To me the non-event loop case is beyond the scope of QEMU's ThreadPool. I have CCed Paolo, who wrote the thread pool in its current form in case he wants to participate in the discussion.

Quoted 3 lines

Using glib's ThreadPool solves the issue while still reusing an existing thread pool implementation. Waiting for all work to complete can be done using QemuSemaphore.

Right. It's a pity that g_thread_pool_unprocessed() only monitors unqueuing of tasks, and looks like there's no g_thread_pool_flush().

Indeed the current thread poll is very aio-centric, and if we worry about misuse of the APIs we can switch to glib's threadpool. Sorry Maciej, looks like I routed you to a direction that I didn't see the side effects..

Quoted 6 lines

I think the fundamental request from my side (on behalf of migration) is we should avoid a specific vmstate handler managing threads on its own. E.g., any future devices (vdpa, vcpu, etc.) that may also be able to offload save() processes concurrently to threads (just like what VFIO can already do right now) should share the same pool of threads. As long as that can be achieved I am ok.

So, to be clear - do you still prefer using the (extended) QEMU's thread pool or rather prefer switching to the Glib thread pool instead (with thread_pool_wait() equivalent reimplemented inside QEMU since Glib lacks it)?

Quoted 2 lines

Thanks,

Thanks,
Maciej

#22 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 133 lines · Maciej S. Szmigiero
Quoted 125 lines · Peter Xu

Hi, Stefan, Maciej,

Sorry to be slow on responding.

Quoted 71 lines · Stefan Hajnoczi
Quoted 60 lines · Maciej S. Szmigiero
Quoted 29 lines · Stefan Hajnoczi
Quoted 16 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

Quoted 7 lines

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

Did you consider glib's GThreadPool?
https://docs.gtk.org/glib/struct.ThreadPool.html

Quoted 9 lines

QEMU's thread pool is integrated into the QEMU event loop. If your goal is to bypass the QEMU event loop, then you may as well use the glib API instead.

thread_pool_join() and thread_pool_poll() will lead to code that blocks the event loop. QEMU's aio_poll() and nested event loops in general are a source of hangs and re-entrancy bugs. I would prefer not introducing these issues in the QEMU ThreadPool API.

Unfortunately, the problem with the migration code is that it is synchronous - it does not return to the main event loop until the migration is done.

So the only way to handle things that need working event loop is to pump it manually from inside the migration code.

The reason why I used the QEMU thread pool in the first place in this patch set version is because Peter asked me to do so during the review of its previous iteration [1].

Peter also asked me previously to move to QEMU synchronization primitives from using the Glib ones in the early version of this patch set [2].

I personally would rather use something common to many applications, well tested and with more pairs of eyes looking at it rather to re-invent things in QEMU.

Quoted 6 lines

Looking at GThreadPool it seems that it lacks ability to wait until all queued work have finished, so this would need to be open-coded in the migration code.

@Peter, what's your opinion on using Glib's thread pool instead of QEMU's one, considering the above things?

I'll add a bit more about my thinking:

Quoted 7 lines

Using QEMU's event-driven model is usually preferred because it makes integrating with the rest of QEMU easy and avoids having lots of single-purpose threads that are hard to observe/manage (e.g. through the QMP monitor).

When there is a genuine need to spawn a thread and write synchronous code (e.g. a blocking ioctl(2) call or something CPU-intensive), then

Right, AFAIU this is the current use case for VFIO, and anything beyond in migration context, where we want to use genuine threads with no need to integrate with the main even loop.

Currently the VFIO workfn should read() the VFIO fd in a blocked way, then dump them to multifd threads (further dump to migration channels), during which it can wait on a semaphore.

Quoted 22 lines

it's okay to do that. Use QEMUBH, EventNotifier, or other QEMU APIs to synchronize between event loop threads and special-purpose synchronous threads.

I haven't looked at the patch series enough to have an opinion about whether this use case needs a special-purpose thread or not. I am assuming it really needs to be a special-purpose thread. Peter and you could discuss that further if you want.

I agree with Peter's request to use QEMU's synchronization primitives. They do not depend on the event loop so they can be used outside the event loop.

The issue I'm raising with this patch is that adding new join()/poll() APIs that shouldn't be called from the event loop is bug-prone. It will make the QEMU ThreadPool code harder to understand and maintain because now there are two different contexts where different subsets of this API can be used and mixing them leads to problems. To me the non-event loop case is beyond the scope of QEMU's ThreadPool. I have CCed Paolo, who wrote the thread pool in its current form in case he wants to participate in the discussion.

Quoted 3 lines

Using glib's ThreadPool solves the issue while still reusing an existing thread pool implementation. Waiting for all work to complete can be done using QemuSemaphore.

Right. It's a pity that g_thread_pool_unprocessed() only monitors unqueuing of tasks, and looks like there's no g_thread_pool_flush().

Indeed the current thread poll is very aio-centric, and if we worry about misuse of the APIs we can switch to glib's threadpool. Sorry Maciej, looks like I routed you to a direction that I didn't see the side effects..

Quoted 6 lines

I think the fundamental request from my side (on behalf of migration) is we should avoid a specific vmstate handler managing threads on its own. E.g., any future devices (vdpa, vcpu, etc.) that may also be able to offload save() processes concurrently to threads (just like what VFIO can already do right now) should share the same pool of threads. As long as that can be achieved I am ok.

Quoted 3 lines

So, to be clear - do you still prefer using the (extended) QEMU's thread pool or rather prefer switching to the Glib thread pool instead (with thread_pool_wait() equivalent reimplemented inside QEMU since Glib lacks it)?

After reading Stefan's comment, I prefer the latter.

I wonder whether we should rename the current ThreadPool to AioThreadPool or similar, so that it'll be crystal clear we want it to stick to aio context. Then the new pool can be the raw thread pool (and I also wonder whether at some point the aio thread pool can still reuse the raw thread pool to some degree).

And yes, it'll be nice we can wrap glib's with a wait() semantics.

Thanks,

Signature · 1 line
Peter Xu
#23 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 140 lines · Peter Xu
Quoted 133 lines · Maciej S. Szmigiero
Quoted 125 lines · Peter Xu

Hi, Stefan, Maciej,

Sorry to be slow on responding.

Quoted 71 lines · Stefan Hajnoczi
Quoted 60 lines · Maciej S. Szmigiero
Quoted 29 lines · Stefan Hajnoczi
Quoted 16 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Migration code wants to manage device data sending threads in one place.

QEMU has an existing thread pool implementation, however it was limited to queuing AIO operations only and essentially had a 1:1 mapping between the current AioContext and the ThreadPool in use.

Implement what is necessary to queue generic (non-AIO) work on a ThreadPool too.

This brings a few new operations on a pool:
* thread_pool_set_minmax_threads() explicitly sets the minimum and maximum thread count in the pool.

Quoted 7 lines

* thread_pool_join() operation waits until all the submitted work requests have finished.

* thread_pool_poll() lets the new thread and / or thread completion bottom halves run (if they are indeed scheduled to be run).
It is useful for thread pool users that need to launch or terminate new threads without returning to the QEMU main loop.

Did you consider glib's GThreadPool?
https://docs.gtk.org/glib/struct.ThreadPool.html

Quoted 9 lines

QEMU's thread pool is integrated into the QEMU event loop. If your goal is to bypass the QEMU event loop, then you may as well use the glib API instead.

thread_pool_join() and thread_pool_poll() will lead to code that blocks the event loop. QEMU's aio_poll() and nested event loops in general are a source of hangs and re-entrancy bugs. I would prefer not introducing these issues in the QEMU ThreadPool API.

Unfortunately, the problem with the migration code is that it is synchronous - it does not return to the main event loop until the migration is done.

So the only way to handle things that need working event loop is to pump it manually from inside the migration code.

The reason why I used the QEMU thread pool in the first place in this patch set version is because Peter asked me to do so during the review of its previous iteration [1].

Peter also asked me previously to move to QEMU synchronization primitives from using the Glib ones in the early version of this patch set [2].

I personally would rather use something common to many applications, well tested and with more pairs of eyes looking at it rather to re-invent things in QEMU.

Quoted 6 lines

Looking at GThreadPool it seems that it lacks ability to wait until all queued work have finished, so this would need to be open-coded in the migration code.

@Peter, what's your opinion on using Glib's thread pool instead of QEMU's one, considering the above things?

I'll add a bit more about my thinking:

Quoted 7 lines

Using QEMU's event-driven model is usually preferred because it makes integrating with the rest of QEMU easy and avoids having lots of single-purpose threads that are hard to observe/manage (e.g. through the QMP monitor).

When there is a genuine need to spawn a thread and write synchronous code (e.g. a blocking ioctl(2) call or something CPU-intensive), then

Right, AFAIU this is the current use case for VFIO, and anything beyond in migration context, where we want to use genuine threads with no need to integrate with the main even loop.

Currently the VFIO workfn should read() the VFIO fd in a blocked way, then dump them to multifd threads (further dump to migration channels), during which it can wait on a semaphore.

Quoted 22 lines

it's okay to do that. Use QEMUBH, EventNotifier, or other QEMU APIs to synchronize between event loop threads and special-purpose synchronous threads.

I haven't looked at the patch series enough to have an opinion about whether this use case needs a special-purpose thread or not. I am assuming it really needs to be a special-purpose thread. Peter and you could discuss that further if you want.

I agree with Peter's request to use QEMU's synchronization primitives. They do not depend on the event loop so they can be used outside the event loop.

The issue I'm raising with this patch is that adding new join()/poll() APIs that shouldn't be called from the event loop is bug-prone. It will make the QEMU ThreadPool code harder to understand and maintain because now there are two different contexts where different subsets of this API can be used and mixing them leads to problems. To me the non-event loop case is beyond the scope of QEMU's ThreadPool. I have CCed Paolo, who wrote the thread pool in its current form in case he wants to participate in the discussion.

Quoted 3 lines

Using glib's ThreadPool solves the issue while still reusing an existing thread pool implementation. Waiting for all work to complete can be done using QemuSemaphore.

Right. It's a pity that g_thread_pool_unprocessed() only monitors unqueuing of tasks, and looks like there's no g_thread_pool_flush().

Indeed the current thread poll is very aio-centric, and if we worry about misuse of the APIs we can switch to glib's threadpool. Sorry Maciej, looks like I routed you to a direction that I didn't see the side effects..

Quoted 6 lines

I think the fundamental request from my side (on behalf of migration) is we should avoid a specific vmstate handler managing threads on its own. E.g., any future devices (vdpa, vcpu, etc.) that may also be able to offload save() processes concurrently to threads (just like what VFIO can already do right now) should share the same pool of threads. As long as that can be achieved I am ok.

Quoted 3 lines

So, to be clear - do you still prefer using the (extended) QEMU's thread pool or rather prefer switching to the Glib thread pool instead (with thread_pool_wait() equivalent reimplemented inside QEMU since Glib lacks it)?

After reading Stefan's comment, I prefer the latter.

Quoted 7 lines

I wonder whether we should rename the current ThreadPool to AioThreadPool or similar, so that it'll be crystal clear we want it to stick to aio context. Then the new pool can be the raw thread pool (and I also wonder whether at some point the aio thread pool can still reuse the raw thread pool to some degree).

And yes, it'll be nice we can wrap glib's with a wait() semantics.

So, if I understand your design correctly, you want to basically wrap the Glib's GThreadPool into some QEMU GenericThreadPool and then use the later in multifd code, right?

Quoted 2 lines

Thanks,

Thanks,
Maciej

#24 lore raw

Re: [PATCH v2 05/17] thread-pool: Implement non-AIO (generic) pool support

Quoted 3 lines · Maciej S. Szmigiero

So, if I understand your design correctly, you want to basically wrap the Glib's GThreadPool into some QEMU GenericThreadPool and then use the later in multifd code, right?

Yes. I didn't have an explicit picture yet in mind, but what you said makes sense to me.

Signature · 1 line
Peter Xu
#25 lore raw

PATCH v2 6/17 migration: Add save_live_complete_precopy_{begin, end} handlers

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
 include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
 migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
 2 files changed, 71 insertions(+)
include/migration/register.h +36 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
      */
     int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);
+
     /* This runs both outside and inside the BQL.  */
 
     /**
migration/savevm.c +35 -0
index 6bb404b9c86f..d43acbbf20cf 100644
@@ -1496,6 +1496,27 @@ int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
     SaveStateEntry *se;
     int ret;
 
+    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
+        if (!se->ops || (in_postcopy && se->ops->has_postcopy &&
+             se->ops->has_postcopy(se->opaque)) ||
+            !se->ops->save_live_complete_precopy_begin) {
+            continue;
+        }
+
+        save_section_header(f, se, QEMU_VM_SECTION_END);
+
+        ret = se->ops->save_live_complete_precopy_begin(f,
+                                                        se->idstr, se->instance_id,
+                                                        se->opaque);
+
+        save_section_footer(f, se);
+
+        if (ret < 0) {
+            qemu_file_set_error(f, ret);
+            return -1;
+        }
+    }
+
     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
         if (!se->ops ||
             (in_postcopy && se->ops->has_postcopy &&
@@ -1527,6 +1548,20 @@ int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
                                     end_ts_each - start_ts_each);
     }
 
+    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
+        if (!se->ops || (in_postcopy && se->ops->has_postcopy &&
+             se->ops->has_postcopy(se->opaque)) ||
+            !se->ops->save_live_complete_precopy_end) {
+            continue;
+        }
+
+        ret = se->ops->save_live_complete_precopy_end(f, se->opaque);
+        if (ret < 0) {
+            qemu_file_set_error(f, ret);
+            return -1;
+        }
+    }
+
     trace_vmstate_downtime_checkpoint("src-iterable-saved");
 
     return 0;
Reviewed-by on v2 6/17
#26 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

Quoted 5 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

Quoted 7 lines

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

#27 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

In reply to Maciej S. Szmigiero
Quoted 53 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
  include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
  migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
  2 files changed, 71 insertions(+)
include/migration/register.h +25 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
       */
      int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 10 lines
include/migration/register.h +10 -0
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Thanks.

Quoted 57 lines
include/migration/register.h +1 -0
+
      /* This runs both outside and inside the BQL.  */
 
      /**
migration/savevm.c +35 -0
index 6bb404b9c86f..d43acbbf20cf 100644
@@ -1496,6 +1496,27 @@ int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
      SaveStateEntry *se;
      int ret;
 
+    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
+        if (!se->ops || (in_postcopy && se->ops->has_postcopy &&
+             se->ops->has_postcopy(se->opaque)) ||
+            !se->ops->save_live_complete_precopy_begin) {
+            continue;
+        }
+
+        save_section_header(f, se, QEMU_VM_SECTION_END);
+
+        ret = se->ops->save_live_complete_precopy_begin(f,
+                                                        se->idstr, se->instance_id,
+                                                        se->opaque);
+
+        save_section_footer(f, se);
+
+        if (ret < 0) {
+            qemu_file_set_error(f, ret);
+            return -1;
+        }
+    }
+
      QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
          if (!se->ops ||
              (in_postcopy && se->ops->has_postcopy &&
@@ -1527,6 +1548,20 @@ int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
                                      end_ts_each - start_ts_each);
      }
 
+    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
+        if (!se->ops || (in_postcopy && se->ops->has_postcopy &&
+             se->ops->has_postcopy(se->opaque)) ||
+            !se->ops->save_live_complete_precopy_end) {
+            continue;
+        }
+
+        ret = se->ops->save_live_complete_precopy_end(f, se->opaque);
+        if (ret < 0) {
+            qemu_file_set_error(f, ret);
+            return -1;
+        }
+    }
+
      trace_vmstate_downtime_checkpoint("src-iterable-saved");
 
      return 0;
#28 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

Quoted 60 lines · Avihai Horon
Quoted 58 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
  include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
  migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
  2 files changed, 71 insertions(+)
include/migration/register.h +30 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
       */
      int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 5 lines
include/migration/register.h +5 -0
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Right, I spot the same thing.

This series added three hooks: begin, end, precopy_thread.

What I think is it only needs one, which is precopy_async. My vague memory was that was what we used to discuss too, so that when migration precopy flushes the final round of iterable data, it does:

(1) loop over all complete_precopy_async() and enqueue the tasks if existed into the migration worker pool. Then,

(2) loop over all complete_precopy() like before.

Optionally, we can enforce one vmstate handler only provides either complete_precopy_async() or complete_precopy(). In this case VFIO can update the two hooks during setup() by detecting multifd && !mapped_ram && nocomp.

Signature · 1 line
Peter Xu
#29 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

Quoted 81 lines · Peter Xu
Quoted 60 lines · Avihai Horon
Quoted 58 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
   include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
   migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
   2 files changed, 71 insertions(+)
include/migration/register.h +30 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
        */
       int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 5 lines
include/migration/register.h +5 -0
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Right, I spot the same thing.

This series added three hooks: begin, end, precopy_thread.

What I think is it only needs one, which is precopy_async. My vague memory was that was what we used to discuss too, so that when migration precopy flushes the final round of iterable data, it does:

(1) loop over all complete_precopy_async() and enqueue the tasks if existed into the migration worker pool. Then,

Quoted 7 lines

(2) loop over all complete_precopy() like before.

Optionally, we can enforce one vmstate handler only provides either complete_precopy_async() or complete_precopy(). In this case VFIO can update the two hooks during setup() by detecting multifd && !mapped_ram && nocomp.

The "_begin" hook is still necessary to mark the end of the device state sent via the main migration stream (during the phase VM is still running) since we can't start loading the multifd sent device state until all of that earlier data finishes loading first.

We shouldn't send that boundary marker in .save_live_complete_precopy either since it would meant unnecessary waiting for other devices (not necessary VFIO ones) .save_live_complete_precopy bulk data.

And VFIO SaveVMHandlers are shared for all VFIO devices (and const) so we can't really change them at runtime.

Thanks,
Maciej

#30 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

Quoted 90 lines · Maciej S. Szmigiero
Quoted 81 lines · Peter Xu
Quoted 60 lines · Avihai Horon
Quoted 58 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
   include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
   migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
   2 files changed, 71 insertions(+)
include/migration/register.h +30 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
        */
       int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 5 lines
include/migration/register.h +5 -0
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Right, I spot the same thing.

This series added three hooks: begin, end, precopy_thread.

What I think is it only needs one, which is precopy_async. My vague memory was that was what we used to discuss too, so that when migration precopy flushes the final round of iterable data, it does:

(1) loop over all complete_precopy_async() and enqueue the tasks if existed into the migration worker pool. Then,

Quoted 7 lines

(2) loop over all complete_precopy() like before.

Optionally, we can enforce one vmstate handler only provides either complete_precopy_async() or complete_precopy(). In this case VFIO can update the two hooks during setup() by detecting multifd && !mapped_ram && nocomp.

Quoted 4 lines

The "_begin" hook is still necessary to mark the end of the device state sent via the main migration stream (during the phase VM is still running) since we can't start loading the multifd sent device state until all of that earlier data finishes loading first.

Ah I remembered some more now, thanks.

If vfio can send data during iterations this new hook will also not be needed, right?

I remember you mentioned you'd have a look and see the challenges there, is there any conclusion yet on whether we can use multifd even during that?

It's also a pity that we introduce this hook only because we want a boundary between "iterable stage" and "final stage". IIUC if we have any kind of message telling dest before hand that "we're going to the last stage" then this hook can be avoided. Now it's at least inefficient because we need to trigger begin() per-device, even if I think it's more of a global request saying that "we need to load all main stream data first before moving on".

Quoted 7 lines

We shouldn't send that boundary marker in .save_live_complete_precopy either since it would meant unnecessary waiting for other devices (not necessary VFIO ones) .save_live_complete_precopy bulk data.

And VFIO SaveVMHandlers are shared for all VFIO devices (and const) so we can't really change them at runtime.

In all cases, please consider dropping end() if it's never used; IMO it's fine if there is only begin(), and we shouldn't keep hooks that are never used.

Thanks,

Signature · 1 line
Peter Xu
#31 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

Quoted 104 lines · Peter Xu
Quoted 90 lines · Maciej S. Szmigiero
Quoted 81 lines · Peter Xu
Quoted 60 lines · Avihai Horon
Quoted 58 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
   include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
   migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
   2 files changed, 71 insertions(+)
include/migration/register.h +30 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
        */
       int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 5 lines
include/migration/register.h +5 -0
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Right, I spot the same thing.

This series added three hooks: begin, end, precopy_thread.

What I think is it only needs one, which is precopy_async. My vague memory was that was what we used to discuss too, so that when migration precopy flushes the final round of iterable data, it does:

(1) loop over all complete_precopy_async() and enqueue the tasks if existed into the migration worker pool. Then,

Quoted 7 lines

(2) loop over all complete_precopy() like before.

Optionally, we can enforce one vmstate handler only provides either complete_precopy_async() or complete_precopy(). In this case VFIO can update the two hooks during setup() by detecting multifd && !mapped_ram && nocomp.

Quoted 4 lines

The "_begin" hook is still necessary to mark the end of the device state sent via the main migration stream (during the phase VM is still running) since we can't start loading the multifd sent device state until all of that earlier data finishes loading first.

Ah I remembered some more now, thanks.

If vfio can send data during iterations this new hook will also not be needed, right?

I remember you mentioned you'd have a look and see the challenges there, is there any conclusion yet on whether we can use multifd even during that?

Quoted 7 lines

It's also a pity that we introduce this hook only because we want a boundary between "iterable stage" and "final stage". IIUC if we have any kind of message telling dest before hand that "we're going to the last stage" then this hook can be avoided. Now it's at least inefficient because we need to trigger begin() per-device, even if I think it's more of a global request saying that "we need to load all main stream data first before moving on".

Or, we could add one MIG_CMD_SWITCHOVER under QEMU_VM_COMMAND, then send it at the beginning of the switchover phase. Then we can have a generic marker on destination to be the boundary of "iterations" v.s. "switchover". Then I think we can also drop the begin() here, just to avoid one such sync per-device (also in case if others may have such need, like vdpa, then vdpa doesn't need that flag too).

Fundamentally, that makes the VFIO_MIG_FLAG_DEV_DATA_STATE_COMPLETE to be a migration flag..

But for sure the best is still if VFIO can enable multifd even during iterations. Then the boundary guard may not be needed.

Quoted 17 lines
Quoted 8 lines

We shouldn't send that boundary marker in .save_live_complete_precopy either since it would meant unnecessary waiting for other devices (not necessary VFIO ones) .save_live_complete_precopy bulk data.

And VFIO SaveVMHandlers are shared for all VFIO devices (and const) so we can't really change them at runtime.

In all cases, please consider dropping end() if it's never used; IMO it's fine if there is only begin(), and we shouldn't keep hooks that are never used.

Thanks,

Signature · 1 line
Peter Xu
Signature · 1 line
Peter Xu
#32 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

Quoted 120 lines · Peter Xu
Quoted 104 lines · Peter Xu
Quoted 90 lines · Maciej S. Szmigiero
Quoted 81 lines · Peter Xu
Quoted 60 lines · Avihai Horon
Quoted 58 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
    include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
    migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
    2 files changed, 71 insertions(+)
include/migration/register.h +30 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
         */
        int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 5 lines
include/migration/register.h +5 -0
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Right, I spot the same thing.

This series added three hooks: begin, end, precopy_thread.

What I think is it only needs one, which is precopy_async. My vague memory was that was what we used to discuss too, so that when migration precopy flushes the final round of iterable data, it does:

(1) loop over all complete_precopy_async() and enqueue the tasks if existed into the migration worker pool. Then,

Quoted 7 lines

(2) loop over all complete_precopy() like before.

Optionally, we can enforce one vmstate handler only provides either complete_precopy_async() or complete_precopy(). In this case VFIO can update the two hooks during setup() by detecting multifd && !mapped_ram && nocomp.

Quoted 4 lines

The "_begin" hook is still necessary to mark the end of the device state sent via the main migration stream (during the phase VM is still running) since we can't start loading the multifd sent device state until all of that earlier data finishes loading first.

Ah I remembered some more now, thanks.

If vfio can send data during iterations this new hook will also not be needed, right?

I remember you mentioned you'd have a look and see the challenges there, is there any conclusion yet on whether we can use multifd even during that?

Quoted 7 lines

It's also a pity that we introduce this hook only because we want a boundary between "iterable stage" and "final stage". IIUC if we have any kind of message telling dest before hand that "we're going to the last stage" then this hook can be avoided. Now it's at least inefficient because we need to trigger begin() per-device, even if I think it's more of a global request saying that "we need to load all main stream data first before moving on".

Or, we could add one MIG_CMD_SWITCHOVER under QEMU_VM_COMMAND, then send it at the beginning of the switchover phase. Then we can have a generic marker on destination to be the boundary of "iterations" v.s. "switchover". Then I think we can also drop the begin() here, just to avoid one such sync per-device (also in case if others may have such need, like vdpa, then vdpa doesn't need that flag too).

Quoted 5 lines

Fundamentally, that makes the VFIO_MIG_FLAG_DEV_DATA_STATE_COMPLETE to be a migration flag..

But for sure the best is still if VFIO can enable multifd even during iterations. Then the boundary guard may not be needed.

That begin() handler was supposed to be generic for multiple device types, that's why it was paired with the end() one that has no current use.

But you are right that using a single "barrier" or "sync" command for all device types makes sense, so I will change it to MIG_CMD_SWITCHOVER.

Thanks,
Maciej

#33 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

In reply to Peter Xu
Quoted 96 lines · Peter Xu
Quoted 90 lines · Maciej S. Szmigiero
Quoted 81 lines · Peter Xu
Quoted 60 lines · Avihai Horon
Quoted 58 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
    include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
    migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
    2 files changed, 71 insertions(+)
include/migration/register.h +30 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
         */
        int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 5 lines
include/migration/register.h +5 -0
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Right, I spot the same thing.

This series added three hooks: begin, end, precopy_thread.

What I think is it only needs one, which is precopy_async. My vague memory was that was what we used to discuss too, so that when migration precopy flushes the final round of iterable data, it does:

(1) loop over all complete_precopy_async() and enqueue the tasks if existed into the migration worker pool. Then,

Quoted 7 lines

(2) loop over all complete_precopy() like before.

Optionally, we can enforce one vmstate handler only provides either complete_precopy_async() or complete_precopy(). In this case VFIO can update the two hooks during setup() by detecting multifd && !mapped_ram && nocomp.

Quoted 4 lines

The "_begin" hook is still necessary to mark the end of the device state sent via the main migration stream (during the phase VM is still running) since we can't start loading the multifd sent device state until all of that earlier data finishes loading first.

Quoted 7 lines

Ah I remembered some more now, thanks.

If vfio can send data during iterations this new hook will also not be needed, right?

I remember you mentioned you'd have a look and see the challenges there, is there any conclusion yet on whether we can use multifd even during that?

Yeah, I looked at that and it wasn't a straightforward thing to introduce.

I am worried that with all the things that already piled up (including the new thread pool implementation) we risk missing QEMU 9.2 too if this is included.

Quoted 7 lines

It's also a pity that we introduce this hook only because we want a boundary between "iterable stage" and "final stage". IIUC if we have any kind of message telling dest before hand that "we're going to the last stage" then this hook can be avoided. Now it's at least inefficient because we need to trigger begin() per-device, even if I think it's more of a global request saying that "we need to load all main stream data first before moving on".

It should be pretty easy to remove that begin() hook once it is no longer needed - after all, it's only necessary for the sender.

Quoted 11 lines
Quoted 7 lines

We shouldn't send that boundary marker in .save_live_complete_precopy either since it would meant unnecessary waiting for other devices (not necessary VFIO ones) .save_live_complete_precopy bulk data.

And VFIO SaveVMHandlers are shared for all VFIO devices (and const) so we can't really change them at runtime.

In all cases, please consider dropping end() if it's never used; IMO it's fine if there is only begin(), and we shouldn't keep hooks that are never used.

Okay, will remove the end() hook then.

Quoted 2 lines

Thanks,

Thanks,
Maciej

#34 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

Quoted 102 lines · Maciej S. Szmigiero
Quoted 101 lines · Peter Xu
Quoted 90 lines · Maciej S. Szmigiero
Quoted 81 lines · Peter Xu
Quoted 60 lines · Avihai Horon
Quoted 58 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
    include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
    migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
    2 files changed, 71 insertions(+)
include/migration/register.h +30 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
         */
        int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 5 lines
include/migration/register.h +5 -0
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Right, I spot the same thing.

This series added three hooks: begin, end, precopy_thread.

What I think is it only needs one, which is precopy_async. My vague memory was that was what we used to discuss too, so that when migration precopy flushes the final round of iterable data, it does:

(1) loop over all complete_precopy_async() and enqueue the tasks if existed into the migration worker pool. Then,

Quoted 7 lines

(2) loop over all complete_precopy() like before.

Optionally, we can enforce one vmstate handler only provides either complete_precopy_async() or complete_precopy(). In this case VFIO can update the two hooks during setup() by detecting multifd && !mapped_ram && nocomp.

Quoted 4 lines

The "_begin" hook is still necessary to mark the end of the device state sent via the main migration stream (during the phase VM is still running) since we can't start loading the multifd sent device state until all of that earlier data finishes loading first.

Ah I remembered some more now, thanks.

If vfio can send data during iterations this new hook will also not be needed, right?

Quoted 8 lines
Quoted 2 lines

I remember you mentioned you'd have a look and see the challenges there, is there any conclusion yet on whether we can use multifd even during that?

Yeah, I looked at that and it wasn't a straightforward thing to introduce.

I am worried that with all the things that already piled up (including the new thread pool implementation) we risk missing QEMU 9.2 too if this is included.

Not explicitly required, but IMHO it'll be nice to provide a paragraph in the new version when repost explaining the challenges of using it during iterations. It'll be not only for me but for whoever may want to extend your solution to iterations.

I asked this question again mostly because I found that when with iteration support the design looks simpler in begin(), so that the extra sync is not needed. But I confess you know better than me, so whatever you think best is ok here.

Quoted 11 lines
Quoted 8 lines

It's also a pity that we introduce this hook only because we want a boundary between "iterable stage" and "final stage". IIUC if we have any kind of message telling dest before hand that "we're going to the last stage" then this hook can be avoided. Now it's at least inefficient because we need to trigger begin() per-device, even if I think it's more of a global request saying that "we need to load all main stream data first before moving on".

It should be pretty easy to remove that begin() hook once it is no longer needed - after all, it's only necessary for the sender.

Do you mean you have plan to remove the begin() hook even without making interate() work too? That's definitely nice if so.

Quoted 21 lines
Quoted 6 lines
Quoted 6 lines

We shouldn't send that boundary marker in .save_live_complete_precopy either since it would meant unnecessary waiting for other devices (not necessary VFIO ones) .save_live_complete_precopy bulk data.

Quoted 6 lines
Quoted 2 lines

And VFIO SaveVMHandlers are shared for all VFIO devices (and const) so we can't really change them at runtime.

In all cases, please consider dropping end() if it's never used; IMO it's fine if there is only begin(), and we shouldn't keep hooks that are never used.

Okay, will remove the end() hook then.

Quoted 2 lines

Thanks,

Thanks,
Maciej

Signature · 1 line
Peter Xu
#35 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

Quoted 108 lines · Peter Xu
Quoted 107 lines · Maciej S. Szmigiero
Quoted 96 lines · Peter Xu
Quoted 90 lines · Maciej S. Szmigiero
Quoted 81 lines · Peter Xu
Quoted 60 lines · Avihai Horon
Quoted 58 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
     include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
     migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
     2 files changed, 71 insertions(+)
include/migration/register.h +30 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
          */
         int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 5 lines
include/migration/register.h +5 -0
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Right, I spot the same thing.

This series added three hooks: begin, end, precopy_thread.

What I think is it only needs one, which is precopy_async. My vague memory was that was what we used to discuss too, so that when migration precopy flushes the final round of iterable data, it does:

(1) loop over all complete_precopy_async() and enqueue the tasks if existed into the migration worker pool. Then,

Quoted 7 lines

(2) loop over all complete_precopy() like before.

Optionally, we can enforce one vmstate handler only provides either complete_precopy_async() or complete_precopy(). In this case VFIO can update the two hooks during setup() by detecting multifd && !mapped_ram && nocomp.

Quoted 4 lines

The "_begin" hook is still necessary to mark the end of the device state sent via the main migration stream (during the phase VM is still running) since we can't start loading the multifd sent device state until all of that earlier data finishes loading first.

Quoted 7 lines

Ah I remembered some more now, thanks.

If vfio can send data during iterations this new hook will also not be needed, right?

I remember you mentioned you'd have a look and see the challenges there, is there any conclusion yet on whether we can use multifd even during that?

Yeah, I looked at that and it wasn't a straightforward thing to introduce.

Quoted 8 lines
Quoted 3 lines

I am worried that with all the things that already piled up (including the new thread pool implementation) we risk missing QEMU 9.2 too if this is included.

Not explicitly required, but IMHO it'll be nice to provide a paragraph in the new version when repost explaining the challenges of using it during iterations. It'll be not only for me but for whoever may want to extend your solution to iterations.

Will do.

Quoted 4 lines

I asked this question again mostly because I found that when with iteration support the design looks simpler in begin(), so that the extra sync is not needed. But I confess you know better than me, so whatever you think best is ok here.

If we do the MIG_CMD_SWITCHOVER / QEMU_VM_COMMAND thing common for all devices then we don't need begin() even without live-phase multifd device state transfer.

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines

It's also a pity that we introduce this hook only because we want a boundary between "iterable stage" and "final stage". IIUC if we have any kind of message telling dest before hand that "we're going to the last stage" then this hook can be avoided. Now it's at least inefficient because we need to trigger begin() per-device, even if I think it's more of a global request saying that "we need to load all main stream data first before moving on".

Quoted 5 lines
Quoted 2 lines

It should be pretty easy to remove that begin() hook once it is no longer needed - after all, it's only necessary for the sender.

Do you mean you have plan to remove the begin() hook even without making interate() work too? That's definitely nice if so.

As I wrote above, I think with MIG_CMD_SWITCHOVER it shouldn't be needed?

Thanks,
Maciej

#36 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

Quoted 138 lines · Maciej S. Szmigiero
Quoted 108 lines · Peter Xu
Quoted 107 lines · Maciej S. Szmigiero
Quoted 96 lines · Peter Xu
Quoted 90 lines · Maciej S. Szmigiero
Quoted 81 lines · Peter Xu
Quoted 60 lines · Avihai Horon
Quoted 58 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
     include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++
     migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++
     2 files changed, 71 insertions(+)
include/migration/register.h +30 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
          */
         int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 5 lines
include/migration/register.h +5 -0
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

Right, I spot the same thing.

This series added three hooks: begin, end, precopy_thread.

What I think is it only needs one, which is precopy_async. My vague memory was that was what we used to discuss too, so that when migration precopy flushes the final round of iterable data, it does:

(1) loop over all complete_precopy_async() and enqueue the tasks if existed into the migration worker pool. Then,

Quoted 7 lines

(2) loop over all complete_precopy() like before.

Optionally, we can enforce one vmstate handler only provides either complete_precopy_async() or complete_precopy(). In this case VFIO can update the two hooks during setup() by detecting multifd && !mapped_ram && nocomp.

Quoted 4 lines

The "_begin" hook is still necessary to mark the end of the device state sent via the main migration stream (during the phase VM is still running) since we can't start loading the multifd sent device state until all of that earlier data finishes loading first.

Quoted 7 lines

Ah I remembered some more now, thanks.

If vfio can send data during iterations this new hook will also not be needed, right?

I remember you mentioned you'd have a look and see the challenges there, is there any conclusion yet on whether we can use multifd even during that?

Yeah, I looked at that and it wasn't a straightforward thing to introduce.

Quoted 8 lines
Quoted 3 lines

I am worried that with all the things that already piled up (including the new thread pool implementation) we risk missing QEMU 9.2 too if this is included.

Not explicitly required, but IMHO it'll be nice to provide a paragraph in the new version when repost explaining the challenges of using it during iterations. It'll be not only for me but for whoever may want to extend your solution to iterations.

Will do.

Quoted 4 lines

I asked this question again mostly because I found that when with iteration support the design looks simpler in begin(), so that the extra sync is not needed. But I confess you know better than me, so whatever you think best is ok here.

If we do the MIG_CMD_SWITCHOVER / QEMU_VM_COMMAND thing common for all devices then we don't need begin() even without live-phase multifd device state transfer.

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines

It's also a pity that we introduce this hook only because we want a boundary between "iterable stage" and "final stage". IIUC if we have any kind of message telling dest before hand that "we're going to the last stage" then this hook can be avoided. Now it's at least inefficient because we need to trigger begin() per-device, even if I think it's more of a global request saying that "we need to load all main stream data first before moving on".

Quoted 7 lines
Quoted 5 lines
Quoted 2 lines

It should be pretty easy to remove that begin() hook once it is no longer needed - after all, it's only necessary for the sender.

Do you mean you have plan to remove the begin() hook even without making interate() work too? That's definitely nice if so.

As I wrote above, I think with MIG_CMD_SWITCHOVER it shouldn't be needed?

Ah I see, yes if with that it's ok.

Just a heads-up - please remember to add one migration_properties[] entry and a compat property for pre-9.1 so that we don't generate that message when migrating to old binaries.

Meanwhile if we're going to add it, let's also make sure postcopy also has it, as it shares the same SWITCHOVER idea.

Thanks,

Signature · 1 line
Peter Xu
#37 lore raw

Re: [PATCH v2 06/17] migration: Add save_live_complete_precopy_{begin,end} handlers

In reply to Avihai Horon
Quoted 59 lines · Avihai Horon
Quoted 57 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

These SaveVMHandlers help device provide its own asynchronous transmission of the remaining data at the end of a precopy phase.

In this use case the save_live_complete_precopy_begin handler might be used to mark the stream boundary before proceeding with asynchronous transmission of the remaining data while the save_live_complete_precopy_end handler might be used to mark the stream boundary after performing the asynchronous transmission.

---
  include/migration/register.h | 36 ++++++++++++++++++++++++++++++++++++ migration/savevm.c           | 35 +++++++++++++++++++++++++++++++++++

  2 files changed, 71 insertions(+)
include/migration/register.h +29 -0
index f60e797894e5..9de123252edf 100644
@@ -103,6 +103,42 @@ typedef struct SaveVMHandlers {
        */
       int (*save_live_complete_precopy)(QEMUFile *f, void *opaque);
 
+    /**
+     * @save_live_complete_precopy_begin
+     *
+     * Called at the end of a precopy phase, before all
+     * @save_live_complete_precopy handlers and before launching
+     * all @save_live_complete_precopy_thread threads.
+     * The handler might, for example, mark the stream boundary before
+     * proceeding with asynchronous transmission of the remaining data via
+     * @save_live_complete_precopy_thread.
+     * When postcopy is enabled, devices that support postcopy will skip this step.
+     *
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @idstr: this device section idstr
+     * @instance_id: this device section instance_id
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_begin)(QEMUFile *f,
+                                            char *idstr, uint32_t instance_id,
+                                            void *opaque);
+    /**
+     * @save_live_complete_precopy_end
+     *
+     * Called at the end of a precopy phase, after @save_live_complete_precopy
+     * handlers and after all @save_live_complete_precopy_thread threads have
+     * finished. When postcopy is enabled, devices that support postcopy will
+     * skip this step.
+     *
Quoted 8 lines

include/migration/register.h typedef struct SaveVMHandlers { · line 140

Quoted 6 lines
include/migration/register.h +6 -0
+     * @f: QEMUFile where the handler can synchronously send data before returning
+     * @opaque: data pointer passed to register_savevm_live()
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*save_live_complete_precopy_end)(QEMUFile *f, void *opaque);

Is this handler necessary now that migration core is responsible for the threads and joins them? I don't see VFIO implementing it later on.

It's not 100% necessary for the current implementation but preserved for future usage and code consistency with the "_begin" handler (which IS necessary).

Quoted 1 line

Thanks.

Thanks,
Maciej

#38 lore raw

PATCH v2 7/17 migration: Add qemu_loadvm_load_state_buffer() and its handler

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

qemu_loadvm_load_state_buffer() and its load_state_buffer SaveVMHandler allow providing device state buffer to explicitly specified device via its idstr and instance id.

---
 include/migration/register.h | 15 +++++++++++++++
 migration/savevm.c           | 25 +++++++++++++++++++++++++
 migration/savevm.h           |  3 +++
 3 files changed, 43 insertions(+)
include/migration/register.h +15 -0
index 9de123252edf..4a578f140713 100644
@@ -263,6 +263,21 @@ typedef struct SaveVMHandlers {
      */
     int (*load_state)(QEMUFile *f, void *opaque, int version_id);
 
+    /**
+     * @load_state_buffer
+     *
+     * Load device state buffer provided to qemu_loadvm_load_state_buffer().
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @data: the data buffer to load
+     * @data_size: the data length in buffer
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
+                             Error **errp);
+
     /**
      * @load_setup
      *
migration/savevm.c +25 -0
index d43acbbf20cf..3fde5ca8c26b 100644
@@ -3101,6 +3101,31 @@ int qemu_loadvm_approve_switchover(void)
     return migrate_send_rp_switchover_ack(mis);
 }
 
+int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
+                                  char *buf, size_t len, Error **errp)
+{
+    SaveStateEntry *se;
+
+    se = find_se(idstr, instance_id);
+    if (!se) {
+        error_setg(errp, "Unknown idstr %s or instance id %u for load state buffer",
+                   idstr, instance_id);
+        return -1;
+    }
+
+    if (!se->ops || !se->ops->load_state_buffer) {
+        error_setg(errp, "idstr %s / instance %u has no load state buffer operation",
+                   idstr, instance_id);
+        return -1;
+    }
+
+    if (se->ops->load_state_buffer(se->opaque, buf, len, errp) != 0) {
+        return -1;
+    }
+
+    return 0;
+}
+
 bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
                   bool has_devices, strList *devices, Error **errp)
 {
migration/savevm.h +3 -0
index 9ec96a995c93..d388f1bfca98 100644
@@ -70,4 +70,7 @@ int qemu_loadvm_approve_switchover(void);
 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
         bool in_postcopy, bool inactivate_disks);
 
+int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
+                                  char *buf, size_t len, Error **errp);
+
 #endif
Reviewed-by on v2 7/17
#39 lore raw

Re: [PATCH v2 07/17] migration: Add qemu_loadvm_load_state_buffer() and its handler

Quoted 7 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

qemu_loadvm_load_state_buffer() and its load_state_buffer SaveVMHandler allow providing device state buffer to explicitly specified device via its idstr and instance id.

#40 lore raw

Re: [PATCH v2 07/17] migration: Add qemu_loadvm_load_state_buffer() and its handler

In reply to Maciej S. Szmigiero
Quoted 28 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

qemu_loadvm_load_state_buffer() and its load_state_buffer SaveVMHandler allow providing device state buffer to explicitly specified device via its idstr and instance id.

---
  include/migration/register.h | 15 +++++++++++++++
  migration/savevm.c           | 25 +++++++++++++++++++++++++
  migration/savevm.h           |  3 +++
  3 files changed, 43 insertions(+)
include/migration/register.h +4 -0
index 9de123252edf..4a578f140713 100644
@@ -263,6 +263,21 @@ typedef struct SaveVMHandlers {
       */
      int (*load_state)(QEMUFile *f, void *opaque, int version_id);
 
+    /**
+     * @load_state_buffer
+     *
+     * Load device state buffer provided to qemu_loadvm_load_state_buffer().

include/migration/register.h typedef struct SaveVMHandlers { · line 279

Quoted 10 lines
include/migration/register.h +10 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @data: the data buffer to load
+     * @data_size: the data length in buffer
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
+                             Error **errp);

Nit: Maybe rename data to buf and data_size to len to be consistent with qemu_loadvm_load_state_buffer()?

Quoted 25 lines
include/migration/register.h +1 -0
+
      /**
       * @load_setup
       *
migration/savevm.c +13 -0
index d43acbbf20cf..3fde5ca8c26b 100644
@@ -3101,6 +3101,31 @@ int qemu_loadvm_approve_switchover(void)
      return migrate_send_rp_switchover_ack(mis);
  }
 
+int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
+                                  char *buf, size_t len, Error **errp)
+{
+    SaveStateEntry *se;
+
+    se = find_se(idstr, instance_id);
+    if (!se) {
+        error_setg(errp, "Unknown idstr %s or instance id %u for load state buffer",
+                   idstr, instance_id);
+        return -1;
+    }
+
+    if (!se->ops || !se->ops->load_state_buffer) {

migration/savevm.c int qemu_loadvm_approve_switchover(void) · line 3126

Quoted 10 lines
migration/savevm.c +10 -0
+        error_setg(errp, "idstr %s / instance %u has no load state buffer operation",
+                   idstr, instance_id);
+        return -1;
+    }
+
+    if (se->ops->load_state_buffer(se->opaque, buf, len, errp) != 0) {
+        return -1;
+    }
+
+    return 0;

Nit: this can be simplified to:
return se->ops->load_state_buffer(se->opaque, buf, len, errp);

Thanks.

Quoted 17 lines
migration/savevm.c +2 -0
+}
+
  bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
                    bool has_devices, strList *devices, Error **errp)
  {
migration/savevm.h +3 -0
index 9ec96a995c93..d388f1bfca98 100644
@@ -70,4 +70,7 @@ int qemu_loadvm_approve_switchover(void);
  int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
          bool in_postcopy, bool inactivate_disks);
 
+int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
+                                  char *buf, size_t len, Error **errp);
+
  #endif
#41 lore raw

Re: [PATCH v2 07/17] migration: Add qemu_loadvm_load_state_buffer() and its handler

Quoted 26 lines · Avihai Horon
Quoted 24 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

qemu_loadvm_load_state_buffer() and its load_state_buffer SaveVMHandler allow providing device state buffer to explicitly specified device via its idstr and instance id.

---
  include/migration/register.h | 15 +++++++++++++++ migration/savevm.c           | 25 +++++++++++++++++++++++++ migration/savevm.h           |  3 +++

  3 files changed, 43 insertions(+)
include/migration/register.h +0 -0
index 9de123252edf..4a578f140713 100644
@@ -263,6 +263,21 @@ typedef struct SaveVMHandlers {
        */
       int (*load_state)(QEMUFile *f, void *opaque, int version_id);
 
Quoted 16 lines
Quoted 4 lines
include/migration/register.h +4 -0
+    /**
+     * @load_state_buffer
+     *
+     * Load device state buffer provided to qemu_loadvm_load_state_buffer().

include/migration/register.h typedef struct SaveVMHandlers { · line 279

Quoted 10 lines
include/migration/register.h +10 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @data: the data buffer to load
+     * @data_size: the data length in buffer
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     */
+    int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
+                             Error **errp);

Nit: Maybe rename data to buf and data_size to len to be consistent with qemu_loadvm_load_state_buffer()?

Will do.

Quoted 30 lines
Quoted 30 lines
include/migration/register.h +1 -0
+
       /**
        * @load_setup
        *
migration/savevm.c +18 -0
index d43acbbf20cf..3fde5ca8c26b 100644
@@ -3101,6 +3101,31 @@ int qemu_loadvm_approve_switchover(void)
       return migrate_send_rp_switchover_ack(mis);
   }
 
+int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
+                                  char *buf, size_t len, Error **errp)
+{
+    SaveStateEntry *se;
+
+    se = find_se(idstr, instance_id);
+    if (!se) {
+        error_setg(errp, "Unknown idstr %s or instance id %u for load state buffer",
+                   idstr, instance_id);
+        return -1;
+    }
+
+    if (!se->ops || !se->ops->load_state_buffer) {
+        error_setg(errp, "idstr %s / instance %u has no load state buffer operation",
+                   idstr, instance_id);
+        return -1;
+    }
+
Quoted 8 lines

migration/savevm.c int qemu_loadvm_approve_switchover(void) · line 3126

Quoted 5 lines
migration/savevm.c +5 -0
+    if (se->ops->load_state_buffer(se->opaque, buf, len, errp) != 0) {
+        return -1;
+    }
+
+    return 0;

Nit: this can be simplified to:
return se->ops->load_state_buffer(se->opaque, buf, len, errp);

You're right - will change it so.

Quoted 1 line

Thanks.

Thanks,
Maciej

#42 lore raw

PATCH v2 8/17 migration: Add load_finish handler and associated functions

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
 include/migration/register.h | 21 +++++++++++++++
 migration/migration.c        |  6 +++++
 migration/migration.h        |  3 +++
 migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
 migration/savevm.h           |  4 +++
 5 files changed, 86 insertions(+)
include/migration/register.h +21 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
     int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                              Error **errp);
 
+    /**
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
+
     /**
      * @load_setup
      *
migration/migration.c +6 -0
index 3dea06d57732..d61e7b055e07 100644
@@ -259,6 +259,9 @@ void migration_object_init(void)
 
     current_incoming->exit_on_error = INMIGRATE_DEFAULT_EXIT_ON_ERROR;
 
+    qemu_mutex_init(&current_incoming->load_finish_ready_mutex);
+    qemu_cond_init(&current_incoming->load_finish_ready_cond);
+
     migration_object_check(current_migration, &error_fatal);
 
     ram_mig_init();
@@ -410,6 +413,9 @@ void migration_incoming_state_destroy(void)
         mis->postcopy_qemufile_dst = NULL;
     }
 
+    qemu_mutex_destroy(&mis->load_finish_ready_mutex);
+    qemu_cond_destroy(&mis->load_finish_ready_cond);
+
     yank_unregister_instance(MIGRATION_YANK_INSTANCE);
 }
 
migration/migration.h +3 -0
index 38aa1402d516..4e2443e6c8ec 100644
@@ -230,6 +230,9 @@ struct MigrationIncomingState {
 
     /* Do exit on incoming migration failure */
     bool exit_on_error;
+
+    QemuCond load_finish_ready_cond;
+    QemuMutex load_finish_ready_mutex;
 };
 
 MigrationIncomingState *migration_incoming_get_current(void);
migration/savevm.c +52 -0

64 lines not on this page · raw message

migration/savevm.h +4 -0
index d388f1bfca98..69ae22cded7a 100644
@@ -73,4 +73,8 @@ int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
 int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
                                   char *buf, size_t len, Error **errp);
 
+void qemu_loadvm_load_finish_ready_lock(void);
+void qemu_loadvm_load_finish_ready_unlock(void);
+void qemu_loadvm_load_finish_ready_broadcast(void);
+
 #endif
Reviewed-by on v2 8/17
#43 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 80 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
 include/migration/register.h | 21 +++++++++++++++
 migration/migration.c        |  6 +++++
 migration/migration.h        |  3 +++
 migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
 migration/savevm.h           |  4 +++
 5 files changed, 86 insertions(+)
include/migration/register.h +21 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
     int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                              Error **errp);
 
+    /**
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
+
     /**
      * @load_setup
      *
migration/migration.c +6 -0
index 3dea06d57732..d61e7b055e07 100644
@@ -259,6 +259,9 @@ void migration_object_init(void)
 
     current_incoming->exit_on_error = INMIGRATE_DEFAULT_EXIT_ON_ERROR;
 
+    qemu_mutex_init(&current_incoming->load_finish_ready_mutex);
+    qemu_cond_init(&current_incoming->load_finish_ready_cond);
+
     migration_object_check(current_migration, &error_fatal);
 
     ram_mig_init();
@@ -410,6 +413,9 @@ void migration_incoming_state_destroy(void)
         mis->postcopy_qemufile_dst = NULL;
     }
 
+    qemu_mutex_destroy(&mis->load_finish_ready_mutex);
+    qemu_cond_destroy(&mis->load_finish_ready_cond);
+
     yank_unregister_instance(MIGRATION_YANK_INSTANCE);
 }
 
migration/migration.h +0 -0
index 38aa1402d516..4e2443e6c8ec 100644

migration/migration.h struct MigrationIncomingState { · line 235

Quoted 6 lines
migration/migration.h +3 -0
@@ -230,6 +230,9 @@ struct MigrationIncomingState {
 
     /* Do exit on incoming migration failure */
     bool exit_on_error;
+
+    QemuCond load_finish_ready_cond;
+    QemuMutex load_finish_ready_mutex;

With these moved to MigrationState:

#44 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

In reply to Maciej S. Szmigiero
Quoted 97 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
  include/migration/register.h | 21 +++++++++++++++
  migration/migration.c        |  6 +++++
  migration/migration.h        |  3 +++
  migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
  migration/savevm.h           |  4 +++
  5 files changed, 86 insertions(+)
include/migration/register.h +21 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
      int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                               Error **errp);
 
+    /**
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
+
      /**
       * @load_setup
       *
migration/migration.c +6 -0
index 3dea06d57732..d61e7b055e07 100644
@@ -259,6 +259,9 @@ void migration_object_init(void)
 
      current_incoming->exit_on_error = INMIGRATE_DEFAULT_EXIT_ON_ERROR;
 
+    qemu_mutex_init(&current_incoming->load_finish_ready_mutex);
+    qemu_cond_init(&current_incoming->load_finish_ready_cond);
+
      migration_object_check(current_migration, &error_fatal);
 
      ram_mig_init();
@@ -410,6 +413,9 @@ void migration_incoming_state_destroy(void)
          mis->postcopy_qemufile_dst = NULL;
      }
 
+    qemu_mutex_destroy(&mis->load_finish_ready_mutex);
+    qemu_cond_destroy(&mis->load_finish_ready_cond);
+
      yank_unregister_instance(MIGRATION_YANK_INSTANCE);
  }
 
migration/migration.h +3 -0
index 38aa1402d516..4e2443e6c8ec 100644
@@ -230,6 +230,9 @@ struct MigrationIncomingState {
 
      /* Do exit on incoming migration failure */
      bool exit_on_error;
+
+    QemuCond load_finish_ready_cond;
+    QemuMutex load_finish_ready_mutex;
  };
 
  MigrationIncomingState *migration_incoming_get_current(void);
migration/savevm.c +0 -0
index 3fde5ca8c26b..33c9200d1e78 100644

migration/savevm.c int qemu_loadvm_state(QEMUFile *f) · line 3027

Quoted 6 lines
migration/savevm.c +3 -0
@@ -3022,6 +3022,37 @@ int qemu_loadvm_state(QEMUFile *f)
          return ret;
      }
 
+    qemu_loadvm_load_finish_ready_lock();
+    while (!ret) { /* Don't call load_finish() handlers on the load failure path */
+        bool all_ready = true;

Nit: Maybe rename all_ready to all_finished to be consistent with load_finish() terminology? Same for this_ready.

Quoted 44 lines
migration/savevm.c +37 -0
+        SaveStateEntry *se = NULL;
+
+        QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
+            bool this_ready;
+
+            if (!se->ops || !se->ops->load_finish) {
+                continue;
+            }
+
+            ret = se->ops->load_finish(se->opaque, &this_ready, &local_err);
+            if (ret) {
+                error_report_err(local_err);
+
+                qemu_loadvm_load_finish_ready_unlock();
+                return -EINVAL;
+            } else if (!this_ready) {
+                all_ready = false;
+            }
+        }
+
+        if (all_ready) {
+            break;
+        }
+
+        qemu_cond_wait(&mis->load_finish_ready_cond, &mis->load_finish_ready_mutex);
+    }
+    qemu_loadvm_load_finish_ready_unlock();
+
      if (ret == 0) {
          ret = qemu_file_get_error(f);
      }
@@ -3126,6 +3157,27 @@ int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
      return 0;
  }
 
+void qemu_loadvm_load_finish_ready_lock(void)
+{
+    MigrationIncomingState *mis = migration_incoming_get_current();
+
+    qemu_mutex_lock(&mis->load_finish_ready_mutex);
+}
+
+void qemu_loadvm_load_finish_ready_unlock(void)
+{

migration/savevm.c int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id, · line 3178

Quoted 10 lines
migration/savevm.c +10 -0
+    MigrationIncomingState *mis = migration_incoming_get_current();
+
+    qemu_mutex_unlock(&mis->load_finish_ready_mutex);
+}
+
+void qemu_loadvm_load_finish_ready_broadcast(void)
+{
+    MigrationIncomingState *mis = migration_incoming_get_current();
+
+    qemu_cond_broadcast(&mis->load_finish_ready_cond);

Do we need a broadcast? isn't signal enough as we only have one waiter thread?

Thanks.

Quoted 18 lines
migration/savevm.c +2 -0
+}
+
  bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
                    bool has_devices, strList *devices, Error **errp)
  {
migration/savevm.h +4 -0
index d388f1bfca98..69ae22cded7a 100644
@@ -73,4 +73,8 @@ int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
  int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
                                    char *buf, size_t len, Error **errp);
 
+void qemu_loadvm_load_finish_ready_lock(void);
+void qemu_loadvm_load_finish_ready_unlock(void);
+void qemu_loadvm_load_finish_ready_broadcast(void);
+
  #endif
#45 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 102 lines · Avihai Horon
Quoted 100 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
  include/migration/register.h | 21 +++++++++++++++ migration/migration.c        |  6 +++++ migration/migration.h        |  3 +++
  migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++ migration/savevm.h           |  4 +++

  5 files changed, 86 insertions(+)
include/migration/register.h +21 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
       int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                Error **errp);
 
+    /**
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
+
       /**
        * @load_setup
        *
migration/migration.c +6 -0
index 3dea06d57732..d61e7b055e07 100644
@@ -259,6 +259,9 @@ void migration_object_init(void)
 
       current_incoming->exit_on_error = INMIGRATE_DEFAULT_EXIT_ON_ERROR;
 
+    qemu_mutex_init(&current_incoming->load_finish_ready_mutex);
+    qemu_cond_init(&current_incoming->load_finish_ready_cond);
+
       migration_object_check(current_migration, &error_fatal);
 
       ram_mig_init();
@@ -410,6 +413,9 @@ void migration_incoming_state_destroy(void)
           mis->postcopy_qemufile_dst = NULL;
       }
 
+    qemu_mutex_destroy(&mis->load_finish_ready_mutex);
+    qemu_cond_destroy(&mis->load_finish_ready_cond);
+
       yank_unregister_instance(MIGRATION_YANK_INSTANCE);
   }
 
migration/migration.h +3 -0
index 38aa1402d516..4e2443e6c8ec 100644
@@ -230,6 +230,9 @@ struct MigrationIncomingState {
 
       /* Do exit on incoming migration failure */
       bool exit_on_error;
+
+    QemuCond load_finish_ready_cond;
+    QemuMutex load_finish_ready_mutex;
   };
 
   MigrationIncomingState *migration_incoming_get_current(void);
migration/savevm.c +0 -0
index 3fde5ca8c26b..33c9200d1e78 100644
@@ -3022,6 +3022,37 @@ int qemu_loadvm_state(QEMUFile *f)
           return ret;
       }
 
Quoted 5 lines

migration/savevm.c int qemu_loadvm_state(QEMUFile *f) · line 3027

Quoted 3 lines
migration/savevm.c +3 -0
+    qemu_loadvm_load_finish_ready_lock();
+    while (!ret) { /* Don't call load_finish() handlers on the load failure path */
+        bool all_ready = true;

Nit: Maybe rename all_ready to all_finished to be consistent with load_finish() terminology? Same for this_ready.

Will rename it accordingly.

Quoted 48 lines
Quoted 48 lines
migration/savevm.c +41 -0
+        SaveStateEntry *se = NULL;
+
+        QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
+            bool this_ready;
+
+            if (!se->ops || !se->ops->load_finish) {
+                continue;
+            }
+
+            ret = se->ops->load_finish(se->opaque, &this_ready, &local_err);
+            if (ret) {
+                error_report_err(local_err);
+
+                qemu_loadvm_load_finish_ready_unlock();
+                return -EINVAL;
+            } else if (!this_ready) {
+                all_ready = false;
+            }
+        }
+
+        if (all_ready) {
+            break;
+        }
+
+        qemu_cond_wait(&mis->load_finish_ready_cond, &mis->load_finish_ready_mutex);
+    }
+    qemu_loadvm_load_finish_ready_unlock();
+
       if (ret == 0) {
           ret = qemu_file_get_error(f);
       }
@@ -3126,6 +3157,27 @@ int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
       return 0;
   }
 
+void qemu_loadvm_load_finish_ready_lock(void)
+{
+    MigrationIncomingState *mis = migration_incoming_get_current();
+
+    qemu_mutex_lock(&mis->load_finish_ready_mutex);
+}
+
+void qemu_loadvm_load_finish_ready_unlock(void)
+{
+    MigrationIncomingState *mis = migration_incoming_get_current();
+
+    qemu_mutex_unlock(&mis->load_finish_ready_mutex);
+}
Quoted 8 lines

migration/savevm.c int qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id, · line 3178

Quoted 6 lines
migration/savevm.c +6 -0
+
+void qemu_loadvm_load_finish_ready_broadcast(void)
+{
+    MigrationIncomingState *mis = migration_incoming_get_current();
+
+    qemu_cond_broadcast(&mis->load_finish_ready_cond);

Do we need a broadcast? isn't signal enough as we only have one waiter thread?

Currently, there's just one waiter but looking at the relatively small implementation difference between pthread_cond_signal() and pthread_cond_broadcast() I'm not sure whether it is worth changing it it to _signal() and not having a possibility of signalling multiple waiters upfront.

Quoted 1 line

Thanks.

Thanks,
Maciej

#46 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

In reply to Maciej S. Szmigiero
Quoted 28 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
 include/migration/register.h | 21 +++++++++++++++
 migration/migration.c        |  6 +++++
 migration/migration.h        |  3 +++
 migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
 migration/savevm.h           |  4 +++
 5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
     int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                              Error **errp);
 
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 291

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 300

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads, then after everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

    if (migrate_switchover_ack()) {
        qemu_loadvm_state_switchover_ack_needed(mis);
    }

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Signature · 1 line
Peter Xu
#47 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 52 lines · Peter Xu
Quoted 28 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
  include/migration/register.h | 21 +++++++++++++++
  migration/migration.c        |  6 +++++
  migration/migration.h        |  3 +++
  migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
  migration/savevm.h           |  4 +++
  5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
      int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                               Error **errp);
 
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 291

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 300

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Quoted 8 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

     if (migrate_switchover_ack()) {
         qemu_loadvm_state_switchover_ack_needed(mis);
     }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Thanks,
Maciej

#48 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 59 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
  include/migration/register.h | 21 +++++++++++++++
  migration/migration.c        |  6 +++++
  migration/migration.h        |  3 +++
  migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
  migration/savevm.h           |  4 +++
  5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
      int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                               Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 300

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 7 lines
Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states? And just curious: how large is it normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

     if (migrate_switchover_ack()) {
         qemu_loadvm_state_switchover_ack_needed(mis);
     }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

So IMHO this recv side interface so far is the major pain that I really want to avoid (comparing to the rest) in the series. Let's see whether we can come up with something better..

One other (probably not pretty..) idea is when waiting here in the main thread it yields BQL, then other threads can take it and load the VFIO final chunk of data. But I could miss something else.

Signature · 1 line
Peter Xu
#49 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
   include/migration/register.h | 21 +++++++++++++++
   migration/migration.c        |  6 +++++
   migration/migration.h        |  3 +++
   migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
   migration/savevm.h           |  4 +++
   5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
       int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 300

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

      if (migrate_switchover_ack()) {
          qemu_loadvm_state_switchover_ack_needed(mis);
      }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

Quoted 8 lines

So IMHO this recv side interface so far is the major pain that I really want to avoid (comparing to the rest) in the series. Let's see whether we can come up with something better..

One other (probably not pretty..) idea is when waiting here in the main thread it yields BQL, then other threads can take it and load the VFIO final chunk of data. But I could miss something else.

I think temporary dropping BQL deep inside migration code is similar to running QEMU event loop deep inside migration code (about which people complained in my generic thread pool implementation): it's easy to miss some subtle dependency/race somewhere and accidentally cause rare hard to debug deadlock.

That's why I think that it's ultimately probably better to make QEMU core address space modification methods thread safe / re-entrant instead.

Thanks,
Maciej

#50 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 121 lines · Maciej S. Szmigiero
Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
   include/migration/register.h | 21 +++++++++++++++
   migration/migration.c        |  6 +++++
   migration/migration.h        |  3 +++
   migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
   migration/savevm.h           |  4 +++
   5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
       int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 300

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

      if (migrate_switchover_ack()) {
          qemu_loadvm_state_switchover_ack_needed(mis);
      }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Quoted 7 lines

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

This sounds like a performance concern, and I wonder how much this impacts the real workload (that you run a test and measure, with/without such concurrency) when we can save two devices in parallel anyway; I would expect the real diff is small due to the fact I mentioned that we save >1 VFIO devices concurrently via multifd.

Do you think we can start with a simpler approach?

So what I'm thinking could be very clean is, we just discussed about MIG_CMD_SWITCHOVER and looks like you also think it's an OK approach. I wonder when with it why not we move one step further to have MIG_CMD_SEND_NON_ITERABE just to mark that "iterable devices all done, ready to send non-iterable". It can be controlled by the same migration property so we only send these two flags in 9.2+ machine types.

Then IIUC VFIO can send config data through main wire (just like most of other pci devices! which is IMHO a good fit..) and on destination VFIO holds off loading them until passing the MIG_CMD_SEND_NON_ITERABE phase.

Side note: when looking again, I really think we should cleanup some migration switchover phase functions, e.g. I think qemu_savevm_state_complete_precopy() parameters are pretty confusing, especially iterable_only, even if inside it it also have some postcopy implicit checks, urgh.. but this is not relevant to our discussion, and I won't draft that before your series land; that can complicate stuff.

Quoted 10 lines
Quoted 9 lines

So IMHO this recv side interface so far is the major pain that I really want to avoid (comparing to the rest) in the series. Let's see whether we can come up with something better..

One other (probably not pretty..) idea is when waiting here in the main thread it yields BQL, then other threads can take it and load the VFIO final chunk of data. But I could miss something else.

Quoted 8 lines

I think temporary dropping BQL deep inside migration code is similar to running QEMU event loop deep inside migration code (about which people complained in my generic thread pool implementation): it's easy to miss some subtle dependency/race somewhere and accidentally cause rare hard to debug deadlock.

That's why I think that it's ultimately probably better to make QEMU core address space modification methods thread safe / re-entrant instead.

Right, let's see how you think about above.

Thanks,

Signature · 1 line
Peter Xu
#51 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 130 lines · Peter Xu
Quoted 121 lines · Maciej S. Szmigiero
Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
    include/migration/register.h | 21 +++++++++++++++
    migration/migration.c        |  6 +++++
    migration/migration.h        |  3 +++
    migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
    migration/savevm.h           |  4 +++
    5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
        int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                 Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 300

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

       if (migrate_switchover_ack()) {
           qemu_loadvm_state_switchover_ack_needed(mis);
       }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Quoted 7 lines

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

Quoted 7 lines

This sounds like a performance concern, and I wonder how much this impacts the real workload (that you run a test and measure, with/without such concurrency) when we can save two devices in parallel anyway; I would expect the real diff is small due to the fact I mentioned that we save >1 VFIO devices concurrently via multifd.

Do you think we can start with a simpler approach?

I don't think introducing a performance/scalability issue like that is a good thing, especially that we already have a design that avoids it.

Unfortunately, my current setup does not allow live migrating VMs with more than 4 VFs so I can't benchmark that.

But I almost certain that with more VFs the situation with devices being ready out-of-order will get even more likely.

Quoted 10 lines

So what I'm thinking could be very clean is, we just discussed about MIG_CMD_SWITCHOVER and looks like you also think it's an OK approach. I wonder when with it why not we move one step further to have MIG_CMD_SEND_NON_ITERABE just to mark that "iterable devices all done, ready to send non-iterable". It can be controlled by the same migration property so we only send these two flags in 9.2+ machine types.

Then IIUC VFIO can send config data through main wire (just like most of other pci devices! which is IMHO a good fit..) and on destination VFIO holds off loading them until passing the MIG_CMD_SEND_NON_ITERABE phase.

Starting the config load only on MIG_CMD_SEND_NON_ITERABE would (in addition to the considerations above) also delay starting the config load until all iterable devices were read/transferred/loaded and also would complicate future efforts at loading that config data in parallel.

Quoted 3 lines

Thanks,

Thanks,
Maciej

#52 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 137 lines · Maciej S. Szmigiero
Quoted 136 lines · Peter Xu
Quoted 121 lines · Maciej S. Szmigiero
Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
    include/migration/register.h | 21 +++++++++++++++
    migration/migration.c        |  6 +++++
    migration/migration.h        |  3 +++
    migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
    migration/savevm.h           |  4 +++
    5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
        int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                 Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 299

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

       if (migrate_switchover_ack()) {
           qemu_loadvm_state_switchover_ack_needed(mis);
       }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Quoted 7 lines

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

This sounds like a performance concern, and I wonder how much this impacts the real workload (that you run a test and measure, with/without such concurrency) when we can save two devices in parallel anyway; I would expect the real diff is small due to the fact I mentioned that we save >1 VFIO devices concurrently via multifd.

Quoted 7 lines
Quoted 1 line

Do you think we can start with a simpler approach?

I don't think introducing a performance/scalability issue like that is a good thing, especially that we already have a design that avoids it.

Unfortunately, my current setup does not allow live migrating VMs with more than 4 VFs so I can't benchmark that.

/me wonders why benchmarking it requires more than 4 VFs.

Quoted 3 lines

But I almost certain that with more VFs the situation with devices being ready out-of-order will get even more likely.

If the config space is small, why loading it in sequence would be a problem?

Have you measured how much time it needs to load one VF's config space that you're using? I suppose that's vfio_load_device_config_state() alone?

Quoted 8 lines
Quoted 8 lines

So what I'm thinking could be very clean is, we just discussed about MIG_CMD_SWITCHOVER and looks like you also think it's an OK approach. I wonder when with it why not we move one step further to have MIG_CMD_SEND_NON_ITERABE just to mark that "iterable devices all done, ready to send non-iterable". It can be controlled by the same migration property so we only send these two flags in 9.2+ machine types.

Quoted 8 lines
Quoted 3 lines

Then IIUC VFIO can send config data through main wire (just like most of other pci devices! which is IMHO a good fit..) and on destination VFIO holds off loading them until passing the MIG_CMD_SEND_NON_ITERABE phase.

Starting the config load only on MIG_CMD_SEND_NON_ITERABE would (in addition to the considerations above) also delay starting the config load until all iterable devices were read/transferred/loaded and also would complicate future efforts at loading that config data in parallel.

However I wonder whether we can keep it simple in that VFIO's config space is still always saved in vfio_save_state(). I still think it's easier we stick with the main channel whenever possible. For this specific case, if the config space is small I think it's tricky you bypass this with:

    if (migration->multifd_transfer) {
        /* Emit dummy NOP data */
        qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
        return;
    }

Then squash this as the tail of the iterable data.

On the src, I think it could use a per-device semaphore, so that iterable save() thread will post() only if it finishes dumping all the data, then that orders VFIO iterable data v.s. config space save().

On the dst, after a 2nd thought, MIG_CMD_SEND_NON_ITERABE may not work or needed indeed, because multifd bypasses the main channel, so if we send anything like MIG_CMD_SEND_NON_ITERABE on the main channel it won't guarantee multifd load all complete. However IIUC that can be used in a similar way as the src qemu I mentioned above with a per-device semaphore, so that only all the iterable data of this device loaded and applied to the HW would it post(), before that, vfio_load_state() should wait() on that sem waiting for data to ready (while multifd threads will be doing that part). I wonder whether we may reuse the multifd recv thread in the initial version, so maybe we don't need any other threads on destination.

The load_finish() interface is currently not able to be reused right, afaict. Just have a look at its definition:

/**
* @load_finish
*
* Poll whether all asynchronous device state loading had finished.
* Not called on the load failure path.
*
* Called while holding the qemu_loadvm_load_finish_ready_lock. *
* If this method signals "not ready" then it might not be called
* again until qemu_loadvm_load_finish_ready_broadcast() is invoked
* while holding qemu_loadvm_load_finish_ready_lock.
*
* @opaque: data pointer passed to register_savevm_live()
* @is_finished: whether the loading had finished (output parameter)
* @errp: pointer to Error*, to store an error if it happens. *
* Returns zero to indicate success and negative for error
* It's not an error that the loading still hasn't finished. */
int (*load_finish)(void *opaque, bool *is_finished, Error **errp);

It's over complicated on defining all its details:

- Not re-entrant by default.. this is so weirdly designed so that the caller needs to know which is even the "1st invocation of the function"... It is just weird.

- Requires one more global mutex that non vmstate handler ever requested, that I feel like perhaps can be replaced by a sem (then to drop the condvar)?

- How qemu_loadvm_load_finish_ready_broadcast() interacts with all

    above..

So if you really think it matters to load whatever VFIO device who's iterable data is ready first, then let's try come up with some better interface.. I can try to think about it too, but please answer me questions above so I can understand what I am missing on why that's important. Numbers could help, even if 4 VF and I wonder how much diff there can be. Mostly, I don't know why it's slow right now if it is; I thought it should be pretty fast, at least not a concern in VFIO migration world (which can take seconds of downtime or more..).

IOW, it sounds more reasonalbe to me that no matter whether vfio will support multifd, it'll be nice we stick with vfio_load_state() / vfio_save_state() for config space, and hopefully it's also easier it always go via the main channel to everyone. In these two hooks, VFIO can do whatever it wants to sync with other things (on src, sync with concurrent thread pool saving iterable data and dumping things to multifd channels; on dst, sync with multifd concurrent loads). I think it can remove the requirement on the load_finish() interface completely. Yes, this can only load VFIO's pci config space one by one, but I think this is much simpler, and I hope it's also not that slow, but I'm not sure.

Thanks,

Signature · 1 line
Peter Xu
#53 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 140 lines · Peter Xu
Quoted 139 lines · Maciej S. Szmigiero
Quoted 137 lines · Peter Xu
Quoted 121 lines · Maciej S. Szmigiero
Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
     include/migration/register.h | 21 +++++++++++++++
     migration/migration.c        |  6 +++++
     migration/migration.h        |  3 +++
     migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
     migration/savevm.h           |  4 +++
     5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
         int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                  Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 299

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

        if (migrate_switchover_ack()) {
            qemu_loadvm_state_switchover_ack_needed(mis);
        }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Quoted 7 lines

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

This sounds like a performance concern, and I wonder how much this impacts the real workload (that you run a test and measure, with/without such concurrency) when we can save two devices in parallel anyway; I would expect the real diff is small due to the fact I mentioned that we save >1 VFIO devices concurrently via multifd.

Do you think we can start with a simpler approach?

Quoted 7 lines
Quoted 5 lines

I don't think introducing a performance/scalability issue like that is a good thing, especially that we already have a design that avoids it.

Unfortunately, my current setup does not allow live migrating VMs with more than 4 VFs so I can't benchmark that.

/me wonders why benchmarking it requires more than 4 VFs.

My point here was that the scalability problem will most likely get more pronounced with more VFs.

Quoted 9 lines
Quoted 3 lines

But I almost certain that with more VFs the situation with devices being ready out-of-order will get even more likely.

If the config space is small, why loading it in sequence would be a problem?

Have you measured how much time it needs to load one VF's config space that you're using? I suppose that's vfio_load_device_config_state() alone?

It's not the amount of data to load matters here but that these address space operations are slow.

The whole config load takes ~70 ms per device - that's time equivalent of transferring 875 MiB of device state via a 100 GBit/s link.

Quoted 28 lines
Quoted 8 lines
Quoted 8 lines

So what I'm thinking could be very clean is, we just discussed about MIG_CMD_SWITCHOVER and looks like you also think it's an OK approach. I wonder when with it why not we move one step further to have MIG_CMD_SEND_NON_ITERABE just to mark that "iterable devices all done, ready to send non-iterable". It can be controlled by the same migration property so we only send these two flags in 9.2+ machine types.

Quoted 8 lines
Quoted 3 lines

Then IIUC VFIO can send config data through main wire (just like most of other pci devices! which is IMHO a good fit..) and on destination VFIO holds off loading them until passing the MIG_CMD_SEND_NON_ITERABE phase.

Starting the config load only on MIG_CMD_SEND_NON_ITERABE would (in addition to the considerations above) also delay starting the config load until all iterable devices were read/transferred/loaded and also would complicate future efforts at loading that config data in parallel.

However I wonder whether we can keep it simple in that VFIO's config space is still always saved in vfio_save_state(). I still think it's easier we stick with the main channel whenever possible. For this specific case, if the config space is small I think it's tricky you bypass this with:

     if (migration->multifd_transfer) {
         /* Emit dummy NOP data */
         qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
         return;
     }
Quoted 5 lines

Then squash this as the tail of the iterable data.

On the src, I think it could use a per-device semaphore, so that iterable save() thread will post() only if it finishes dumping all the data, then that orders VFIO iterable data v.s. config space save().

In the future we want to not only transfer but also load the config data in parallel.

So going back to transferring this data serialized via the main migration channel would be taking a step back here.

By the way, we already have a serialization point in qemu_savevm_state_complete_precopy_iterable() after iterables have been sent - waiting for device state sending threads to finish their work.

Whether this thread_pool_wait() operation will be implemented using semaphores I'm not sure yet - will depend on how well this will fit other GThreadPool internals.

Quoted 35 lines

On the dst, after a 2nd thought, MIG_CMD_SEND_NON_ITERABE may not work or needed indeed, because multifd bypasses the main channel, so if we send anything like MIG_CMD_SEND_NON_ITERABE on the main channel it won't guarantee multifd load all complete. However IIUC that can be used in a similar way as the src qemu I mentioned above with a per-device semaphore, so that only all the iterable data of this device loaded and applied to the HW would it post(), before that, vfio_load_state() should wait() on that sem waiting for data to ready (while multifd threads will be doing that part). I wonder whether we may reuse the multifd recv thread in the initial version, so maybe we don't need any other threads on destination.

The load_finish() interface is currently not able to be reused right, afaict. Just have a look at its definition:

/**
* @load_finish
*
* Poll whether all asynchronous device state loading had finished.
* Not called on the load failure path.
*
* Called while holding the qemu_loadvm_load_finish_ready_lock. *
* If this method signals "not ready" then it might not be called
* again until qemu_loadvm_load_finish_ready_broadcast() is invoked
* while holding qemu_loadvm_load_finish_ready_lock.
*
* @opaque: data pointer passed to register_savevm_live()
* @is_finished: whether the loading had finished (output parameter)
* @errp: pointer to Error*, to store an error if it happens. *
* Returns zero to indicate success and negative for error
* It's not an error that the loading still hasn't finished. */
int (*load_finish)(void *opaque, bool *is_finished, Error **errp);

Quoted 3 lines

It's over complicated on defining all its details:

- Not re-entrant by default..

What do you mean by "re-entrant" here?

This handler is called only from single migration thread, so it cannot be re-entered anyway since the control doesn't return to the migration code until this handler exits (and obviously the handler won't call itself recursively).

Quoted 3 lines

this is so weirdly designed so that the
caller needs to know which is even the "1st invocation of the function"... It is just weird.

I don't quite understand that - why do you think that caller needs to know whether this is the "1st invocation of the function"?

The caller only tracks whether all these handlers reported that they finished their work:

Quoted 16 lines
      bool all_ready = true;
      QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
          bool this_ready;

          ret = se->ops->load_finish(se->opaque, &this_ready, &local_err);
          if (ret) {
          } else if (!this_ready) {
              all_ready = false;
          }

      }
      if (all_ready) {
            break;
      }
Quoted 1 line

- Requires one more global mutex that non vmstate handler ever requested,

Could you elaborate what do you mean by "that non vmstate handler ever requested"?

Quoted 2 lines

that I feel like perhaps can be replaced by a sem (then to drop the condvar)?

Once we have ability to load device config state outside main migration thread replacing "load_finish" handler with a semaphore should indeed be possible (that's internal migration API so there should be no issue removing it as not necessary anymore at this point).

But for now, the devices need to have ability to run their config load code on the main migration thread, and for that they need to be called from this handler "load_finish".

Quoted 12 lines

- How qemu_loadvm_load_finish_ready_broadcast() interacts with all

     above..

So if you really think it matters to load whatever VFIO device who's iterable data is ready first, then let's try come up with some better interface.. I can try to think about it too, but please answer me questions above so I can understand what I am missing on why that's important. Numbers could help, even if 4 VF and I wonder how much diff there can be. Mostly, I don't know why it's slow right now if it is; I thought it should be pretty fast, at least not a concern in VFIO migration world (which can take seconds of downtime or more..).

Quoted 10 lines

IOW, it sounds more reasonalbe to me that no matter whether vfio will support multifd, it'll be nice we stick with vfio_load_state() / vfio_save_state() for config space, and hopefully it's also easier it always go via the main channel to everyone. In these two hooks, VFIO can do whatever it wants to sync with other things (on src, sync with concurrent thread pool saving iterable data and dumping things to multifd channels; on dst, sync with multifd concurrent loads). I think it can remove the requirement on the load_finish() interface completely. Yes, this can only load VFIO's pci config space one by one, but I think this is much simpler, and I hope it's also not that slow, but I'm not sure.

To be clear, I made a following diagram describing how the patch set is supposed to work right now, including changing per-device VFIO_MIG_FLAG_DEV_DATA_STATE_COMPLETE into a common MIG_CMD_SWITCHOVER.

Time flows on it left to right (->).

----------- DIAGRAM START -----------
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /

Target overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable -> config data load operations
Multifd channels: \ multifd device state (1) -> multifd config data read (1)

Target config data load operations flow:
multifd config data read (1) -> config data load (2)

Notes:
(1): per device threads running in parallel
(2): currently serialized (only one such operation running at a particular time), will hopefully be parallelized in the future ----------- DIAGRAM END -----------

Hope the diagram survived being pasted into an e-mail message.

One can see, that even now there's a bit of "low hanging fruit" of missing possible parallelism:
It seems that the source could wait for multifd device state + multifd config data *after* non-iterables are sent rather than before as it is done currently - so they will be sent in parallel with multifd data.

Since written description is often prone to misunderstanding could you please annotate that diagram with your proposed new flow?

Thanks,
Maciej

#54 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 159 lines · Maciej S. Szmigiero
Quoted 140 lines · Peter Xu
Quoted 139 lines · Maciej S. Szmigiero
Quoted 137 lines · Peter Xu
Quoted 121 lines · Maciej S. Szmigiero
Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
     include/migration/register.h | 21 +++++++++++++++
     migration/migration.c        |  6 +++++
     migration/migration.h        |  3 +++
     migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
     migration/savevm.h           |  4 +++
     5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
         int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                  Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 299

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

        if (migrate_switchover_ack()) {
            qemu_loadvm_state_switchover_ack_needed(mis);
        }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Quoted 7 lines

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

This sounds like a performance concern, and I wonder how much this impacts the real workload (that you run a test and measure, with/without such concurrency) when we can save two devices in parallel anyway; I would expect the real diff is small due to the fact I mentioned that we save >1 VFIO devices concurrently via multifd.

Do you think we can start with a simpler approach?

Quoted 7 lines
Quoted 5 lines

I don't think introducing a performance/scalability issue like that is a good thing, especially that we already have a design that avoids it.

Unfortunately, my current setup does not allow live migrating VMs with more than 4 VFs so I can't benchmark that.

/me wonders why benchmarking it requires more than 4 VFs.

My point here was that the scalability problem will most likely get more pronounced with more VFs.

Quoted 7 lines
Quoted 3 lines

But I almost certain that with more VFs the situation with devices being ready out-of-order will get even more likely.

If the config space is small, why loading it in sequence would be a problem?

Quoted 8 lines
Quoted 2 lines

Have you measured how much time it needs to load one VF's config space that you're using? I suppose that's vfio_load_device_config_state() alone?

It's not the amount of data to load matters here but that these address space operations are slow.

The whole config load takes ~70 ms per device - that's time equivalent of transferring 875 MiB of device state via a 100 GBit/s link.

What's the downtime of migration with 1/2/4 VFs? I remember I saw some data somewhere but it's not in the cover letter. It'll be good to mention these results in the cover letter when repost.

I'm guessing 70ms isn't a huge deal here, if your NIC has 128GB internal device state to migrate.. but maybe I'm wrong.

I also wonder whether you profiled a bit on how that 70ms contributes to what is slow.

Quoted 29 lines
Quoted 29 lines
Quoted 9 lines
Quoted 9 lines

So what I'm thinking could be very clean is, we just discussed about MIG_CMD_SWITCHOVER and looks like you also think it's an OK approach. I wonder when with it why not we move one step further to have MIG_CMD_SEND_NON_ITERABE just to mark that "iterable devices all done, ready to send non-iterable". It can be controlled by the same migration property so we only send these two flags in 9.2+ machine types.

Quoted 8 lines
Quoted 3 lines

Then IIUC VFIO can send config data through main wire (just like most of other pci devices! which is IMHO a good fit..) and on destination VFIO holds off loading them until passing the MIG_CMD_SEND_NON_ITERABE phase.

Starting the config load only on MIG_CMD_SEND_NON_ITERABE would (in addition to the considerations above) also delay starting the config load until all iterable devices were read/transferred/loaded and also would complicate future efforts at loading that config data in parallel.

However I wonder whether we can keep it simple in that VFIO's config space is still always saved in vfio_save_state(). I still think it's easier we stick with the main channel whenever possible. For this specific case, if the config space is small I think it's tricky you bypass this with:

     if (migration->multifd_transfer) {
         /* Emit dummy NOP data */
         qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
         return;
     }
Quoted 8 lines
Quoted 5 lines

Then squash this as the tail of the iterable data.

On the src, I think it could use a per-device semaphore, so that iterable save() thread will post() only if it finishes dumping all the data, then that orders VFIO iterable data v.s. config space save().

In the future we want to not only transfer but also load the config data in parallel.

How feasible do you think this idea is? E.g. does it involve BQL so far (e.g. memory updates, others)? What's still missing to make it concurrent?

Quoted 3 lines

So going back to transferring this data serialized via the main migration channel would be taking a step back here.

If below holds true:

- 70ms is still very small amount in the total downtime, and,

- this can avoid the below load_finish() API

Then I'd go for it.. or again, at least the load_finish() needs change, IMHO..

Quoted 46 lines

By the way, we already have a serialization point in qemu_savevm_state_complete_precopy_iterable() after iterables have been sent - waiting for device state sending threads to finish their work.

Whether this thread_pool_wait() operation will be implemented using semaphores I'm not sure yet - will depend on how well this will fit other GThreadPool internals.

Quoted 37 lines

On the dst, after a 2nd thought, MIG_CMD_SEND_NON_ITERABE may not work or needed indeed, because multifd bypasses the main channel, so if we send anything like MIG_CMD_SEND_NON_ITERABE on the main channel it won't guarantee multifd load all complete. However IIUC that can be used in a similar way as the src qemu I mentioned above with a per-device semaphore, so that only all the iterable data of this device loaded and applied to the HW would it post(), before that, vfio_load_state() should wait() on that sem waiting for data to ready (while multifd threads will be doing that part). I wonder whether we may reuse the multifd recv thread in the initial version, so maybe we don't need any other threads on destination.

The load_finish() interface is currently not able to be reused right, afaict. Just have a look at its definition:

/**
* @load_finish
*
* Poll whether all asynchronous device state loading had finished.
* Not called on the load failure path.
*
* Called while holding the qemu_loadvm_load_finish_ready_lock. *
* If this method signals "not ready" then it might not be called
* again until qemu_loadvm_load_finish_ready_broadcast() is invoked
* while holding qemu_loadvm_load_finish_ready_lock.
*
* @opaque: data pointer passed to register_savevm_live()
* @is_finished: whether the loading had finished (output parameter)
* @errp: pointer to Error*, to store an error if it happens. *
* Returns zero to indicate success and negative for error
* It's not an error that the loading still hasn't finished. */
int (*load_finish)(void *opaque, bool *is_finished, Error **errp);

It's over complicated on defining all its details:

Quoted 8 lines
Quoted 1 line

- Not re-entrant by default..

What do you mean by "re-entrant" here?

This handler is called only from single migration thread, so it cannot be re-entered anyway since the control doesn't return to the migration code until this handler exits (and obviously the handler won't call itself recursively).

I think it's not a good design to say "you can call this function once, but not the 2nd time until you wait on a semaphore".

Quoted 26 lines
Quoted 4 lines

this is so weirdly designed so that the
caller needs to know which is even the "1st invocation of the function"... It is just weird.

I don't quite understand that - why do you think that caller needs to know whether this is the "1st invocation of the function"?

The caller only tracks whether all these handlers reported that they finished their work:

Quoted 14 lines
      bool all_ready = true;
      QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
          bool this_ready;

          ret = se->ops->load_finish(se->opaque, &this_ready, &local_err);
          if (ret) {
          } else if (!this_ready) {
              all_ready = false;
          }

      }
      if (all_ready) {
            break;
      }
Quoted 3 lines
Quoted 1 line

- Requires one more global mutex that non vmstate handler ever requested,

Could you elaborate what do you mean by "that non vmstate handler ever requested"?

I meant no historical vmstate handler hook functions requires such complicated locking to work.

Quoted 4 lines
Quoted 3 lines

that I feel like perhaps can be replaced by a sem (then to drop the condvar)?

Quoted 8 lines

Once we have ability to load device config state outside main migration thread replacing "load_finish" handler with a semaphore should indeed be possible (that's internal migration API so there should be no issue removing it as not necessary anymore at this point).

But for now, the devices need to have ability to run their config load code on the main migration thread, and for that they need to be called from this handler "load_finish".

A sem seems a must here to notify the iterable data finished loading, but that doesn't need to hook to the vmstate handler, but some post-process tasks, like what we do around cpu_synchronize_all_post_init() time.

If per-device vmstate handler hook version of load_finish() is destined to look as weird in this case, I'd rather consider a totally separate way to enqueue some jobs that needs to be run after all vmstates loaded. Then after one VFIO device fully loads its data, it enqueues the task and post() to one migration sem saying that "there's one post-process task, please run it in migration thread". There can be a total number of tasks registered so that migration thread knows not to continue until these number of tasks processed. That counter can be part of vmstate handler, maybe, reporting that "this vmstate handler has one post-process task".

Maybe you have other ideas, but please no, let's avoid this load_finish() thing..

I'd rather still see justifications showing that this 70ms really is helpful.. I'd rather wish we have +70ms*Ndev downtime but drop this hook until we have a clearer mind when all config space can be loaded concurrently, for example. So we start from simple.

Quoted 39 lines
Quoted 13 lines

- How qemu_loadvm_load_finish_ready_broadcast() interacts with all

     above..

So if you really think it matters to load whatever VFIO device who's iterable data is ready first, then let's try come up with some better interface.. I can try to think about it too, but please answer me questions above so I can understand what I am missing on why that's important. Numbers could help, even if 4 VF and I wonder how much diff there can be. Mostly, I don't know why it's slow right now if it is; I thought it should be pretty fast, at least not a concern in VFIO migration world (which can take seconds of downtime or more..).

Quoted 10 lines

IOW, it sounds more reasonalbe to me that no matter whether vfio will support multifd, it'll be nice we stick with vfio_load_state() / vfio_save_state() for config space, and hopefully it's also easier it always go via the main channel to everyone. In these two hooks, VFIO can do whatever it wants to sync with other things (on src, sync with concurrent thread pool saving iterable data and dumping things to multifd channels; on dst, sync with multifd concurrent loads). I think it can remove the requirement on the load_finish() interface completely. Yes, this can only load VFIO's pci config space one by one, but I think this is much simpler, and I hope it's also not that slow, but I'm not sure.

To be clear, I made a following diagram describing how the patch set is supposed to work right now, including changing per-device VFIO_MIG_FLAG_DEV_DATA_STATE_COMPLETE into a common MIG_CMD_SWITCHOVER.

Time flows on it left to right (->).

----------- DIAGRAM START -----------
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /

Target overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable -> config data load operations
Multifd channels: \ multifd device state (1) -> multifd config data read (1)

Quoted 5 lines

Target config data load operations flow:
multifd config data read (1) -> config data load (2)

Notes:
(1): per device threads running in parallel

Here I raised this question before, but I'll ask again: do you think we can avoid using a separate thread on dest qemu, but reuse multifd recv threads?

Src probably needs its own threads because multifd sender threads takes request, so it can't block on its own.

However dest qemu isn't like that, it's packet driven so I think maybe it's ok VFIO directly loads the data in the multifd threads. We may want to have enough multifd threads to make sure IO still don't block much on the NIC, but I think tuning the num of multifd threads should work in this case.

Quoted 10 lines

(2): currently serialized (only one such operation running at a particular time), will hopefully be parallelized in the future ----------- DIAGRAM END -----------

Hope the diagram survived being pasted into an e-mail message.

One can see, that even now there's a bit of "low hanging fruit" of missing possible parallelism:
It seems that the source could wait for multifd device state + multifd config data *after* non-iterables are sent rather than before as it is done currently - so they will be sent in parallel with multifd data.

Currently it's blocked by this chunk of code of yours:

    if (multifd_device_state) {
        ret = multifd_join_device_state_save_threads();
        if (ret) {
            qemu_file_set_error(f, ret);
            return -1;
        }
    }

If with your proposal that vfio config space sent via multifd channels, indeed I don't see why it can't be moved to be after non-iterable save() completes. Is that what you implied as "low hanging fruit"?

[***]

Quoted 3 lines

Since written description is often prone to misunderstanding could you please annotate that diagram with your proposed new flow?

What I was suggesting (removing load_finish()) is mostly the same as what you drew I think, especially on src:

===============
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /
===============

In this case we can't do the optimization above [***], since what I suggested requires VFIO's vfio_save_state() to dump the config space, so the original order will be needed here.

While on dest, config data load will need to also load using vfio's vfio_load_state() so it'll be invoked just like what we normally do with non-iterable device states (so here "config data load operations" is part of loading all non-iterable devices):

===============

Target overall flow:                                                              (X)
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable (multifd config data read -> config data load operations)
Multifd channels:                                       \ multifd device state load                                /

(lower part done via multifd recv threads, not separate threads)
===============

So here the ordering of (X) is not guarded by anything, however in vfio_load_state() the device can sem_wait() on a semaphore that only be posted until this device's device state is fully loaded. So it's not completely serialized - "config data load operations" of DEV1 can still happen concurrently with "multifd device state load" of DEV2.

Sorry, this might not be as clear as it's not easy to draw in the graph, but I hope the words can help clarify what I meant.

If 70ms is not a major deal, I suggest we consider above approach, I think it can simplify at least the vmstate handler API. If 70ms matters, let's try refactor load_finish() to something usable.

Thanks,

Signature · 1 line
Peter Xu
#55 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 166 lines · Peter Xu
Quoted 165 lines · Maciej S. Szmigiero
Quoted 140 lines · Peter Xu
Quoted 139 lines · Maciej S. Szmigiero
Quoted 137 lines · Peter Xu
Quoted 121 lines · Maciej S. Szmigiero
Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
      include/migration/register.h | 21 +++++++++++++++
      migration/migration.c        |  6 +++++
      migration/migration.h        |  3 +++
      migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
      migration/savevm.h           |  4 +++
      5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
          int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                   Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 299

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

         if (migrate_switchover_ack()) {
             qemu_loadvm_state_switchover_ack_needed(mis);
         }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Quoted 7 lines

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

This sounds like a performance concern, and I wonder how much this impacts the real workload (that you run a test and measure, with/without such concurrency) when we can save two devices in parallel anyway; I would expect the real diff is small due to the fact I mentioned that we save >1 VFIO devices concurrently via multifd.

Do you think we can start with a simpler approach?

Quoted 7 lines
Quoted 5 lines

I don't think introducing a performance/scalability issue like that is a good thing, especially that we already have a design that avoids it.

Unfortunately, my current setup does not allow live migrating VMs with more than 4 VFs so I can't benchmark that.

/me wonders why benchmarking it requires more than 4 VFs.

My point here was that the scalability problem will most likely get more pronounced with more VFs.

Quoted 9 lines
Quoted 3 lines

But I almost certain that with more VFs the situation with devices being ready out-of-order will get even more likely.

If the config space is small, why loading it in sequence would be a problem?

Have you measured how much time it needs to load one VF's config space that you're using? I suppose that's vfio_load_device_config_state() alone?

It's not the amount of data to load matters here but that these address space operations are slow.

Quoted 6 lines
Quoted 2 lines

The whole config load takes ~70 ms per device - that's time equivalent of transferring 875 MiB of device state via a 100 GBit/s link.

What's the downtime of migration with 1/2/4 VFs? I remember I saw some data somewhere but it's not in the cover letter. It'll be good to mention these results in the cover letter when repost.

Downtimes with the device state transfer being disabled / enabled:
4 VFs 2 VFs 1 VF

Disabled: 1783 ms  614 ms  283 ms
Enabled:  1068 ms  434 ms  274 ms

Will add these numbers to the cover letter of the next patch set version.

Quoted 2 lines

I'm guessing 70ms isn't a huge deal here, if your NIC has 128GB internal device state to migrate.. but maybe I'm wrong.

It's ~100 MiB of device state per VF here.

And it's 70ms of downtime *per device*:
so with 4 VF it's ~280ms of downtime taken by the config loads. That's a lot - with perfect parallelization this downtime should *reduce by* 210ms.

Quoted 2 lines

I also wonder whether you profiled a bit on how that 70ms contributes to what is slow.

I think that's something we can do after we have parallel config loads and it turns out their downtime for some reason still scales strongly linearly with the number of VFIO devices (rather than taking roughly constant time regardless of the count of these devices if running perfectly in parallel).

Quoted 35 lines
Quoted 35 lines
Quoted 34 lines
Quoted 9 lines
Quoted 9 lines

So what I'm thinking could be very clean is, we just discussed about MIG_CMD_SWITCHOVER and looks like you also think it's an OK approach. I wonder when with it why not we move one step further to have MIG_CMD_SEND_NON_ITERABE just to mark that "iterable devices all done, ready to send non-iterable". It can be controlled by the same migration property so we only send these two flags in 9.2+ machine types.

Quoted 8 lines
Quoted 3 lines

Then IIUC VFIO can send config data through main wire (just like most of other pci devices! which is IMHO a good fit..) and on destination VFIO holds off loading them until passing the MIG_CMD_SEND_NON_ITERABE phase.

Starting the config load only on MIG_CMD_SEND_NON_ITERABE would (in addition to the considerations above) also delay starting the config load until all iterable devices were read/transferred/loaded and also would complicate future efforts at loading that config data in parallel.

However I wonder whether we can keep it simple in that VFIO's config space is still always saved in vfio_save_state(). I still think it's easier we stick with the main channel whenever possible. For this specific case, if the config space is small I think it's tricky you bypass this with:

      if (migration->multifd_transfer) {
          /* Emit dummy NOP data */
          qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
          return;
      }

Then squash this as the tail of the iterable data.

On the src, I think it could use a per-device semaphore, so that iterable save() thread will post() only if it finishes dumping all the data, then that orders VFIO iterable data v.s. config space save().

Quoted 5 lines
Quoted 2 lines

In the future we want to not only transfer but also load the config data in parallel.

How feasible do you think this idea is? E.g. does it involve BQL so far (e.g. memory updates, others)? What's still missing to make it concurrent?

My gut feeling is that is feasible overall but it's too much of a rabbit hole for the first version of this device state transfer feature.

I think it will need some deeper QEMU core address space management changes, which need to be researched/developed/tested/reviewed/etc. on their own.

If it was an easy task I would have gladly included such support in this patch set version already for extra downtime reduction :)

Quoted 4 lines
Quoted 3 lines

So going back to transferring this data serialized via the main migration channel would be taking a step back here.

Quoted 8 lines

If below holds true:

- 70ms is still very small amount in the total downtime, and,

- this can avoid the below load_finish() API

Then I'd go for it.. or again, at least the load_finish() needs change, IMHO..

As I wrote above, it's not 70 ms total but 70 ms per device.

Also, even 70 ms is a lot, considering that the default downtime limit is 300 ms - with a single device that's nearly 1/4 of the limit already.

Quoted 50 lines
Quoted 50 lines

By the way, we already have a serialization point in qemu_savevm_state_complete_precopy_iterable() after iterables have been sent - waiting for device state sending threads to finish their work.

Whether this thread_pool_wait() operation will be implemented using semaphores I'm not sure yet - will depend on how well this will fit other GThreadPool internals.

Quoted 35 lines

On the dst, after a 2nd thought, MIG_CMD_SEND_NON_ITERABE may not work or needed indeed, because multifd bypasses the main channel, so if we send anything like MIG_CMD_SEND_NON_ITERABE on the main channel it won't guarantee multifd load all complete. However IIUC that can be used in a similar way as the src qemu I mentioned above with a per-device semaphore, so that only all the iterable data of this device loaded and applied to the HW would it post(), before that, vfio_load_state() should wait() on that sem waiting for data to ready (while multifd threads will be doing that part). I wonder whether we may reuse the multifd recv thread in the initial version, so maybe we don't need any other threads on destination.

The load_finish() interface is currently not able to be reused right, afaict. Just have a look at its definition:

/**
* @load_finish
*
* Poll whether all asynchronous device state loading had finished.
* Not called on the load failure path.
*
* Called while holding the qemu_loadvm_load_finish_ready_lock. *
* If this method signals "not ready" then it might not be called
* again until qemu_loadvm_load_finish_ready_broadcast() is invoked
* while holding qemu_loadvm_load_finish_ready_lock.
*
* @opaque: data pointer passed to register_savevm_live()
* @is_finished: whether the loading had finished (output parameter)
* @errp: pointer to Error*, to store an error if it happens. *
* Returns zero to indicate success and negative for error
* It's not an error that the loading still hasn't finished. */
int (*load_finish)(void *opaque, bool *is_finished, Error **errp);

Quoted 3 lines

It's over complicated on defining all its details:

- Not re-entrant by default..

What do you mean by "re-entrant" here?

Quoted 7 lines
Quoted 4 lines

This handler is called only from single migration thread, so it cannot be re-entered anyway since the control doesn't return to the migration code until this handler exits (and obviously the handler won't call itself recursively).

I think it's not a good design to say "you can call this function once, but not the 2nd time until you wait on a semaphore".

That's not exactly how this API is supposed to work.

I suspect that you took that "it might not be called again until qemu_loadvm_load_finish_ready_broadcast() is invoked" as prohibition from being called again until that signal is broadcast.

The intended meaning of that sentence was "it is possible that it won't be called again until qemu_loadvm_load_finish_ready_broadcast() is invoked".

In other words, the migration core is free to call this handler how many times the migration core wants.

But if the handler wants be *sure* that it will get called by the migration core after the handler has returned "not ready" then it needs to arrange for load_finish_ready_broadcast() to be invoked somehow.

(..)

Quoted 27 lines
Quoted 4 lines
Quoted 3 lines

that I feel like perhaps can be replaced by a sem (then to drop the condvar)?

Quoted 8 lines

Once we have ability to load device config state outside main migration thread replacing "load_finish" handler with a semaphore should indeed be possible (that's internal migration API so there should be no issue removing it as not necessary anymore at this point).

But for now, the devices need to have ability to run their config load code on the main migration thread, and for that they need to be called from this handler "load_finish".

A sem seems a must here to notify the iterable data finished loading, but that doesn't need to hook to the vmstate handler, but some post-process tasks, like what we do around cpu_synchronize_all_post_init() time.

If per-device vmstate handler hook version of load_finish() is destined to look as weird in this case, I'd rather consider a totally separate way to enqueue some jobs that needs to be run after all vmstates loaded. Then after one VFIO device fully loads its data, it enqueues the task and post() to one migration sem saying that "there's one post-process task, please run it in migration thread". There can be a total number of tasks registered so that migration thread knows not to continue until these number of tasks processed. That counter can be part of vmstate handler, maybe, reporting that "this vmstate handler has one post-process task".

Quoted 2 lines

Maybe you have other ideas, but please no, let's avoid this load_finish() thing..

I can certainly implement the task-queuing approach instead of the load_finish() handler API if you like such approach more.

Quoted 4 lines

I'd rather still see justifications showing that this 70ms really is helpful.. I'd rather wish we have +70ms*Ndev downtime but drop this hook until we have a clearer mind when all config space can be loaded concurrently, for example. So we start from simple.

As I wrote above, even 70ms for a single device is a lot considering the default downtime limit - and that's even more true if multiplied by multiple devices.

Quoted 48 lines
Quoted 39 lines
Quoted 13 lines

- How qemu_loadvm_load_finish_ready_broadcast() interacts with all above..

So if you really think it matters to load whatever VFIO device who's iterable data is ready first, then let's try come up with some better interface.. I can try to think about it too, but please answer me questions above so I can understand what I am missing on why that's important. Numbers could help, even if 4 VF and I wonder how much diff there can be. Mostly, I don't know why it's slow right now if it is; I thought it should be pretty fast, at least not a concern in VFIO migration world (which can take seconds of downtime or more..).

Quoted 10 lines

IOW, it sounds more reasonalbe to me that no matter whether vfio will support multifd, it'll be nice we stick with vfio_load_state() / vfio_save_state() for config space, and hopefully it's also easier it always go via the main channel to everyone. In these two hooks, VFIO can do whatever it wants to sync with other things (on src, sync with concurrent thread pool saving iterable data and dumping things to multifd channels; on dst, sync with multifd concurrent loads). I think it can remove the requirement on the load_finish() interface completely. Yes, this can only load VFIO's pci config space one by one, but I think this is much simpler, and I hope it's also not that slow, but I'm not sure.

To be clear, I made a following diagram describing how the patch set is supposed to work right now, including changing per-device VFIO_MIG_FLAG_DEV_DATA_STATE_COMPLETE into a common MIG_CMD_SWITCHOVER.

Time flows on it left to right (->).

----------- DIAGRAM START -----------
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /

Target overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable -> config data load operations
Multifd channels: \ multifd device state (1) -> multifd config data read (1)

Quoted 5 lines

Target config data load operations flow:
multifd config data read (1) -> config data load (2)

Notes:
(1): per device threads running in parallel

Here I raised this question before, but I'll ask again: do you think we can avoid using a separate thread on dest qemu, but reuse multifd recv threads?

Quoted 8 lines

Src probably needs its own threads because multifd sender threads takes request, so it can't block on its own.

However dest qemu isn't like that, it's packet driven so I think maybe it's ok VFIO directly loads the data in the multifd threads. We may want to have enough multifd threads to make sure IO still don't block much on the NIC, but I think tuning the num of multifd threads should work in this case.

We need to have the receiving threads decoupled from the VFIO device state loading threads at least because otherwise:
1) You can have a deadlock if device state for multiple devices arrives out of order, like here:

Time flows left to right (->).
Multifd channel 1: (VFIO device 1 buffer 2) (VFIO device 2 buffer 1) Multifd channel 2: (VFIO device 2 buffer 2) (VFIO device 1 buffer 1)

Both channel receive/load threads would be stuck forever in this case, since they can't load buffer 2 for devices 1 and 2 until they load buffer 1 for each of these devices.

2) If devices are loading buffers at different speeds you don't want to block the faster device from receiving new buffer just because the slower one hasn't finished its loading yet.

Quoted 21 lines
Quoted 10 lines

(2): currently serialized (only one such operation running at a particular time), will hopefully be parallelized in the future ----------- DIAGRAM END -----------

Hope the diagram survived being pasted into an e-mail message.

One can see, that even now there's a bit of "low hanging fruit" of missing possible parallelism:
It seems that the source could wait for multifd device state + multifd config data *after* non-iterables are sent rather than before as it is done currently - so they will be sent in parallel with multifd data.

Currently it's blocked by this chunk of code of yours:

     if (multifd_device_state) {
         ret = multifd_join_device_state_save_threads();
         if (ret) {
             qemu_file_set_error(f, ret);
             return -1;
         }
     }
Quoted 3 lines

If with your proposal that vfio config space sent via multifd channels, indeed I don't see why it can't be moved to be after non-iterable save() completes. Is that what you implied as "low hanging fruit"?

Yes, exactly - to wait for save threads to finish only after non-iterables have already been saved.

By "low hanging fruit" I meant it should be a fairly easy change.

Quoted 37 lines

[***]

Quoted 3 lines

Since written description is often prone to misunderstanding could you please annotate that diagram with your proposed new flow?

What I was suggesting (removing load_finish()) is mostly the same as what you drew I think, especially on src:

===============
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /
===============

In this case we can't do the optimization above [***], since what I suggested requires VFIO's vfio_save_state() to dump the config space, so the original order will be needed here.

While on dest, config data load will need to also load using vfio's vfio_load_state() so it'll be invoked just like what we normally do with non-iterable device states (so here "config data load operations" is part of loading all non-iterable devices):

===============

Target overall flow:                                                              (X)
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable (multifd config data read -> config data load operations)
Multifd channels:                                       \ multifd device state load                                /

(lower part done via multifd recv threads, not separate threads)
===============

So here the ordering of (X) is not guarded by anything, however in vfio_load_state() the device can sem_wait() on a semaphore that only be posted until this device's device state is fully loaded. So it's not completely serialized - "config data load operations" of DEV1 can still happen concurrently with "multifd device state load" of DEV2.

Quoted 6 lines

Sorry, this might not be as clear as it's not easy to draw in the graph, but I hope the words can help clarify what I meant.

If 70ms is not a major deal, I suggest we consider above approach, I think it can simplify at least the vmstate handler API. If 70ms matters, let's try refactor load_finish() to something usable.

I understand your point here, however as I wrote above, I think that's too much downtime to "waste" so I will try to rework the load_finish() handler into the task-queuing approach as you suggested earlier.

Quoted 2 lines

Thanks,

Thanks,
Maciej

#56 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 174 lines · Maciej S. Szmigiero
Quoted 166 lines · Peter Xu
Quoted 165 lines · Maciej S. Szmigiero
Quoted 140 lines · Peter Xu
Quoted 139 lines · Maciej S. Szmigiero
Quoted 137 lines · Peter Xu
Quoted 121 lines · Maciej S. Szmigiero
Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
      include/migration/register.h | 21 +++++++++++++++
      migration/migration.c        |  6 +++++
      migration/migration.h        |  3 +++
      migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
      migration/savevm.h           |  4 +++
      5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
          int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                   Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 299

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

         if (migrate_switchover_ack()) {
             qemu_loadvm_state_switchover_ack_needed(mis);
         }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Quoted 7 lines

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

This sounds like a performance concern, and I wonder how much this impacts the real workload (that you run a test and measure, with/without such concurrency) when we can save two devices in parallel anyway; I would expect the real diff is small due to the fact I mentioned that we save >1 VFIO devices concurrently via multifd.

Do you think we can start with a simpler approach?

Quoted 7 lines
Quoted 5 lines

I don't think introducing a performance/scalability issue like that is a good thing, especially that we already have a design that avoids it.

Unfortunately, my current setup does not allow live migrating VMs with more than 4 VFs so I can't benchmark that.

/me wonders why benchmarking it requires more than 4 VFs.

My point here was that the scalability problem will most likely get more pronounced with more VFs.

Quoted 9 lines
Quoted 3 lines

But I almost certain that with more VFs the situation with devices being ready out-of-order will get even more likely.

If the config space is small, why loading it in sequence would be a problem?

Have you measured how much time it needs to load one VF's config space that you're using? I suppose that's vfio_load_device_config_state() alone?

It's not the amount of data to load matters here but that these address space operations are slow.

Quoted 6 lines
Quoted 2 lines

The whole config load takes ~70 ms per device - that's time equivalent of transferring 875 MiB of device state via a 100 GBit/s link.

What's the downtime of migration with 1/2/4 VFs? I remember I saw some data somewhere but it's not in the cover letter. It'll be good to mention these results in the cover letter when repost.

Quoted 6 lines

Downtimes with the device state transfer being disabled / enabled:
4 VFs 2 VFs 1 VF

Disabled: 1783 ms  614 ms  283 ms
Enabled:  1068 ms  434 ms  274 ms

Will add these numbers to the cover letter of the next patch set version.

Thanks.

Quoted 5 lines
Quoted 3 lines

I'm guessing 70ms isn't a huge deal here, if your NIC has 128GB internal device state to migrate.. but maybe I'm wrong.

It's ~100 MiB of device state per VF here.

Ouch..

I watched your kvm forum talk recording, I remember that's where I get that 128 number but probably get the unit wrong.. ok that makes sense.

Quoted 5 lines

And it's 70ms of downtime *per device*:
so with 4 VF it's ~280ms of downtime taken by the config loads. That's a lot - with perfect parallelization this downtime should *reduce by* 210ms.

Yes, in this case it's a lot. I wonder why it won't scale as good even with your patchset.

Did you profile why? I highly doubt in your case network is an issue, as there's only 100MB per-dev data, so even on 10gbps it takes 100ms only to transfer for each, while now assuming it can run concurrently. I think you mentioned you were using 100gbps, right?

Logically when with multiple threads, VFIO read()s should happen at least concurrently per-device. Have you checked that there's no kernel-side global VFIO lock etc. that serializes portions of the threads read()s / write()s on the VFIO fds?

It's just a pity that you went this far, added all these logics, but without making it fully concurrent at least per device.

I'm OK if you want this in without that figured out, but if I were you I'll probably try to dig a bit to at least know why.

Quoted 9 lines
Quoted 3 lines

I also wonder whether you profiled a bit on how that 70ms contributes to what is slow.

I think that's something we can do after we have parallel config loads and it turns out their downtime for some reason still scales strongly linearly with the number of VFIO devices (rather than taking roughly constant time regardless of the count of these devices if running perfectly in parallel).

Similarly, I wonder whether the config space load() can involves something globally shared. I'd also dig a bit here, but I'll leave that to you to decide.

Quoted 42 lines
Quoted 36 lines
Quoted 36 lines
Quoted 35 lines
Quoted 10 lines
Quoted 10 lines

So what I'm thinking could be very clean is, we just discussed about MIG_CMD_SWITCHOVER and looks like you also think it's an OK approach. I wonder when with it why not we move one step further to have MIG_CMD_SEND_NON_ITERABE just to mark that "iterable devices all done, ready to send non-iterable". It can be controlled by the same migration property so we only send these two flags in 9.2+ machine types.

Quoted 8 lines
Quoted 3 lines

Then IIUC VFIO can send config data through main wire (just like most of other pci devices! which is IMHO a good fit..) and on destination VFIO holds off loading them until passing the MIG_CMD_SEND_NON_ITERABE phase.

Starting the config load only on MIG_CMD_SEND_NON_ITERABE would (in addition to the considerations above) also delay starting the config load until all iterable devices were read/transferred/loaded and also would complicate future efforts at loading that config data in parallel.

However I wonder whether we can keep it simple in that VFIO's config space is still always saved in vfio_save_state(). I still think it's easier we stick with the main channel whenever possible. For this specific case, if the config space is small I think it's tricky you bypass this with:

      if (migration->multifd_transfer) {
          /* Emit dummy NOP data */
          qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
          return;
      }

Then squash this as the tail of the iterable data.

On the src, I think it could use a per-device semaphore, so that iterable save() thread will post() only if it finishes dumping all the data, then that orders VFIO iterable data v.s. config space save().

Quoted 5 lines
Quoted 2 lines

In the future we want to not only transfer but also load the config data in parallel.

How feasible do you think this idea is? E.g. does it involve BQL so far (e.g. memory updates, others)? What's still missing to make it concurrent?

Quoted 8 lines

My gut feeling is that is feasible overall but it's too much of a rabbit hole for the first version of this device state transfer feature.

I think it will need some deeper QEMU core address space management changes, which need to be researched/developed/tested/reviewed/etc. on their own.

If it was an easy task I would have gladly included such support in this patch set version already for extra downtime reduction :)

Yes I understand.

Note that it doesn't need to be implemented and resolved in one shot, but I wonder if it'll still be good to debug the issue and know where is not scaling.

Considering that your design is fully concurrent as of now on iterable data from QEMU side, it's less persuasive to provide perf numbers that still doesn't scale that much; 1.78s -> 1.06s is a good improvement, but it doesn't seem to solve the scalability issue that this whole series wanted to address in general.

An extreme (bad) example is if VFIO has all ioctl()/read()/write() take a global lock, then any work in QEMU trying to run things in parallel will be a vain. Such patchset cannot be accepted because the other issue needs to be resolved first.

Now it's in the middle of best/worst condition, where it did improve but it still doesn't scale that well. I think it can be accepted, but still I feel like we're ignoring some of the real issues. We can choose to ignore the kernel saying that "it's too much to do together", but IMHO the issues should be tackled in the other way round.. the normal case is one should work out the kernel scalability issues, then QEMU should be on top.. Simply because any kernel change that might scale >1 device save()/load() can affect future QEMU change and design, not vice versa.

Again, I know you wished we make some progress, so I don't have a strong opinion. Just FYI.

Quoted 86 lines
Quoted 5 lines
Quoted 4 lines

So going back to transferring this data serialized via the main migration channel would be taking a step back here.

Quoted 8 lines

If below holds true:

- 70ms is still very small amount in the total downtime, and,

- this can avoid the below load_finish() API

Then I'd go for it.. or again, at least the load_finish() needs change, IMHO..

As I wrote above, it's not 70 ms total but 70 ms per device.

Also, even 70 ms is a lot, considering that the default downtime limit is 300 ms - with a single device that's nearly 1/4 of the limit already.

Quoted 50 lines
Quoted 50 lines

By the way, we already have a serialization point in qemu_savevm_state_complete_precopy_iterable() after iterables have been sent - waiting for device state sending threads to finish their work.

Whether this thread_pool_wait() operation will be implemented using semaphores I'm not sure yet - will depend on how well this will fit other GThreadPool internals.

Quoted 35 lines

On the dst, after a 2nd thought, MIG_CMD_SEND_NON_ITERABE may not work or needed indeed, because multifd bypasses the main channel, so if we send anything like MIG_CMD_SEND_NON_ITERABE on the main channel it won't guarantee multifd load all complete. However IIUC that can be used in a similar way as the src qemu I mentioned above with a per-device semaphore, so that only all the iterable data of this device loaded and applied to the HW would it post(), before that, vfio_load_state() should wait() on that sem waiting for data to ready (while multifd threads will be doing that part). I wonder whether we may reuse the multifd recv thread in the initial version, so maybe we don't need any other threads on destination.

The load_finish() interface is currently not able to be reused right, afaict. Just have a look at its definition:

/**
* @load_finish
*
* Poll whether all asynchronous device state loading had finished.
* Not called on the load failure path.
*
* Called while holding the qemu_loadvm_load_finish_ready_lock. *
* If this method signals "not ready" then it might not be called
* again until qemu_loadvm_load_finish_ready_broadcast() is invoked
* while holding qemu_loadvm_load_finish_ready_lock.
*
* @opaque: data pointer passed to register_savevm_live()
* @is_finished: whether the loading had finished (output parameter)
* @errp: pointer to Error*, to store an error if it happens. *
* Returns zero to indicate success and negative for error
* It's not an error that the loading still hasn't finished. */
int (*load_finish)(void *opaque, bool *is_finished, Error **errp);

Quoted 3 lines

It's over complicated on defining all its details:

- Not re-entrant by default..

What do you mean by "re-entrant" here?

Quoted 7 lines
Quoted 4 lines

This handler is called only from single migration thread, so it cannot be re-entered anyway since the control doesn't return to the migration code until this handler exits (and obviously the handler won't call itself recursively).

I think it's not a good design to say "you can call this function once, but not the 2nd time until you wait on a semaphore".

That's not exactly how this API is supposed to work.

I suspect that you took that "it might not be called again until qemu_loadvm_load_finish_ready_broadcast() is invoked" as prohibition from being called again until that signal is broadcast.

The intended meaning of that sentence was "it is possible that it won't be called again until qemu_loadvm_load_finish_ready_broadcast() is invoked".

Quoted 6 lines

In other words, the migration core is free to call this handler how many times the migration core wants.

But if the handler wants be *sure* that it will get called by the migration core after the handler has returned "not ready" then it needs to arrange for load_finish_ready_broadcast() to be invoked somehow.

OK I see.

Quoted 29 lines

(..)

Quoted 27 lines
Quoted 4 lines
Quoted 3 lines

that I feel like perhaps can be replaced by a sem (then to drop the condvar)?

Quoted 8 lines

Once we have ability to load device config state outside main migration thread replacing "load_finish" handler with a semaphore should indeed be possible (that's internal migration API so there should be no issue removing it as not necessary anymore at this point).

But for now, the devices need to have ability to run their config load code on the main migration thread, and for that they need to be called from this handler "load_finish".

A sem seems a must here to notify the iterable data finished loading, but that doesn't need to hook to the vmstate handler, but some post-process tasks, like what we do around cpu_synchronize_all_post_init() time.

If per-device vmstate handler hook version of load_finish() is destined to look as weird in this case, I'd rather consider a totally separate way to enqueue some jobs that needs to be run after all vmstates loaded. Then after one VFIO device fully loads its data, it enqueues the task and post() to one migration sem saying that "there's one post-process task, please run it in migration thread". There can be a total number of tasks registered so that migration thread knows not to continue until these number of tasks processed. That counter can be part of vmstate handler, maybe, reporting that "this vmstate handler has one post-process task".

Quoted 5 lines
Quoted 2 lines

Maybe you have other ideas, but please no, let's avoid this load_finish() thing..

I can certainly implement the task-queuing approach instead of the load_finish() handler API if you like such approach more.

I have an even simpler solution now. I think you can reuse precopy notifiers.

You can add one new PRECOPY_NOTIFY_INCOMING_COMPLETE event, invoke it after vmstate load all done.

As long as VFIO devices exist, VFIO can register with that event, then it can do whatever it wants in the main loader thread with BQL held.

You can hide that sem post() / wait() all there, then it's completely VFIO internal. Then we leave vmstate handler alone; it just doesn't sound suitable when the hooks need to be called out of order.

Quoted 76 lines
Quoted 5 lines

I'd rather still see justifications showing that this 70ms really is helpful.. I'd rather wish we have +70ms*Ndev downtime but drop this hook until we have a clearer mind when all config space can be loaded concurrently, for example. So we start from simple.

As I wrote above, even 70ms for a single device is a lot considering the default downtime limit - and that's even more true if multiplied by multiple devices.

Quoted 48 lines
Quoted 39 lines
Quoted 13 lines

- How qemu_loadvm_load_finish_ready_broadcast() interacts with all above..

So if you really think it matters to load whatever VFIO device who's iterable data is ready first, then let's try come up with some better interface.. I can try to think about it too, but please answer me questions above so I can understand what I am missing on why that's important. Numbers could help, even if 4 VF and I wonder how much diff there can be. Mostly, I don't know why it's slow right now if it is; I thought it should be pretty fast, at least not a concern in VFIO migration world (which can take seconds of downtime or more..).

Quoted 10 lines

IOW, it sounds more reasonalbe to me that no matter whether vfio will support multifd, it'll be nice we stick with vfio_load_state() / vfio_save_state() for config space, and hopefully it's also easier it always go via the main channel to everyone. In these two hooks, VFIO can do whatever it wants to sync with other things (on src, sync with concurrent thread pool saving iterable data and dumping things to multifd channels; on dst, sync with multifd concurrent loads). I think it can remove the requirement on the load_finish() interface completely. Yes, this can only load VFIO's pci config space one by one, but I think this is much simpler, and I hope it's also not that slow, but I'm not sure.

To be clear, I made a following diagram describing how the patch set is supposed to work right now, including changing per-device VFIO_MIG_FLAG_DEV_DATA_STATE_COMPLETE into a common MIG_CMD_SWITCHOVER.

Time flows on it left to right (->).

----------- DIAGRAM START -----------
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /

Target overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable -> config data load operations
Multifd channels: \ multifd device state (1) -> multifd config data read (1)

Quoted 5 lines

Target config data load operations flow:
multifd config data read (1) -> config data load (2)

Notes:
(1): per device threads running in parallel

Here I raised this question before, but I'll ask again: do you think we can avoid using a separate thread on dest qemu, but reuse multifd recv threads?

Quoted 8 lines

Src probably needs its own threads because multifd sender threads takes request, so it can't block on its own.

However dest qemu isn't like that, it's packet driven so I think maybe it's ok VFIO directly loads the data in the multifd threads. We may want to have enough multifd threads to make sure IO still don't block much on the NIC, but I think tuning the num of multifd threads should work in this case.

We need to have the receiving threads decoupled from the VFIO device state loading threads at least because otherwise:
1) You can have a deadlock if device state for multiple devices arrives out of order, like here:

Time flows left to right (->).
Multifd channel 1: (VFIO device 1 buffer 2) (VFIO device 2 buffer 1) Multifd channel 2: (VFIO device 2 buffer 2) (VFIO device 1 buffer 1)

Quoted 7 lines

Both channel receive/load threads would be stuck forever in this case, since they can't load buffer 2 for devices 1 and 2 until they load buffer 1 for each of these devices.

2) If devices are loading buffers at different speeds you don't want to block the faster device from receiving new buffer just because the slower one hasn't finished its loading yet.

I don't see why it can't be avoided. Let me draw this in columns.

How I picture this is:

multifd recv thread 1 multifd recv thread 2
--------------------- ---------------------
recv VFIO device 1 buffer 2 recv VFIO device 2 buffer 2
-> found that (dev1, buf1) missing, -> found that (dev2, buf1) missing,
skip load skip load
recv VFIO device 2 buffer 1 recv VFIO device 1 buffer 1
-> found that (dev2, buf1+buf2) ready, -> found that (dev1, buf1+buf2) ready,
load buf1+2 for dev2 here load buf1+2 for dev1 here

Here right after one multifd thread recvs a buffer, it needs to be injected into the cache array (with proper locking), so that whoever receives a full series of those buffers will do the load (again, with proper locking..).

Would this not work?

Quoted 71 lines
Quoted 22 lines
Quoted 11 lines

(2): currently serialized (only one such operation running at a particular time), will hopefully be parallelized in the future ----------- DIAGRAM END -----------

Hope the diagram survived being pasted into an e-mail message.

One can see, that even now there's a bit of "low hanging fruit" of missing possible parallelism:
It seems that the source could wait for multifd device state + multifd config data *after* non-iterables are sent rather than before as it is done currently - so they will be sent in parallel with multifd data.

Currently it's blocked by this chunk of code of yours:

     if (multifd_device_state) {
         ret = multifd_join_device_state_save_threads();
         if (ret) {
             qemu_file_set_error(f, ret);
             return -1;
         }
     }
Quoted 3 lines

If with your proposal that vfio config space sent via multifd channels, indeed I don't see why it can't be moved to be after non-iterable save() completes. Is that what you implied as "low hanging fruit"?

Yes, exactly - to wait for save threads to finish only after non-iterables have already been saved.

By "low hanging fruit" I meant it should be a fairly easy change.

Quoted 40 lines

[***]

Quoted 3 lines

Since written description is often prone to misunderstanding could you please annotate that diagram with your proposed new flow?

What I was suggesting (removing load_finish()) is mostly the same as what you drew I think, especially on src:

===============
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /
===============

In this case we can't do the optimization above [***], since what I suggested requires VFIO's vfio_save_state() to dump the config space, so the original order will be needed here.

While on dest, config data load will need to also load using vfio's vfio_load_state() so it'll be invoked just like what we normally do with non-iterable device states (so here "config data load operations" is part of loading all non-iterable devices):

===============

Target overall flow:                                                              (X)
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable (multifd config data read -> config data load operations)
Multifd channels:                                       \ multifd device state load                                /

(lower part done via multifd recv threads, not separate threads)
===============

So here the ordering of (X) is not guarded by anything, however in vfio_load_state() the device can sem_wait() on a semaphore that only be posted until this device's device state is fully loaded. So it's not completely serialized - "config data load operations" of DEV1 can still happen concurrently with "multifd device state load" of DEV2.

Sorry, this might not be as clear as it's not easy to draw in the graph, but I hope the words can help clarify what I meant.

Quoted 7 lines
Quoted 3 lines

If 70ms is not a major deal, I suggest we consider above approach, I think it can simplify at least the vmstate handler API. If 70ms matters, let's try refactor load_finish() to something usable.

I understand your point here, however as I wrote above, I think that's too much downtime to "waste" so I will try to rework the load_finish() handler into the task-queuing approach as you suggested earlier.

Thanks.

Signature · 1 line
Peter Xu
#57 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 201 lines · Peter Xu
Quoted 174 lines · Maciej S. Szmigiero
Quoted 166 lines · Peter Xu
Quoted 165 lines · Maciej S. Szmigiero
Quoted 140 lines · Peter Xu
Quoted 139 lines · Maciej S. Szmigiero
Quoted 137 lines · Peter Xu
Quoted 121 lines · Maciej S. Szmigiero
Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 27 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed to notify the migration code of its possible readiness via a call to qemu_loadvm_load_finish_ready_broadcast() while holding qemu_loadvm_load_finish_ready_lock.

---
       include/migration/register.h | 21 +++++++++++++++
       migration/migration.c        |  6 +++++
       migration/migration.h        |  3 +++
       migration/savevm.c           | 52 ++++++++++++++++++++++++++++++++++++
       migration/savevm.h           |  4 +++
       5 files changed, 86 insertions(+)
include/migration/register.h +1 -0
index 4a578f140713..44d8cf5192ae 100644
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
           int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
                                    Error **errp);
+    /**

include/migration/register.h typedef struct SaveVMHandlers { · line 290

Quoted 10 lines
include/migration/register.h +10 -0
+     * @load_finish
+     *
+     * Poll whether all asynchronous device state loading had finished.
+     * Not called on the load failure path.
+     *
+     * Called while holding the qemu_loadvm_load_finish_ready_lock.
+     *
+     * If this method signals "not ready" then it might not be called
+     * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+     * while holding qemu_loadvm_load_finish_ready_lock.

[1]

include/migration/register.h typedef struct SaveVMHandlers { · line 299

Quoted 9 lines
include/migration/register.h +9 -0
+     *
+     * @opaque: data pointer passed to register_savevm_live()
+     * @is_finished: whether the loading had finished (output parameter)
+     * @errp: pointer to Error*, to store an error if it happens.
+     *
+     * Returns zero to indicate success and negative for error
+     * It's not an error that the loading still hasn't finished.
+     */
+    int (*load_finish)(void *opaque, bool *is_finished, Error **errp);
Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

          if (migrate_switchover_ack()) {
              qemu_loadvm_state_switchover_ack_needed(mis);
          }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Quoted 7 lines

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

This sounds like a performance concern, and I wonder how much this impacts the real workload (that you run a test and measure, with/without such concurrency) when we can save two devices in parallel anyway; I would expect the real diff is small due to the fact I mentioned that we save >1 VFIO devices concurrently via multifd.

Do you think we can start with a simpler approach?

Quoted 7 lines
Quoted 5 lines

I don't think introducing a performance/scalability issue like that is a good thing, especially that we already have a design that avoids it.

Unfortunately, my current setup does not allow live migrating VMs with more than 4 VFs so I can't benchmark that.

/me wonders why benchmarking it requires more than 4 VFs.

My point here was that the scalability problem will most likely get more pronounced with more VFs.

Quoted 9 lines
Quoted 3 lines

But I almost certain that with more VFs the situation with devices being ready out-of-order will get even more likely.

If the config space is small, why loading it in sequence would be a problem?

Have you measured how much time it needs to load one VF's config space that you're using? I suppose that's vfio_load_device_config_state() alone?

It's not the amount of data to load matters here but that these address space operations are slow.

Quoted 6 lines
Quoted 2 lines

The whole config load takes ~70 ms per device - that's time equivalent of transferring 875 MiB of device state via a 100 GBit/s link.

What's the downtime of migration with 1/2/4 VFs? I remember I saw some data somewhere but it's not in the cover letter. It'll be good to mention these results in the cover letter when repost.

Quoted 6 lines

Downtimes with the device state transfer being disabled / enabled:
4 VFs 2 VFs 1 VF

Disabled: 1783 ms  614 ms  283 ms
Enabled:  1068 ms  434 ms  274 ms

Will add these numbers to the cover letter of the next patch set version.

Thanks.

Quoted 5 lines
Quoted 3 lines

I'm guessing 70ms isn't a huge deal here, if your NIC has 128GB internal device state to migrate.. but maybe I'm wrong.

It's ~100 MiB of device state per VF here.

Ouch..

I watched your kvm forum talk recording, I remember that's where I get that 128 number but probably get the unit wrong.. ok that makes sense.

Quoted 5 lines

And it's 70ms of downtime *per device*:
so with 4 VF it's ~280ms of downtime taken by the config loads. That's a lot - with perfect parallelization this downtime should *reduce by* 210ms.

Quoted 7 lines

Yes, in this case it's a lot. I wonder why it won't scale as good even with your patchset.

Did you profile why? I highly doubt in your case network is an issue, as there's only 100MB per-dev data, so even on 10gbps it takes 100ms only to transfer for each, while now assuming it can run concurrently. I think you mentioned you were using 100gbps, right?

Right, these 2 test machines are connected via a 100 GBbps network.

Quoted 4 lines

Logically when with multiple threads, VFIO read()s should happen at least concurrently per-device. Have you checked that there's no kernel-side global VFIO lock etc. that serializes portions of the threads read()s / write()s on the VFIO fds?

For these devices the kernel side has been significantly improved a year ago:
https://lore.kernel.org/kvm/[email protected]/

In the mlx5 driver the in-kernel device reading task (work) is separated from the userspace (QEMU) read()ing task via a double/multi buffering scheme.

If there was indeed some global lock serializing all device accesses we wouldn't be seeing that much improvement from this patch set as we are seeing - especially that the improvement seems to *increase* with the increased VF count in a single PF.

Quoted 2 lines

It's just a pity that you went this far, added all these logics, but without making it fully concurrent at least per device.

AFAIK NVIDIA/Mellanox are continuously working on improving the mlx5 driver, but to benefit from the driver parallelism we need parallelism in QEMU too so the userspace won't become the serialization point/bottleneck.

In other words, it's kind of a chicken and egg problem.

That's why I want to preserve as much parallelism in this patch set as possible to avoid accidental serialization which (even if not a problem right now) may become the bottleneck at some point.

Quoted 13 lines

I'm OK if you want this in without that figured out, but if I were you I'll probably try to dig a bit to at least know why.

Quoted 9 lines
Quoted 3 lines

I also wonder whether you profiled a bit on how that 70ms contributes to what is slow.

I think that's something we can do after we have parallel config loads and it turns out their downtime for some reason still scales strongly linearly with the number of VFIO devices (rather than taking roughly constant time regardless of the count of these devices if running perfectly in parallel).

Quoted 3 lines

Similarly, I wonder whether the config space load() can involves something globally shared. I'd also dig a bit here, but I'll leave that to you to decide.

Making config loads thread-safe/parallelizable is definitely on my future TODO list.

Just wanted to keep the amount of changes in the first version of this patch set within reasonable bounds - one has to draw a line somewhere otherwise we'll keep working on this patch set forever, with the QEMU code being a moving target meanwhile.

Quoted 77 lines
Quoted 42 lines
Quoted 36 lines
Quoted 36 lines
Quoted 35 lines
Quoted 10 lines
Quoted 10 lines

So what I'm thinking could be very clean is, we just discussed about MIG_CMD_SWITCHOVER and looks like you also think it's an OK approach. I wonder when with it why not we move one step further to have MIG_CMD_SEND_NON_ITERABE just to mark that "iterable devices all done, ready to send non-iterable". It can be controlled by the same migration property so we only send these two flags in 9.2+ machine types.

Quoted 8 lines
Quoted 3 lines

Then IIUC VFIO can send config data through main wire (just like most of other pci devices! which is IMHO a good fit..) and on destination VFIO holds off loading them until passing the MIG_CMD_SEND_NON_ITERABE phase.

Starting the config load only on MIG_CMD_SEND_NON_ITERABE would (in addition to the considerations above) also delay starting the config load until all iterable devices were read/transferred/loaded and also would complicate future efforts at loading that config data in parallel.

However I wonder whether we can keep it simple in that VFIO's config space is still always saved in vfio_save_state(). I still think it's easier we stick with the main channel whenever possible. For this specific case, if the config space is small I think it's tricky you bypass this with:

       if (migration->multifd_transfer) {
           /* Emit dummy NOP data */
           qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
           return;
       }

Then squash this as the tail of the iterable data.

On the src, I think it could use a per-device semaphore, so that iterable save() thread will post() only if it finishes dumping all the data, then that orders VFIO iterable data v.s. config space save().

Quoted 5 lines
Quoted 2 lines

In the future we want to not only transfer but also load the config data in parallel.

How feasible do you think this idea is? E.g. does it involve BQL so far (e.g. memory updates, others)? What's still missing to make it concurrent?

Quoted 8 lines

My gut feeling is that is feasible overall but it's too much of a rabbit hole for the first version of this device state transfer feature.

I think it will need some deeper QEMU core address space management changes, which need to be researched/developed/tested/reviewed/etc. on their own.

If it was an easy task I would have gladly included such support in this patch set version already for extra downtime reduction :)

Yes I understand.

Note that it doesn't need to be implemented and resolved in one shot, but I wonder if it'll still be good to debug the issue and know where is not scaling.

Considering that your design is fully concurrent as of now on iterable data from QEMU side, it's less persuasive to provide perf numbers that still doesn't scale that much; 1.78s -> 1.06s is a good improvement, but it doesn't seem to solve the scalability issue that this whole series wanted to address in general.

An extreme (bad) example is if VFIO has all ioctl()/read()/write() take a global lock, then any work in QEMU trying to run things in parallel will be a vain. Such patchset cannot be accepted because the other issue needs to be resolved first.

Now it's in the middle of best/worst condition, where it did improve but it still doesn't scale that well. I think it can be accepted, but still I feel like we're ignoring some of the real issues. We can choose to ignore the kernel saying that "it's too much to do together", but IMHO the issues should be tackled in the other way round.. the normal case is one should work out the kernel scalability issues, then QEMU should be on top.. Simply because any kernel change that might scale >1 device save()/load() can affect future QEMU change and design, not vice versa.

Quoted 3 lines

Again, I know you wished we make some progress, so I don't have a strong opinion. Just FYI.

As I wrote above, the kernel side of things are being taken care of by the mlx5 driver maintainers.

And these performance numbers suggest that there isn't some global lock serializing all device accesses as otherwise it would quickly become the bottleneck and we would be seeing diminishing improvement from increased VF count instead of increased improvement.

(..)

Quoted 39 lines
Quoted 27 lines
Quoted 27 lines
Quoted 4 lines
Quoted 3 lines

that I feel like perhaps can be replaced by a sem (then to drop the condvar)?

Quoted 8 lines

Once we have ability to load device config state outside main migration thread replacing "load_finish" handler with a semaphore should indeed be possible (that's internal migration API so there should be no issue removing it as not necessary anymore at this point).

But for now, the devices need to have ability to run their config load code on the main migration thread, and for that they need to be called from this handler "load_finish".

A sem seems a must here to notify the iterable data finished loading, but that doesn't need to hook to the vmstate handler, but some post-process tasks, like what we do around cpu_synchronize_all_post_init() time.

If per-device vmstate handler hook version of load_finish() is destined to look as weird in this case, I'd rather consider a totally separate way to enqueue some jobs that needs to be run after all vmstates loaded. Then after one VFIO device fully loads its data, it enqueues the task and post() to one migration sem saying that "there's one post-process task, please run it in migration thread". There can be a total number of tasks registered so that migration thread knows not to continue until these number of tasks processed. That counter can be part of vmstate handler, maybe, reporting that "this vmstate handler has one post-process task".

Quoted 5 lines
Quoted 2 lines

Maybe you have other ideas, but please no, let's avoid this load_finish() thing..

I can certainly implement the task-queuing approach instead of the load_finish() handler API if you like such approach more.

I have an even simpler solution now. I think you can reuse precopy notifiers.

You can add one new PRECOPY_NOTIFY_INCOMING_COMPLETE event, invoke it after vmstate load all done.

Quoted 6 lines

As long as VFIO devices exist, VFIO can register with that event, then it can do whatever it wants in the main loader thread with BQL held.

You can hide that sem post() / wait() all there, then it's completely VFIO internal. Then we leave vmstate handler alone; it just doesn't sound suitable when the hooks need to be called out of order.

I can certainly implement this functionality via a new precopy_notify(PRECOPY_NOTIFY_INCOMING_COMPLETE) notifier, for example by having a single notify handler registered by the VFIO driver, which handler will be common to all VFIO devices.

This handler on the VFIO driver side will then take care of proper operation ordering between the existing VFIO devices.

Quoted 87 lines
Quoted 66 lines
Quoted 48 lines
Quoted 39 lines
Quoted 13 lines

- How qemu_loadvm_load_finish_ready_broadcast() interacts with all above..

So if you really think it matters to load whatever VFIO device who's iterable data is ready first, then let's try come up with some better interface.. I can try to think about it too, but please answer me questions above so I can understand what I am missing on why that's important. Numbers could help, even if 4 VF and I wonder how much diff there can be. Mostly, I don't know why it's slow right now if it is; I thought it should be pretty fast, at least not a concern in VFIO migration world (which can take seconds of downtime or more..).

Quoted 10 lines

IOW, it sounds more reasonalbe to me that no matter whether vfio will support multifd, it'll be nice we stick with vfio_load_state() / vfio_save_state() for config space, and hopefully it's also easier it always go via the main channel to everyone. In these two hooks, VFIO can do whatever it wants to sync with other things (on src, sync with concurrent thread pool saving iterable data and dumping things to multifd channels; on dst, sync with multifd concurrent loads). I think it can remove the requirement on the load_finish() interface completely. Yes, this can only load VFIO's pci config space one by one, but I think this is much simpler, and I hope it's also not that slow, but I'm not sure.

To be clear, I made a following diagram describing how the patch set is supposed to work right now, including changing per-device VFIO_MIG_FLAG_DEV_DATA_STATE_COMPLETE into a common MIG_CMD_SWITCHOVER.

Time flows on it left to right (->).

----------- DIAGRAM START -----------
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /

Target overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable -> config data load operations
Multifd channels: \ multifd device state (1) -> multifd config data read (1)

Quoted 5 lines

Target config data load operations flow:
multifd config data read (1) -> config data load (2)

Notes:
(1): per device threads running in parallel

Here I raised this question before, but I'll ask again: do you think we can avoid using a separate thread on dest qemu, but reuse multifd recv threads?

Quoted 8 lines

Src probably needs its own threads because multifd sender threads takes request, so it can't block on its own.

However dest qemu isn't like that, it's packet driven so I think maybe it's ok VFIO directly loads the data in the multifd threads. We may want to have enough multifd threads to make sure IO still don't block much on the NIC, but I think tuning the num of multifd threads should work in this case.

We need to have the receiving threads decoupled from the VFIO device state loading threads at least because otherwise:
1) You can have a deadlock if device state for multiple devices arrives out of order, like here:

Time flows left to right (->).
Multifd channel 1: (VFIO device 1 buffer 2) (VFIO device 2 buffer 1) Multifd channel 2: (VFIO device 2 buffer 2) (VFIO device 1 buffer 1)

Quoted 7 lines

Both channel receive/load threads would be stuck forever in this case, since they can't load buffer 2 for devices 1 and 2 until they load buffer 1 for each of these devices.

2) If devices are loading buffers at different speeds you don't want to block the faster device from receiving new buffer just because the slower one hasn't finished its loading yet.

I don't see why it can't be avoided. Let me draw this in columns.

How I picture this is:

multifd recv thread 1 multifd recv thread 2
--------------------- ---------------------
recv VFIO device 1 buffer 2 recv VFIO device 2 buffer 2
-> found that (dev1, buf1) missing, -> found that (dev2, buf1) missing,
skip load skip load
recv VFIO device 2 buffer 1 recv VFIO device 1 buffer 1
-> found that (dev2, buf1+buf2) ready, -> found that (dev1, buf1+buf2) ready,
load buf1+2 for dev2 here load buf1+2 for dev1 here

Quoted 6 lines

Here right after one multifd thread recvs a buffer, it needs to be injected into the cache array (with proper locking), so that whoever receives a full series of those buffers will do the load (again, with proper locking..).

Would this not work?

For sure but that's definitely more complicated logic than just having a simple device loading thread that naturally loads incoming buffers for that device in-order.
That thread isn't even in the purview of the migration code since it's a VFIO driver internal implementation detail.

And we'd still lose parallelism if it happens that two buffers that are to be loaded next for two devices happen to arrive in the same multifd channel:
Multifd channel 1: (VFIO device 1 buffer 1) (VFIO device 2 buffer 1) Multifd channel 2: (VFIO device 2 buffer 2) (VFIO device 1 buffer 2)

Now device 2 buffer 1 has to wait until loading device 1 buffer 1 finishes even thought with the decoupled loading thread implementation from this patch set these would be loaded in parallel.

Quoted 3 lines

Thanks.

Thanks,
Maciej

#58 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 347 lines · Maciej S. Szmigiero
Quoted 201 lines · Peter Xu
Quoted 174 lines · Maciej S. Szmigiero
Quoted 166 lines · Peter Xu
Quoted 165 lines · Maciej S. Szmigiero
Quoted 140 lines · Peter Xu
Quoted 139 lines · Maciej S. Szmigiero
Quoted 137 lines · Peter Xu
Quoted 121 lines · Maciej S. Szmigiero
Quoted 64 lines · Peter Xu
Quoted 63 lines · Maciej S. Szmigiero
Quoted 51 lines · Peter Xu
Quoted 37 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether
a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed
to notify the migration code of its possible readiness via a call to
qemu_loadvm_load_finish_ready_broadcast() while holding
qemu_loadvm_load_finish_ready_lock.

Signed-off-by: Maciej S. Szmigiero <[email protected]>
---
include/migration/register.h | 21 +++++++++++++++
migration/migration.c | 6 +++++
migration/migration.h | 3 +++
migration/savevm.c | 52 ++++++++++++++++++++++++++++++++++++
migration/savevm.h | 4 +++
5 files changed, 86 insertions(+)

diff --git a/include/migration/register.h b/include/migration/register.h
index 4a578f140713..44d8cf5192ae 100644
--- a/include/migration/register.h
+++ b/include/migration/register.h
@@ -278,6 +278,27 @@ typedef struct SaveVMHandlers {
int (*load_state_buffer)(void *opaque, char *data, size_t data_size,
Error **errp);
+ /**
+ * @load_finish
+ *
+ * Poll whether all asynchronous device state loading had finished.
+ * Not called on the load failure path.
+ *
+ * Called while holding the qemu_loadvm_load_finish_ready_lock.
+ *
+ * If this method signals "not ready" then it might not be called
+ * again until qemu_loadvm_load_finish_ready_broadcast() is invoked
+ * while holding qemu_loadvm_load_finish_ready_lock.

[1]

Quoted 9 lines

+ *
+ * @opaque: data pointer passed to register_savevm_live()
+ * @is_finished: whether the loading had finished (output parameter)
+ * @errp: pointer to Error*, to store an error if it happens.
+ *
+ * Returns zero to indicate success and negative for error
+ * It's not an error that the loading still hasn't finished.
+ */
+ int (*load_finish)(void *opaque, bool *is_finished, Error **errp);

Quoted 2 lines

The load_finish() semantics is a bit weird, especially above [1] on "only allowed to be called once if ..." and also on the locks.

The point of this remark is that a driver needs to call qemu_loadvm_load_finish_ready_broadcast() if it wants for the migration core to call its load_finish handler again.

Quoted 3 lines

It looks to me vfio_load_finish() also does the final load of the device.

I wonder whether that final load can be done in the threads,

Quoted 8 lines
Quoted 3 lines

Here, the problem is that current VFIO VMState has to be loaded from the main migration thread as it internally calls QEMU core address space modification methods which explode if called from another thread(s).

Ahh, I see. I'm trying to make dest qemu loadvm in a thread too and yield BQL if possible, when that's ready then in your case here IIUC you can simply take BQL in whichever thread that loads it.. but yeah it's not ready at least..

Yeah, long term we might want to work on making these QEMU core address space modification methods somehow callable from multiple threads but that's definitely not something for the initial patch set.

Quoted 4 lines

Would it be possible vfio_save_complete_precopy_async_thread_config_state() be done in VFIO's save_live_complete_precopy() through the main channel somehow? IOW, does it rely on iterative data to be fetched first from kernel, or completely separate states?

The device state data needs to be fully loaded first before "activating" the device by loading its config state.

Quoted 3 lines

And just curious: how large is it
normally (and I suppose this decides whether it's applicable to be sent via the main channel at all..)?

Config data is *much* smaller than device state data - as far as I remember it was on order of kilobytes.

Quoted 20 lines
Quoted 15 lines
Quoted 9 lines

then after
everything loaded the device post a semaphore telling the main thread to continue. See e.g.:

          if (migrate_switchover_ack()) {
              qemu_loadvm_state_switchover_ack_needed(mis);
          }
Quoted 5 lines

IIUC, VFIO can register load_complete_ack similarly so it only sem_post() when all things are loaded? We can then get rid of this slightly awkward interface. I had a feeling that things can be simplified (e.g., if the thread will take care of loading the final vmstate then the mutex is also not needed? etc.).

Quoted 4 lines

With just a single call to switchover_ack_needed per VFIO device it would need to do a blocking wait for the device buffers and config state load to finish, therefore blocking other VFIO devices from potentially loading their config state if they are ready to begin this operation earlier.

Quoted 4 lines

I am not sure I get you here, loading VFIO device states (I mean, the non-iterable part) will need to be done sequentially IIUC due to what you said and should rely on BQL, so I don't know how that could happen concurrently for now. But I think indeed BQL is a problem.

Consider that we have two VFIO devices (A and B), with the following order of switchover_ack_needed handler calls for them: first A get this call, once the call for A finishes then B gets this call.

Quoted 7 lines

Now consider what happens if B had loaded all its buffers (in the loading thread) and it is ready for its config load before A finished loading its buffers.

B has to wait idle in this situation (even though it could have been already loading its config) since the switchover_ack_needed handler for A won't return until A is fully done.

This sounds like a performance concern, and I wonder how much this impacts the real workload (that you run a test and measure, with/without such concurrency) when we can save two devices in parallel anyway; I would expect the real diff is small due to the fact I mentioned that we save >1 VFIO devices concurrently via multifd.

Do you think we can start with a simpler approach?

Quoted 7 lines
Quoted 5 lines

I don't think introducing a performance/scalability issue like that is a good thing, especially that we already have a design that avoids it.

Unfortunately, my current setup does not allow live migrating VMs with more than 4 VFs so I can't benchmark that.

/me wonders why benchmarking it requires more than 4 VFs.

My point here was that the scalability problem will most likely get more pronounced with more VFs.

Quoted 9 lines
Quoted 3 lines

But I almost certain that with more VFs the situation with devices being ready out-of-order will get even more likely.

If the config space is small, why loading it in sequence would be a problem?

Have you measured how much time it needs to load one VF's config space that you're using? I suppose that's vfio_load_device_config_state() alone?

It's not the amount of data to load matters here but that these address space operations are slow.

Quoted 6 lines
Quoted 2 lines

The whole config load takes ~70 ms per device - that's time equivalent of transferring 875 MiB of device state via a 100 GBit/s link.

What's the downtime of migration with 1/2/4 VFs? I remember I saw some data somewhere but it's not in the cover letter. It'll be good to mention these results in the cover letter when repost.

Quoted 6 lines

Downtimes with the device state transfer being disabled / enabled:
4 VFs 2 VFs 1 VF

Disabled: 1783 ms  614 ms  283 ms
Enabled:  1068 ms  434 ms  274 ms

Will add these numbers to the cover letter of the next patch set version.

Thanks.

Quoted 5 lines
Quoted 3 lines

I'm guessing 70ms isn't a huge deal here, if your NIC has 128GB internal device state to migrate.. but maybe I'm wrong.

It's ~100 MiB of device state per VF here.

Ouch..

I watched your kvm forum talk recording, I remember that's where I get that 128 number but probably get the unit wrong.. ok that makes sense.

Quoted 5 lines

And it's 70ms of downtime *per device*:
so with 4 VF it's ~280ms of downtime taken by the config loads. That's a lot - with perfect parallelization this downtime should *reduce by* 210ms.

Quoted 7 lines

Yes, in this case it's a lot. I wonder why it won't scale as good even with your patchset.

Did you profile why? I highly doubt in your case network is an issue, as there's only 100MB per-dev data, so even on 10gbps it takes 100ms only to transfer for each, while now assuming it can run concurrently. I think you mentioned you were using 100gbps, right?

Right, these 2 test machines are connected via a 100 GBbps network.

Quoted 4 lines

Logically when with multiple threads, VFIO read()s should happen at least concurrently per-device. Have you checked that there's no kernel-side global VFIO lock etc. that serializes portions of the threads read()s / write()s on the VFIO fds?

For these devices the kernel side has been significantly improved a year ago:
https://lore.kernel.org/kvm/[email protected]/

In the mlx5 driver the in-kernel device reading task (work) is separated from the userspace (QEMU) read()ing task via a double/multi buffering scheme.

If there was indeed some global lock serializing all device accesses we wouldn't be seeing that much improvement from this patch set as we are seeing - especially that the improvement seems to *increase* with the increased VF count in a single PF.

Quoted 2 lines

It's just a pity that you went this far, added all these logics, but without making it fully concurrent at least per device.

AFAIK NVIDIA/Mellanox are continuously working on improving the mlx5 driver, but to benefit from the driver parallelism we need parallelism in QEMU too so the userspace won't become the serialization point/bottleneck.

In other words, it's kind of a chicken and egg problem.

That's why I want to preserve as much parallelism in this patch set as possible to avoid accidental serialization which (even if not a problem right now) may become the bottleneck at some point.

Quoted 13 lines

I'm OK if you want this in without that figured out, but if I were you I'll probably try to dig a bit to at least know why.

Quoted 9 lines
Quoted 3 lines

I also wonder whether you profiled a bit on how that 70ms contributes to what is slow.

I think that's something we can do after we have parallel config loads and it turns out their downtime for some reason still scales strongly linearly with the number of VFIO devices (rather than taking roughly constant time regardless of the count of these devices if running perfectly in parallel).

Quoted 3 lines

Similarly, I wonder whether the config space load() can involves something globally shared. I'd also dig a bit here, but I'll leave that to you to decide.

Making config loads thread-safe/parallelizable is definitely on my future TODO list.

Just wanted to keep the amount of changes in the first version of this patch set within reasonable bounds - one has to draw a line somewhere otherwise we'll keep working on this patch set forever, with the QEMU code being a moving target meanwhile.

Quoted 77 lines
Quoted 42 lines
Quoted 36 lines
Quoted 36 lines
Quoted 35 lines
Quoted 10 lines
Quoted 10 lines

So what I'm thinking could be very clean is, we just discussed about MIG_CMD_SWITCHOVER and looks like you also think it's an OK approach. I wonder when with it why not we move one step further to have MIG_CMD_SEND_NON_ITERABE just to mark that "iterable devices all done, ready to send non-iterable". It can be controlled by the same migration property so we only send these two flags in 9.2+ machine types.

Quoted 8 lines
Quoted 3 lines

Then IIUC VFIO can send config data through main wire (just like most of other pci devices! which is IMHO a good fit..) and on destination VFIO holds off loading them until passing the MIG_CMD_SEND_NON_ITERABE phase.

Starting the config load only on MIG_CMD_SEND_NON_ITERABE would (in addition to the considerations above) also delay starting the config load until all iterable devices were read/transferred/loaded and also would complicate future efforts at loading that config data in parallel.

However I wonder whether we can keep it simple in that VFIO's config space is still always saved in vfio_save_state(). I still think it's easier we stick with the main channel whenever possible. For this specific case, if the config space is small I think it's tricky you bypass this with:

       if (migration->multifd_transfer) {
           /* Emit dummy NOP data */
           qemu_put_be64(f, VFIO_MIG_FLAG_END_OF_STATE);
           return;
       }

Then squash this as the tail of the iterable data.

On the src, I think it could use a per-device semaphore, so that iterable save() thread will post() only if it finishes dumping all the data, then that orders VFIO iterable data v.s. config space save().

Quoted 5 lines
Quoted 2 lines

In the future we want to not only transfer but also load the config data in parallel.

How feasible do you think this idea is? E.g. does it involve BQL so far (e.g. memory updates, others)? What's still missing to make it concurrent?

Quoted 8 lines

My gut feeling is that is feasible overall but it's too much of a rabbit hole for the first version of this device state transfer feature.

I think it will need some deeper QEMU core address space management changes, which need to be researched/developed/tested/reviewed/etc. on their own.

If it was an easy task I would have gladly included such support in this patch set version already for extra downtime reduction :)

Yes I understand.

Note that it doesn't need to be implemented and resolved in one shot, but I wonder if it'll still be good to debug the issue and know where is not scaling.

Considering that your design is fully concurrent as of now on iterable data from QEMU side, it's less persuasive to provide perf numbers that still doesn't scale that much; 1.78s -> 1.06s is a good improvement, but it doesn't seem to solve the scalability issue that this whole series wanted to address in general.

An extreme (bad) example is if VFIO has all ioctl()/read()/write() take a global lock, then any work in QEMU trying to run things in parallel will be a vain. Such patchset cannot be accepted because the other issue needs to be resolved first.

Now it's in the middle of best/worst condition, where it did improve but it still doesn't scale that well. I think it can be accepted, but still I feel like we're ignoring some of the real issues. We can choose to ignore the kernel saying that "it's too much to do together", but IMHO the issues should be tackled in the other way round.. the normal case is one should work out the kernel scalability issues, then QEMU should be on top.. Simply because any kernel change that might scale >1 device save()/load() can affect future QEMU change and design, not vice versa.

Quoted 3 lines

Again, I know you wished we make some progress, so I don't have a strong opinion. Just FYI.

Quoted 7 lines

As I wrote above, the kernel side of things are being taken care of by the mlx5 driver maintainers.

And these performance numbers suggest that there isn't some global lock serializing all device accesses as otherwise it would quickly become the bottleneck and we would be seeing diminishing improvement from increased VF count instead of increased improvement.

Personally I am not satisfied with scaling with these numbers..

1VF 2VFs 4VFs
274 ms -> 434 ms -> 1068 ms

The lock doesn't need to be as stupid as a global lock that all ioctl()s take and it might not be as obvious that we can easily see. It can hide internally, it can be not in the form of a lock at all.

1068 is almost 4x of 274 here, that's really not scalable at all even if it is improvement for sure.. I still feel like something is off. If you think kernel isn't the bottleneck, I am actually more curious on why, especially if that could be relevant to the qemu design.

Quoted 48 lines

(..)

Quoted 39 lines
Quoted 27 lines
Quoted 27 lines
Quoted 4 lines
Quoted 3 lines

that I feel like perhaps can be replaced by a sem (then to drop the condvar)?

Quoted 8 lines

Once we have ability to load device config state outside main migration thread replacing "load_finish" handler with a semaphore should indeed be possible (that's internal migration API so there should be no issue removing it as not necessary anymore at this point).

But for now, the devices need to have ability to run their config load code on the main migration thread, and for that they need to be called from this handler "load_finish".

A sem seems a must here to notify the iterable data finished loading, but that doesn't need to hook to the vmstate handler, but some post-process tasks, like what we do around cpu_synchronize_all_post_init() time.

If per-device vmstate handler hook version of load_finish() is destined to look as weird in this case, I'd rather consider a totally separate way to enqueue some jobs that needs to be run after all vmstates loaded. Then after one VFIO device fully loads its data, it enqueues the task and post() to one migration sem saying that "there's one post-process task, please run it in migration thread". There can be a total number of tasks registered so that migration thread knows not to continue until these number of tasks processed. That counter can be part of vmstate handler, maybe, reporting that "this vmstate handler has one post-process task".

Quoted 5 lines
Quoted 2 lines

Maybe you have other ideas, but please no, let's avoid this load_finish() thing..

I can certainly implement the task-queuing approach instead of the load_finish() handler API if you like such approach more.

I have an even simpler solution now. I think you can reuse precopy notifiers.

You can add one new PRECOPY_NOTIFY_INCOMING_COMPLETE event, invoke it after vmstate load all done.

Quoted 6 lines

As long as VFIO devices exist, VFIO can register with that event, then it can do whatever it wants in the main loader thread with BQL held.

You can hide that sem post() / wait() all there, then it's completely VFIO internal. Then we leave vmstate handler alone; it just doesn't sound suitable when the hooks need to be called out of order.

Quoted 7 lines

I can certainly implement this functionality via a new precopy_notify(PRECOPY_NOTIFY_INCOMING_COMPLETE) notifier, for example by having a single notify handler registered by the VFIO driver, which handler will be common to all VFIO devices.

This handler on the VFIO driver side will then take care of proper operation ordering between the existing VFIO devices.

Great!

Quoted 91 lines
Quoted 91 lines
Quoted 67 lines
Quoted 49 lines
Quoted 40 lines
Quoted 14 lines

- How qemu_loadvm_load_finish_ready_broadcast() interacts with all above..

So if you really think it matters to load whatever VFIO device who's iterable data is ready first, then let's try come up with some better interface.. I can try to think about it too, but please answer me questions above so I can understand what I am missing on why that's important. Numbers could help, even if 4 VF and I wonder how much diff there can be. Mostly, I don't know why it's slow right now if it is; I thought it should be pretty fast, at least not a concern in VFIO migration world (which can take seconds of downtime or more..).

Quoted 10 lines

IOW, it sounds more reasonalbe to me that no matter whether vfio will support multifd, it'll be nice we stick with vfio_load_state() / vfio_save_state() for config space, and hopefully it's also easier it always go via the main channel to everyone. In these two hooks, VFIO can do whatever it wants to sync with other things (on src, sync with concurrent thread pool saving iterable data and dumping things to multifd channels; on dst, sync with multifd concurrent loads). I think it can remove the requirement on the load_finish() interface completely. Yes, this can only load VFIO's pci config space one by one, but I think this is much simpler, and I hope it's also not that slow, but I'm not sure.

To be clear, I made a following diagram describing how the patch set is supposed to work right now, including changing per-device VFIO_MIG_FLAG_DEV_DATA_STATE_COMPLETE into a common MIG_CMD_SWITCHOVER.

Time flows on it left to right (->).

----------- DIAGRAM START -----------
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /

Target overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable -> config data load operations
Multifd channels: \ multifd device state (1) -> multifd config data read (1)

Quoted 5 lines

Target config data load operations flow:
multifd config data read (1) -> config data load (2)

Notes:
(1): per device threads running in parallel

Here I raised this question before, but I'll ask again: do you think we can avoid using a separate thread on dest qemu, but reuse multifd recv threads?

Quoted 8 lines

Src probably needs its own threads because multifd sender threads takes request, so it can't block on its own.

However dest qemu isn't like that, it's packet driven so I think maybe it's ok VFIO directly loads the data in the multifd threads. We may want to have enough multifd threads to make sure IO still don't block much on the NIC, but I think tuning the num of multifd threads should work in this case.

We need to have the receiving threads decoupled from the VFIO device state loading threads at least because otherwise:
1) You can have a deadlock if device state for multiple devices arrives out of order, like here:

Time flows left to right (->).
Multifd channel 1: (VFIO device 1 buffer 2) (VFIO device 2 buffer 1) Multifd channel 2: (VFIO device 2 buffer 2) (VFIO device 1 buffer 1)

Quoted 7 lines

Both channel receive/load threads would be stuck forever in this case, since they can't load buffer 2 for devices 1 and 2 until they load buffer 1 for each of these devices.

2) If devices are loading buffers at different speeds you don't want to block the faster device from receiving new buffer just because the slower one hasn't finished its loading yet.

I don't see why it can't be avoided. Let me draw this in columns.

How I picture this is:

multifd recv thread 1 multifd recv thread 2
--------------------- ---------------------
recv VFIO device 1 buffer 2 recv VFIO device 2 buffer 2
-> found that (dev1, buf1) missing, -> found that (dev2, buf1) missing,
skip load skip load
recv VFIO device 2 buffer 1 recv VFIO device 1 buffer 1
-> found that (dev2, buf1+buf2) ready, -> found that (dev1, buf1+buf2) ready,
load buf1+2 for dev2 here load buf1+2 for dev1 here
Here right after one multifd thread recvs a buffer, it needs to be injected into the cache array (with proper locking), so that whoever receives a full series of those buffers will do the load (again, with proper locking..).

Quoted 6 lines
Quoted 2 lines

Would this not work?

For sure but that's definitely more complicated logic than just having a simple device loading thread that naturally loads incoming buffers for that device in-order.

I thought it was mostly your logic that was implemented, but yeah I didn't check too much details on VFIO side.

Quoted 9 lines

That thread isn't even in the purview of the migration code since it's a VFIO driver internal implementation detail.

And we'd still lose parallelism if it happens that two buffers that are to be loaded next for two devices happen to arrive in the same multifd channel:
Multifd channel 1: (VFIO device 1 buffer 1) (VFIO device 2 buffer 1) Multifd channel 2: (VFIO device 2 buffer 2) (VFIO device 1 buffer 2)

Quoted 3 lines

Now device 2 buffer 1 has to wait until loading device 1 buffer 1 finishes even thought with the decoupled loading thread implementation from this patch set these would be loaded in parallel.

Well it's possible indeed, but with normally 8 or more threads being there, possibility of having such dependency is low.

Cedric has similar comment on starting from simple on the thread model. I'd still suggest if ever possible we try reuse multifd recv threads; I do expect the results should be similar.

I am sorry to ask for this, Fabiano already blames me for this, but.. logically it'll be best we use no new thread in the series, then one patch on top with your new thread solution to justify its performance benefits and worthwhile to having those threads at all.

PS: I'd suggest if you really need those threads it should still be managed by migration framework like the src thread pool. Sorry I'm pretty stubborn on this, especially after I notice we have query-migrationthreads API just recently.. even if now I'm not sure whether we should remove that API. I assume that shouldn't need much change, even if necessary.

Thanks,

Signature · 1 line
Peter Xu
#59 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 25 lines · Peter Xu
Quoted 24 lines · Maciej S. Szmigiero
Quoted 23 lines · Peter Xu
Quoted 22 lines · Maciej S. Szmigiero
Quoted 21 lines · Peter Xu
Quoted 20 lines · Maciej S. Szmigiero
Quoted 19 lines · Peter Xu
Quoted 18 lines · Maciej S. Szmigiero
Quoted 17 lines · Peter Xu
Quoted 16 lines · Maciej S. Szmigiero
Quoted 15 lines · Peter Xu
Quoted 14 lines · Maciej S. Szmigiero
Quoted 13 lines · Peter Xu

On Tue, Aug 27, 2024 at 07:54:27PM +0200, Maciej S. Szmigiero wrote:
From: "Maciej S. Szmigiero" <[email protected]>

load_finish SaveVMHandler allows migration code to poll whether
a device-specific asynchronous device state loading operation had finished.

In order to avoid calling this handler needlessly the device is supposed
to notify the migration code of its possible readiness via a call to
qemu_loadvm_load_finish_ready_broadcast() while holding
qemu_loadvm_load_finish_ready_lock.

Signed-off-by: Maciej S. Szmigiero <[email protected]>
---

(..)

Quoted 13 lines
Quoted 7 lines

As I wrote above, the kernel side of things are being taken care of by the mlx5 driver maintainers.

And these performance numbers suggest that there isn't some global lock serializing all device accesses as otherwise it would quickly become the bottleneck and we would be seeing diminishing improvement from increased VF count instead of increased improvement.

Personally I am not satisfied with scaling with these numbers..

1VF 2VFs 4VFs
274 ms -> 434 ms -> 1068 ms

Quoted 9 lines

The lock doesn't need to be as stupid as a global lock that all ioctl()s take and it might not be as obvious that we can easily see. It can hide internally, it can be not in the form of a lock at all.

1068 is almost 4x of 274 here, that's really not scalable at all even if it is improvement for sure.. I still feel like something is off. If you think kernel isn't the bottleneck, I am actually more curious on why, especially if that could be relevant to the qemu design.

These are 4 VFs of a single PF NIC, so it's not only kernel driver involved here but also the whole physical device itself.

Without the userspace/QEMU side being parallelized it was hard to even measure the driver/device-side bottlenecks.

However, even with the current state of things we still get a nice 67% improvement in downtime.

As I wrote yesterday, AFAIK it is a WIP also on the mlx5/device side of things.

(..)

Quoted 116 lines
Quoted 90 lines
Quoted 90 lines
Quoted 66 lines
Quoted 48 lines
Quoted 39 lines
Quoted 13 lines

- How qemu_loadvm_load_finish_ready_broadcast() interacts with all above..

So if you really think it matters to load whatever VFIO device who's iterable data is ready first, then let's try come up with some better interface.. I can try to think about it too, but please answer me questions above so I can understand what I am missing on why that's important. Numbers could help, even if 4 VF and I wonder how much diff there can be. Mostly, I don't know why it's slow right now if it is; I thought it should be pretty fast, at least not a concern in VFIO migration world (which can take seconds of downtime or more..).

Quoted 10 lines

IOW, it sounds more reasonalbe to me that no matter whether vfio will support multifd, it'll be nice we stick with vfio_load_state() / vfio_save_state() for config space, and hopefully it's also easier it always go via the main channel to everyone. In these two hooks, VFIO can do whatever it wants to sync with other things (on src, sync with concurrent thread pool saving iterable data and dumping things to multifd channels; on dst, sync with multifd concurrent loads). I think it can remove the requirement on the load_finish() interface completely. Yes, this can only load VFIO's pci config space one by one, but I think this is much simpler, and I hope it's also not that slow, but I'm not sure.

To be clear, I made a following diagram describing how the patch set is supposed to work right now, including changing per-device VFIO_MIG_FLAG_DEV_DATA_STATE_COMPLETE into a common MIG_CMD_SWITCHOVER.

Time flows on it left to right (->).

----------- DIAGRAM START -----------
Source overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable
Multifd channels: \ multifd device state read and queue (1) -> multifd config data read and queue (1) /

Target overall flow:
Main channel: live VM phase data -> MIG_CMD_SWITCHOVER -> iterable -> non iterable -> config data load operations
Multifd channels: \ multifd device state (1) -> multifd config data read (1)

Quoted 5 lines

Target config data load operations flow:
multifd config data read (1) -> config data load (2)

Notes:
(1): per device threads running in parallel

Here I raised this question before, but I'll ask again: do you think we can avoid using a separate thread on dest qemu, but reuse multifd recv threads?

Quoted 8 lines

Src probably needs its own threads because multifd sender threads takes request, so it can't block on its own.

However dest qemu isn't like that, it's packet driven so I think maybe it's ok VFIO directly loads the data in the multifd threads. We may want to have enough multifd threads to make sure IO still don't block much on the NIC, but I think tuning the num of multifd threads should work in this case.

We need to have the receiving threads decoupled from the VFIO device state loading threads at least because otherwise:
1) You can have a deadlock if device state for multiple devices arrives out of order, like here:

Time flows left to right (->).
Multifd channel 1: (VFIO device 1 buffer 2) (VFIO device 2 buffer 1) Multifd channel 2: (VFIO device 2 buffer 2) (VFIO device 1 buffer 1)

Quoted 7 lines

Both channel receive/load threads would be stuck forever in this case, since they can't load buffer 2 for devices 1 and 2 until they load buffer 1 for each of these devices.

2) If devices are loading buffers at different speeds you don't want to block the faster device from receiving new buffer just because the slower one hasn't finished its loading yet.

I don't see why it can't be avoided. Let me draw this in columns.

How I picture this is:

multifd recv thread 1 multifd recv thread 2
--------------------- ---------------------
recv VFIO device 1 buffer 2 recv VFIO device 2 buffer 2
-> found that (dev1, buf1) missing, -> found that (dev2, buf1) missing,
skip load skip load
recv VFIO device 2 buffer 1 recv VFIO device 1 buffer 1
-> found that (dev2, buf1+buf2) ready, -> found that (dev1, buf1+buf2) ready,
load buf1+2 for dev2 here load buf1+2 for dev1 here
Here right after one multifd thread recvs a buffer, it needs to be injected into the cache array (with proper locking), so that whoever receives a full series of those buffers will do the load (again, with proper locking..).

Quoted 6 lines
Quoted 2 lines

Would this not work?

For sure but that's definitely more complicated logic than just having a simple device loading thread that naturally loads incoming buffers for that device in-order.

I thought it was mostly your logic that was implemented, but yeah I didn't check too much details on VFIO side.

Quoted 9 lines

That thread isn't even in the purview of the migration code since it's a VFIO driver internal implementation detail.

And we'd still lose parallelism if it happens that two buffers that are to be loaded next for two devices happen to arrive in the same multifd channel:
Multifd channel 1: (VFIO device 1 buffer 1) (VFIO device 2 buffer 1) Multifd channel 2: (VFIO device 2 buffer 2) (VFIO device 1 buffer 2)

Quoted 3 lines

Now device 2 buffer 1 has to wait until loading device 1 buffer 1 finishes even thought with the decoupled loading thread implementation from this patch set these would be loaded in parallel.

Well it's possible indeed, but with normally 8 or more threads being there, possibility of having such dependency is low.

Quoted 8 lines

Cedric has similar comment on starting from simple on the thread model. I'd still suggest if ever possible we try reuse multifd recv threads; I do expect the results should be similar.

I am sorry to ask for this, Fabiano already blames me for this, but.. logically it'll be best we use no new thread in the series, then one patch on top with your new thread solution to justify its performance benefits and worthwhile to having those threads at all.

To be clear, these loading threads are mostly blocking I/O threads, NOT compute threads.
This means that the usual "rule of thumb" that the count of threads should not exceed the total number of logical CPUs does NOT apply to them.

They are similar to what glibc uses under the hood to simulate POSIX AIO (aio_read(), aio_write()), to implement an async DNS resolver (getaddrinfo_a()) and what Glib's GIO uses to simulate its own async file operations. Using helper threads for turning blocking I/O into "AIO" is a pretty common thing.

To show that these loading threads mostly spend their time sleeping (waiting for I/O) I made a quick patch at [1] tracing how much time they spend waiting for incoming buffers and how much time they spend waiting for these buffers to be loaded into the device.

The results (without patch [2] described later) are like this:

Quoted 8 lines
[email protected]:vfio_load_state_device_buffer_start  (0000:af:00.2)
[email protected]:vfio_load_state_device_buffer_start  (0000:af:00.4)
[email protected]:vfio_load_state_device_buffer_start  (0000:af:00.5)
[email protected]:vfio_load_state_device_buffer_start  (0000:af:00.3)
[email protected]:vfio_load_state_device_buffer_end  (0000:af:00.3) wait 43 ms load 217 ms
[email protected]:vfio_load_state_device_buffer_end  (0000:af:00.4) wait 75 ms load 206 ms
[email protected]:vfio_load_state_device_buffer_end  (0000:af:00.2) wait 69 ms load 210 ms
[email protected]:vfio_load_state_device_buffer_end  (0000:af:00.5) wait 79 ms load 204 ms

Summing up:
0000:af:00.2 total loading time 283 ms, wait 69 ms load 210 ms 0000:af:00.3 total loading time 258 ms, wait 43 ms load 217 ms 0000:af:00.4 total loading time 278 ms, wait 75 ms load 206 ms 0000:af:00.5 total loading time 282 ms, wait 79 ms load 204 ms

In other words, these threads spend ~100% of their total runtime waiting for I/O, 70%-75% of that time waiting for buffers to get loaded into their target device.

So having more threads here won't negatively affect the host CPU consumption since these threads barely use the host CPU at all. Also, their count is capped at the number of VFIO devices in the VM.

I also did a quick test with the same config as usual: 4 VFs, 6 multifd channels, but with patch at [2] simulating forced coupling of loading threads to multifd receive channel threads.

With this patch load_state_buffer() handler will return to the multifd channel thread only when the loading thread finishes loading available buffers and is about to wait for the next buffers to arrive - just as loading buffers directly from these channel threads would do.

The resulting lowest downtime from 115 live migration runs was 1295ms - that's 21% worse than 1068ms of downtime with these loading threads running on their own.

I expect that this performance penalty to get even worse with more VFs than 4.

So no, we can't load buffers directly from multifd channel receive threads.

Quoted 5 lines

PS: I'd suggest if you really need those threads it should still be managed by migration framework like the src thread pool. Sorry I'm pretty stubborn on this, especially after I notice we have query-migrationthreads API just recently.. even if now I'm not sure whether we should remove that API. I assume that shouldn't need much change, even if necessary.

I can certainly make these loading threads managed in a thread pool if that's easier for you.

Quoted 2 lines

Thanks,

Thanks,
Maciej

[1]: https://github.com/maciejsszmigiero/qemu/commit/b0833053359715c604070f64fc058f90ec61d180
[2]: https://github.com/maciejsszmigiero/qemu/commit/0c9b4072eaebf8e7bd9560dd27a14cd048097565

#60 lore raw

Re: [PATCH v2 08/17] migration: Add load_finish handler and associated functions

Quoted 10 lines · Maciej S. Szmigiero

To be clear, these loading threads are mostly blocking I/O threads, NOT compute threads.
This means that the usual "rule of thumb" that the count of threads should not exceed the total number of logical CPUs does NOT apply to them.

They are similar to what glibc uses under the hood to simulate POSIX AIO (aio_read(), aio_write()), to implement an async DNS resolver (getaddrinfo_a()) and what Glib's GIO uses to simulate its own async file operations. Using helper threads for turning blocking I/O into "AIO" is a pretty common thing.

Fair enough. Yes I could be over-cautious due to the previous experience on managing all kinds of migration threads.

Quoted 39 lines

To show that these loading threads mostly spend their time sleeping (waiting for I/O) I made a quick patch at [1] tracing how much time they spend waiting for incoming buffers and how much time they spend waiting for these buffers to be loaded into the device.

The results (without patch [2] described later) are like this:

Quoted 8 lines
[email protected]:vfio_load_state_device_buffer_start  (0000:af:00.2)
[email protected]:vfio_load_state_device_buffer_start  (0000:af:00.4)
[email protected]:vfio_load_state_device_buffer_start  (0000:af:00.5)
[email protected]:vfio_load_state_device_buffer_start  (0000:af:00.3)
[email protected]:vfio_load_state_device_buffer_end  (0000:af:00.3) wait 43 ms load 217 ms
[email protected]:vfio_load_state_device_buffer_end  (0000:af:00.4) wait 75 ms load 206 ms
[email protected]:vfio_load_state_device_buffer_end  (0000:af:00.2) wait 69 ms load 210 ms
[email protected]:vfio_load_state_device_buffer_end  (0000:af:00.5) wait 79 ms load 204 ms

Summing up:
0000:af:00.2 total loading time 283 ms, wait 69 ms load 210 ms 0000:af:00.3 total loading time 258 ms, wait 43 ms load 217 ms 0000:af:00.4 total loading time 278 ms, wait 75 ms load 206 ms 0000:af:00.5 total loading time 282 ms, wait 79 ms load 204 ms

In other words, these threads spend ~100% of their total runtime waiting for I/O, 70%-75% of that time waiting for buffers to get loaded into their target device.

So having more threads here won't negatively affect the host CPU consumption since these threads barely use the host CPU at all. Also, their count is capped at the number of VFIO devices in the VM.

I also did a quick test with the same config as usual: 4 VFs, 6 multifd channels, but with patch at [2] simulating forced coupling of loading threads to multifd receive channel threads.

With this patch load_state_buffer() handler will return to the multifd channel thread only when the loading thread finishes loading available buffers and is about to wait for the next buffers to arrive - just as loading buffers directly from these channel threads would do.

Quoted 8 lines

The resulting lowest downtime from 115 live migration runs was 1295ms - that's 21% worse than 1068ms of downtime with these loading threads running on their own.

I expect that this performance penalty to get even worse with more VFs than 4.

So no, we can't load buffers directly from multifd channel receive threads.

6 channels can be a bit less in this test case with 4 VFs, but indeed adding such dependency on number of multifd threads isn't as good either, I agree. I'm ok as long as VFIO reviewers are fine.

Quoted 9 lines
Quoted 6 lines

PS: I'd suggest if you really need those threads it should still be managed by migration framework like the src thread pool. Sorry I'm pretty stubborn on this, especially after I notice we have query-migrationthreads API just recently.. even if now I'm not sure whether we should remove that API. I assume that shouldn't need much change, even if necessary.

I can certainly make these loading threads managed in a thread pool if that's easier for you.

Yes, if you want to use separate thread it'll be great to match on the src thread model with similar pool. I hope the pool interface you have is easily applicable on both sides.

Thanks,

Signature · 1 line
Peter Xu
#61 lore raw

PATCH v2 9/17 migration/multifd: Device state transfer support - receive side

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
 migration/multifd.c | 127 +++++++++++++++++++++++++++++++++++++-------
 migration/multifd.h |  31 ++++++++++-
 2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +108 -19
index b06a9fab500e..d5a8e5a9c9b5 100644
@@ -21,6 +21,7 @@
 #include "file.h"
 #include "migration.h"
 #include "migration-stats.h"
+#include "savevm.h"
 #include "socket.h"
 #include "tls.h"
 #include "qemu-file.h"
@@ -209,10 +210,10 @@ void multifd_send_fill_packet(MultiFDSendParams *p)
 
     memset(packet, 0, p->packet_len);
 
-    packet->magic = cpu_to_be32(MULTIFD_MAGIC);
-    packet->version = cpu_to_be32(MULTIFD_VERSION);
+    packet->hdr.magic = cpu_to_be32(MULTIFD_MAGIC);
+    packet->hdr.version = cpu_to_be32(MULTIFD_VERSION);
 
-    packet->flags = cpu_to_be32(p->flags);
+    packet->hdr.flags = cpu_to_be32(p->flags);
     packet->next_packet_size = cpu_to_be32(p->next_packet_size);
 
     packet_num = qatomic_fetch_inc(&multifd_send_state->packet_num);
@@ -228,31 +229,49 @@ void multifd_send_fill_packet(MultiFDSendParams *p)
                             p->flags, p->next_packet_size);
 }
 
-static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
+static int multifd_recv_unfill_packet_header(MultiFDRecvParams *p,
+                                             MultiFDPacketHdr_t *hdr,
+                                             Error **errp)
 {
-    MultiFDPacket_t *packet = p->packet;
-    int ret = 0;
-
-    packet->magic = be32_to_cpu(packet->magic);
-    if (packet->magic != MULTIFD_MAGIC) {
+    hdr->magic = be32_to_cpu(hdr->magic);
+    if (hdr->magic != MULTIFD_MAGIC) {
         error_setg(errp, "multifd: received packet "
                    "magic %x and expected magic %x",
-                   packet->magic, MULTIFD_MAGIC);
+                   hdr->magic, MULTIFD_MAGIC);
         return -1;
     }
 
-    packet->version = be32_to_cpu(packet->version);
-    if (packet->version != MULTIFD_VERSION) {
+    hdr->version = be32_to_cpu(hdr->version);
+    if (hdr->version != MULTIFD_VERSION) {
         error_setg(errp, "multifd: received packet "
                    "version %u and expected version %u",
-                   packet->version, MULTIFD_VERSION);
+                   hdr->version, MULTIFD_VERSION);
         return -1;
     }
 
-    p->flags = be32_to_cpu(packet->flags);
+    p->flags = be32_to_cpu(hdr->flags);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_device_state(MultiFDRecvParams *p,
+                                                   Error **errp)
+{
+    MultiFDPacketDeviceState_t *packet = p->packet_dev_state;
+
+    packet->instance_id = be32_to_cpu(packet->instance_id);
+    p->next_packet_size = be32_to_cpu(packet->next_packet_size);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_ram(MultiFDRecvParams *p, Error **errp)
+{
+    MultiFDPacket_t *packet = p->packet;
+    int ret = 0;
+
     p->next_packet_size = be32_to_cpu(packet->next_packet_size);
     p->packet_num = be64_to_cpu(packet->packet_num);
-    p->packets_recved++;
 
     if (!(p->flags & MULTIFD_FLAG_SYNC)) {
         ret = multifd_ram_unfill_packet(p, errp);
@@ -264,6 +283,19 @@ static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
     return ret;
 }
 
+static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
+{
+    p->packets_recved++;
+
+    if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
+        return multifd_recv_unfill_packet_device_state(p, errp);
+    } else {
+        return multifd_recv_unfill_packet_ram(p, errp);
+    }
+
+    g_assert_not_reached();
+}
+
 static bool multifd_send_should_exit(void)
 {
     return qatomic_read(&multifd_send_state->exiting);
@@ -1014,6 +1046,7 @@ static void multifd_recv_cleanup_channel(MultiFDRecvParams *p)
     p->packet_len = 0;
     g_free(p->packet);
     p->packet = NULL;
+    g_clear_pointer(&p->packet_dev_state, g_free);
     g_free(p->normal);
     p->normal = NULL;
     g_free(p->zero);
@@ -1126,8 +1159,13 @@ static void *multifd_recv_thread(void *opaque)
     rcu_register_thread();
 
     while (true) {
+        MultiFDPacketHdr_t hdr;
         uint32_t flags = 0;
+        bool is_device_state = false;
         bool has_data = false;
+        uint8_t *pkt_buf;
+        size_t pkt_len;
+
         p->normal_num = 0;
 
         if (use_packets) {
@@ -1135,8 +1173,28 @@ static void *multifd_recv_thread(void *opaque)
                 break;
             }
 
-            ret = qio_channel_read_all_eof(p->c, (void *)p->packet,
-                                           p->packet_len, &local_err);
+            ret = qio_channel_read_all_eof(p->c, (void *)&hdr,
+                                           sizeof(hdr), &local_err);
+            if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
+                break;
+            }
+
+            ret = multifd_recv_unfill_packet_header(p, &hdr, &local_err);
+            if (ret) {
+                break;
+            }
+
+            is_device_state = p->flags & MULTIFD_FLAG_DEVICE_STATE;
+            if (is_device_state) {
+                pkt_buf = (uint8_t *)p->packet_dev_state + sizeof(hdr);
+                pkt_len = sizeof(*p->packet_dev_state) - sizeof(hdr);
+            } else {
+                pkt_buf = (uint8_t *)p->packet + sizeof(hdr);
+                pkt_len = p->packet_len - sizeof(hdr);
+            }
+
+            ret = qio_channel_read_all_eof(p->c, (char *)pkt_buf, pkt_len,
+                                           &local_err);
             if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
                 break;
             }
@@ -1181,8 +1239,33 @@ static void *multifd_recv_thread(void *opaque)
             has_data = !!p->data->size;
         }
 
-        if (has_data) {
-            ret = multifd_recv_state->ops->recv(p, &local_err);
+        if (!is_device_state) {
+            if (has_data) {
+                ret = multifd_recv_state->ops->recv(p, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }
+        } else {
+            g_autofree char *idstr = NULL;
+            g_autofree char *dev_state_buf = NULL;
+
+            assert(use_packets);
+
+            if (p->next_packet_size > 0) {
+                dev_state_buf = g_malloc(p->next_packet_size);
+
+                ret = qio_channel_read_all(p->c, dev_state_buf, p->next_packet_size, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }
+
+            idstr = g_strndup(p->packet_dev_state->idstr, sizeof(p->packet_dev_state->idstr));
+            ret = qemu_loadvm_load_state_buffer(idstr,
+                                                p->packet_dev_state->instance_id,
+                                                dev_state_buf, p->next_packet_size,
+                                                &local_err);
             if (ret != 0) {
                 break;
             }
@@ -1190,6 +1273,11 @@ static void *multifd_recv_thread(void *opaque)
 
         if (use_packets) {
             if (flags & MULTIFD_FLAG_SYNC) {
+                if (is_device_state) {
+                    error_setg(&local_err, "multifd: received SYNC device state packet");
+                    break;
+                }
+
                 qemu_sem_post(&multifd_recv_state->sem_sync);
                 qemu_sem_wait(&p->sem_sync);
             }
@@ -1258,6 +1346,7 @@ int multifd_recv_setup(Error **errp)
             p->packet_len = sizeof(MultiFDPacket_t)
                 + sizeof(uint64_t) * page_count;
             p->packet = g_malloc0(p->packet_len);
+            p->packet_dev_state = g_malloc0(sizeof(*p->packet_dev_state));
         }
         p->name = g_strdup_printf("mig/dst/recv_%d", i);
         p->normal = g_new0(ram_addr_t, page_count);
migration/multifd.h +30 -1
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
 #define MULTIFD_FLAG_QPL (4 << 1)
 #define MULTIFD_FLAG_UADK (8 << 1)
 
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)
+
 /* This value needs to be a multiple of qemu_target_page_size() */
 #define MULTIFD_PACKET_SIZE (512 * 1024)
 
@@ -52,6 +58,11 @@ typedef struct {
     uint32_t magic;
     uint32_t version;
     uint32_t flags;
+} __attribute__((packed)) MultiFDPacketHdr_t;
+
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
     /* maximum number of allocated pages */
     uint32_t pages_alloc;
     /* non zero pages */
@@ -72,6 +83,16 @@ typedef struct {
     uint64_t offset[];
 } __attribute__((packed)) MultiFDPacket_t;
 
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
+    char idstr[256] QEMU_NONSTRING;
+    uint32_t instance_id;
+
+    /* size of the next packet that contains the actual data */
+    uint32_t next_packet_size;
+} __attribute__((packed)) MultiFDPacketDeviceState_t;
+
 typedef struct {
     /* number of used pages */
     uint32_t num;
@@ -89,6 +110,13 @@ struct MultiFDRecvData {
     off_t file_offset;
 };
 
+typedef struct {
+    char *idstr;
+    uint32_t instance_id;
+    char *buf;
+    size_t buf_len;
+} MultiFDDeviceState_t;
+
 typedef enum {
     MULTIFD_PAYLOAD_NONE,
     MULTIFD_PAYLOAD_RAM,
@@ -204,8 +232,9 @@ typedef struct {
 
     /* thread local variables. No locking required */
 
-    /* pointer to the packet */
+    /* pointers to the possible packet types */
     MultiFDPacket_t *packet;
+    MultiFDPacketDeviceState_t *packet_dev_state;
     /* size of the next packet that contains pages */
     uint32_t next_packet_size;
     /* packets received through this channel */
#62 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

Quoted 167 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
 migration/multifd.c | 127 +++++++++++++++++++++++++++++++++++++-------
 migration/multifd.h |  31 ++++++++++-
 2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +62 -17
index b06a9fab500e..d5a8e5a9c9b5 100644
@@ -21,6 +21,7 @@
 #include "file.h"
 #include "migration.h"
 #include "migration-stats.h"
+#include "savevm.h"
 #include "socket.h"
 #include "tls.h"
 #include "qemu-file.h"
@@ -209,10 +210,10 @@ void multifd_send_fill_packet(MultiFDSendParams *p)
 
     memset(packet, 0, p->packet_len);
 
-    packet->magic = cpu_to_be32(MULTIFD_MAGIC);
-    packet->version = cpu_to_be32(MULTIFD_VERSION);
+    packet->hdr.magic = cpu_to_be32(MULTIFD_MAGIC);
+    packet->hdr.version = cpu_to_be32(MULTIFD_VERSION);
 
-    packet->flags = cpu_to_be32(p->flags);
+    packet->hdr.flags = cpu_to_be32(p->flags);
     packet->next_packet_size = cpu_to_be32(p->next_packet_size);
 
     packet_num = qatomic_fetch_inc(&multifd_send_state->packet_num);
@@ -228,31 +229,49 @@ void multifd_send_fill_packet(MultiFDSendParams *p)
                             p->flags, p->next_packet_size);
 }
 
-static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
+static int multifd_recv_unfill_packet_header(MultiFDRecvParams *p,
+                                             MultiFDPacketHdr_t *hdr,
+                                             Error **errp)
 {
-    MultiFDPacket_t *packet = p->packet;
-    int ret = 0;
-
-    packet->magic = be32_to_cpu(packet->magic);
-    if (packet->magic != MULTIFD_MAGIC) {
+    hdr->magic = be32_to_cpu(hdr->magic);
+    if (hdr->magic != MULTIFD_MAGIC) {
         error_setg(errp, "multifd: received packet "
                    "magic %x and expected magic %x",
-                   packet->magic, MULTIFD_MAGIC);
+                   hdr->magic, MULTIFD_MAGIC);
         return -1;
     }
 
-    packet->version = be32_to_cpu(packet->version);
-    if (packet->version != MULTIFD_VERSION) {
+    hdr->version = be32_to_cpu(hdr->version);
+    if (hdr->version != MULTIFD_VERSION) {
         error_setg(errp, "multifd: received packet "
                    "version %u and expected version %u",
-                   packet->version, MULTIFD_VERSION);
+                   hdr->version, MULTIFD_VERSION);
         return -1;
     }
 
-    p->flags = be32_to_cpu(packet->flags);
+    p->flags = be32_to_cpu(hdr->flags);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_device_state(MultiFDRecvParams *p,
+                                                   Error **errp)
+{
+    MultiFDPacketDeviceState_t *packet = p->packet_dev_state;
+
+    packet->instance_id = be32_to_cpu(packet->instance_id);
+    p->next_packet_size = be32_to_cpu(packet->next_packet_size);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_ram(MultiFDRecvParams *p, Error **errp)
+{
+    MultiFDPacket_t *packet = p->packet;
+    int ret = 0;
+
     p->next_packet_size = be32_to_cpu(packet->next_packet_size);
     p->packet_num = be64_to_cpu(packet->packet_num);
-    p->packets_recved++;
 
     if (!(p->flags & MULTIFD_FLAG_SYNC)) {
         ret = multifd_ram_unfill_packet(p, errp);
@@ -264,6 +283,19 @@ static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
     return ret;
 }
 
+static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
+{
+    p->packets_recved++;
+
+    if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
+        return multifd_recv_unfill_packet_device_state(p, errp);
+    } else {
+        return multifd_recv_unfill_packet_ram(p, errp);
+    }
+
+    g_assert_not_reached();
+}
+
 static bool multifd_send_should_exit(void)
 {
     return qatomic_read(&multifd_send_state->exiting);
@@ -1014,6 +1046,7 @@ static void multifd_recv_cleanup_channel(MultiFDRecvParams *p)
     p->packet_len = 0;
     g_free(p->packet);
     p->packet = NULL;
+    g_clear_pointer(&p->packet_dev_state, g_free);
     g_free(p->normal);
     p->normal = NULL;
     g_free(p->zero);
@@ -1126,8 +1159,13 @@ static void *multifd_recv_thread(void *opaque)
     rcu_register_thread();
 
     while (true) {
+        MultiFDPacketHdr_t hdr;
         uint32_t flags = 0;
+        bool is_device_state = false;
         bool has_data = false;
+        uint8_t *pkt_buf;
+        size_t pkt_len;
+
         p->normal_num = 0;
 
         if (use_packets) {
@@ -1135,8 +1173,28 @@ static void *multifd_recv_thread(void *opaque)
                 break;
             }
 
-            ret = qio_channel_read_all_eof(p->c, (void *)p->packet,
-                                           p->packet_len, &local_err);
+            ret = qio_channel_read_all_eof(p->c, (void *)&hdr,
+                                           sizeof(hdr), &local_err);
+            if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
+                break;
+            }
+
+            ret = multifd_recv_unfill_packet_header(p, &hdr, &local_err);
+            if (ret) {
+                break;

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1194

Quoted 10 lines
migration/multifd.c +10 -0
+            }
+
+            is_device_state = p->flags & MULTIFD_FLAG_DEVICE_STATE;
+            if (is_device_state) {
+                pkt_buf = (uint8_t *)p->packet_dev_state + sizeof(hdr);
+                pkt_len = sizeof(*p->packet_dev_state) - sizeof(hdr);
+            } else {
+                pkt_buf = (uint8_t *)p->packet + sizeof(hdr);
+                pkt_len = p->packet_len - sizeof(hdr);
+            }

Should we have made the packet an union as well? Would simplify these sorts of operations. Not sure I want to start messing with that at this point to be honest. But OTOH, look at this...

Quoted 23 lines
migration/multifd.c +14 -2
+
+            ret = qio_channel_read_all_eof(p->c, (char *)pkt_buf, pkt_len,
+                                           &local_err);
             if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
                 break;
             }
@@ -1181,8 +1239,33 @@ static void *multifd_recv_thread(void *opaque)
             has_data = !!p->data->size;
         }
 
-        if (has_data) {
-            ret = multifd_recv_state->ops->recv(p, &local_err);
+        if (!is_device_state) {
+            if (has_data) {
+                ret = multifd_recv_state->ops->recv(p, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }
+        } else {
+            g_autofree char *idstr = NULL;
+            g_autofree char *dev_state_buf = NULL;
+

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1262

Quoted 10 lines
migration/multifd.c +10 -0
+            assert(use_packets);
+
+            if (p->next_packet_size > 0) {
+                dev_state_buf = g_malloc(p->next_packet_size);
+
+                ret = qio_channel_read_all(p->c, dev_state_buf, p->next_packet_size, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }

What's the use case for !next_packet_size and still call load_state_buffer below? I can't see it.

...because I would suggest to set has_data up there with p->next_packet_size:

if (use_packets) {
...
has_data = p->next_packet_size || p->zero_num;
} else {
...
has_data = !!p->data_size;
}

and this whole block would be:

if (has_data) {

   if (is_device_state) {
       multifd_device_state_recv(p, &local_err);
   } else {
       ret = multifd_recv_state->ops->recv(p, &local_err);

}
}

Quoted 10 lines
migration/multifd.c +6 -0
+
+            idstr = g_strndup(p->packet_dev_state->idstr, sizeof(p->packet_dev_state->idstr));
+            ret = qemu_loadvm_load_state_buffer(idstr,
+                                                p->packet_dev_state->instance_id,
+                                                dev_state_buf, p->next_packet_size,
+                                                &local_err);
             if (ret != 0) {
                 break;
             }

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1279

Quoted 7 lines
migration/multifd.c +4 -0
@@ -1190,6 +1273,11 @@ static void *multifd_recv_thread(void *opaque)
 
         if (use_packets) {
             if (flags & MULTIFD_FLAG_SYNC) {
+                if (is_device_state) {
+                    error_setg(&local_err, "multifd: received SYNC device state packet");
+                    break;
+                }

assert(!is_device_state) enough?

Quoted 17 lines
migration/multifd.c +2 -0
+
                 qemu_sem_post(&multifd_recv_state->sem_sync);
                 qemu_sem_wait(&p->sem_sync);
             }
@@ -1258,6 +1346,7 @@ int multifd_recv_setup(Error **errp)
             p->packet_len = sizeof(MultiFDPacket_t)
                 + sizeof(uint64_t) * page_count;
             p->packet = g_malloc0(p->packet_len);
+            p->packet_dev_state = g_malloc0(sizeof(*p->packet_dev_state));
         }
         p->name = g_strdup_printf("mig/dst/recv_%d", i);
         p->normal = g_new0(ram_addr_t, page_count);
migration/multifd.h +0 -0
index a3e35196d179..a8f3e4838c01 100644

migration/multifd.h MultiFDRecvData *multifd_get_recv_data(void); · line 52

Quoted 8 lines
migration/multifd.h +5 -0
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
 #define MULTIFD_FLAG_QPL (4 << 1)
 #define MULTIFD_FLAG_UADK (8 << 1)
 
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)

Overlaps with UADK. I assume on purpose because device_state doesn't support compression? Might be worth a comment.

Quoted 58 lines
migration/multifd.h +25 -1
+
 /* This value needs to be a multiple of qemu_target_page_size() */
 #define MULTIFD_PACKET_SIZE (512 * 1024)
 
@@ -52,6 +58,11 @@ typedef struct {
     uint32_t magic;
     uint32_t version;
     uint32_t flags;
+} __attribute__((packed)) MultiFDPacketHdr_t;
+
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
     /* maximum number of allocated pages */
     uint32_t pages_alloc;
     /* non zero pages */
@@ -72,6 +83,16 @@ typedef struct {
     uint64_t offset[];
 } __attribute__((packed)) MultiFDPacket_t;
 
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
+    char idstr[256] QEMU_NONSTRING;
+    uint32_t instance_id;
+
+    /* size of the next packet that contains the actual data */
+    uint32_t next_packet_size;
+} __attribute__((packed)) MultiFDPacketDeviceState_t;
+
 typedef struct {
     /* number of used pages */
     uint32_t num;
@@ -89,6 +110,13 @@ struct MultiFDRecvData {
     off_t file_offset;
 };
 
+typedef struct {
+    char *idstr;
+    uint32_t instance_id;
+    char *buf;
+    size_t buf_len;
+} MultiFDDeviceState_t;
+
 typedef enum {
     MULTIFD_PAYLOAD_NONE,
     MULTIFD_PAYLOAD_RAM,
@@ -204,8 +232,9 @@ typedef struct {
 
     /* thread local variables. No locking required */
 
-    /* pointer to the packet */
+    /* pointers to the possible packet types */
     MultiFDPacket_t *packet;
+    MultiFDPacketDeviceState_t *packet_dev_state;
     /* size of the next packet that contains pages */
     uint32_t next_packet_size;
     /* packets received through this channel */
#63 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

Quoted 28 lines · Fabiano Rosas
Quoted 26 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
  migration/multifd.c | 127 +++++++++++++++++++++++++++++++++++++-------
  migration/multifd.h |  31 ++++++++++-
  2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +0 -0
index b06a9fab500e..d5a8e5a9c9b5 100644

(..)

Quoted 36 lines
Quoted 36 lines
      g_free(p->zero);
migration/multifd.c +20 -2
@@ -1126,8 +1159,13 @@ static void *multifd_recv_thread(void *opaque)
      rcu_register_thread();
 
      while (true) {
+        MultiFDPacketHdr_t hdr;
          uint32_t flags = 0;
+        bool is_device_state = false;
          bool has_data = false;
+        uint8_t *pkt_buf;
+        size_t pkt_len;
+
          p->normal_num = 0;
 
          if (use_packets) {
@@ -1135,8 +1173,28 @@ static void *multifd_recv_thread(void *opaque)
                  break;
              }
 
-            ret = qio_channel_read_all_eof(p->c, (void *)p->packet,
-                                           p->packet_len, &local_err);
+            ret = qio_channel_read_all_eof(p->c, (void *)&hdr,
+                                           sizeof(hdr), &local_err);
+            if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
+                break;
+            }
+
+            ret = multifd_recv_unfill_packet_header(p, &hdr, &local_err);
+            if (ret) {
+                break;
+            }
+
+            is_device_state = p->flags & MULTIFD_FLAG_DEVICE_STATE;
+            if (is_device_state) {
+                pkt_buf = (uint8_t *)p->packet_dev_state + sizeof(hdr);
+                pkt_len = sizeof(*p->packet_dev_state) - sizeof(hdr);
Quoted 8 lines

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1194

Quoted 4 lines
migration/multifd.c +4 -0
+            } else {
+                pkt_buf = (uint8_t *)p->packet + sizeof(hdr);
+                pkt_len = p->packet_len - sizeof(hdr);
+            }

Should we have made the packet an union as well? Would simplify these sorts of operations. Not sure I want to start messing with that at this point to be honest. But OTOH, look at this...

RAM packet length is not constant (at least from the viewpoint of the migration code) so the union allocation would need some kind of a "multifd_ram_packet_size()" runtime size determination.

Also, since RAM and device state packet body size is different then for the extra complexity introduced by that union we'll just get rid of that single pkt_buf assignment.

Quoted 28 lines
Quoted 28 lines
migration/multifd.c +19 -2
+
+            ret = qio_channel_read_all_eof(p->c, (char *)pkt_buf, pkt_len,
+                                           &local_err);
              if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
                  break;
              }
@@ -1181,8 +1239,33 @@ static void *multifd_recv_thread(void *opaque)
              has_data = !!p->data->size;
          }
 
-        if (has_data) {
-            ret = multifd_recv_state->ops->recv(p, &local_err);
+        if (!is_device_state) {
+            if (has_data) {
+                ret = multifd_recv_state->ops->recv(p, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }
+        } else {
+            g_autofree char *idstr = NULL;
+            g_autofree char *dev_state_buf = NULL;
+
+            assert(use_packets);
+
+            if (p->next_packet_size > 0) {
+                dev_state_buf = g_malloc(p->next_packet_size);
+
Quoted 8 lines

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1262

Quoted 5 lines
migration/multifd.c +5 -0
+                ret = qio_channel_read_all(p->c, dev_state_buf, p->next_packet_size, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }

What's the use case for !next_packet_size and still call load_state_buffer below? I can't see it.

Currently, next_packet_size == 0 has not usage indeed - it is a leftover from an early version of the patch set (not public) that had device state packet (chunk) indexing done by the common migration code, rather than by the VFIO consumer.

And then an empty packet could be used to mark the stream boundary - like the max chunk number to expect.

Quoted 13 lines

...because I would suggest to set has_data up there with p->next_packet_size:

if (use_packets) {
    ...
    has_data = p->next_packet_size || p->zero_num;
} else {
    ...
    has_data = !!p->data_size;
}

and this whole block would be:

Quoted 7 lines
if (has_data) {
    if (is_device_state) {
        multifd_device_state_recv(p, &local_err);
    } else {
        ret = multifd_recv_state->ops->recv(p, &local_err);
    }
}

The above block makes sense to me with two caveats:
1) If empty device state packets (next_packet_size == 0) were to be unsupported they need to be rejected cleanly rather than silently skipped,

2) has_data has to have its value computed depending on whether this is a RAM or a device state packet since looking at p->normal_num and p->zero_num makes no sense for a device state packet while I am not sure that looking at p->next_packet_size for a RAM packet won't introduce some subtle regression.

Quoted 11 lines
Quoted 11 lines
migration/multifd.c +6 -0
+
+            idstr = g_strndup(p->packet_dev_state->idstr, sizeof(p->packet_dev_state->idstr));
+            ret = qemu_loadvm_load_state_buffer(idstr,
+                                                p->packet_dev_state->instance_id,
+                                                dev_state_buf, p->next_packet_size,
+                                                &local_err);
              if (ret != 0) {
                  break;
              }
@@ -1190,6 +1273,11 @@ static void *multifd_recv_thread(void *opaque)
 
Quoted 8 lines

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1279

Quoted 6 lines
migration/multifd.c +4 -0
          if (use_packets) {
              if (flags & MULTIFD_FLAG_SYNC) {
+                if (is_device_state) {
+                    error_setg(&local_err, "multifd: received SYNC device state packet");
+                    break;
+                }

assert(!is_device_state) enough?

It's not bug in the receiver code but rather an issue with the remote QEMU sending us wrong data if we get a SYNC device state packet.

So I think returning an error is more appropriate than triggering an assert() failure for that.

Quoted 20 lines
Quoted 20 lines
migration/multifd.c +2 -0
+
                  qemu_sem_post(&multifd_recv_state->sem_sync);
                  qemu_sem_wait(&p->sem_sync);
              }
@@ -1258,6 +1346,7 @@ int multifd_recv_setup(Error **errp)
              p->packet_len = sizeof(MultiFDPacket_t)
                  + sizeof(uint64_t) * page_count;
              p->packet = g_malloc0(p->packet_len);
+            p->packet_dev_state = g_malloc0(sizeof(*p->packet_dev_state));
          }
          p->name = g_strdup_printf("mig/dst/recv_%d", i);
          p->normal = g_new0(ram_addr_t, page_count);
migration/multifd.h +0 -0
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
  #define MULTIFD_FLAG_QPL (4 << 1)
  #define MULTIFD_FLAG_UADK (8 << 1)
 
Quoted 9 lines

migration/multifd.h MultiFDRecvData *multifd_get_recv_data(void); · line 52

Quoted 5 lines
migration/multifd.h +5 -0
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)

Overlaps with UADK. I assume on purpose because device_state doesn't support compression? Might be worth a comment.

Yes, the device state transfer bit stream does not support compression so it is not a problem since these "compression type" flags will never be set in such bit stream anyway.

Will add a relevant comment here.

Thanks,
Maciej

#64 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

Quoted 149 lines · Maciej S. Szmigiero
Quoted 28 lines · Fabiano Rosas
Quoted 26 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
  migration/multifd.c | 127 +++++++++++++++++++++++++++++++++++++-------
  migration/multifd.h |  31 ++++++++++-
  2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +0 -0
index b06a9fab500e..d5a8e5a9c9b5 100644

(..)

Quoted 36 lines
Quoted 36 lines
      g_free(p->zero);
migration/multifd.c +20 -2
@@ -1126,8 +1159,13 @@ static void *multifd_recv_thread(void *opaque)
      rcu_register_thread();
 
      while (true) {
+        MultiFDPacketHdr_t hdr;
          uint32_t flags = 0;
+        bool is_device_state = false;
          bool has_data = false;
+        uint8_t *pkt_buf;
+        size_t pkt_len;
+
          p->normal_num = 0;
 
          if (use_packets) {
@@ -1135,8 +1173,28 @@ static void *multifd_recv_thread(void *opaque)
                  break;
              }
 
-            ret = qio_channel_read_all_eof(p->c, (void *)p->packet,
-                                           p->packet_len, &local_err);
+            ret = qio_channel_read_all_eof(p->c, (void *)&hdr,
+                                           sizeof(hdr), &local_err);
+            if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
+                break;
+            }
+
+            ret = multifd_recv_unfill_packet_header(p, &hdr, &local_err);
+            if (ret) {
+                break;
+            }
+
+            is_device_state = p->flags & MULTIFD_FLAG_DEVICE_STATE;
+            if (is_device_state) {
+                pkt_buf = (uint8_t *)p->packet_dev_state + sizeof(hdr);
+                pkt_len = sizeof(*p->packet_dev_state) - sizeof(hdr);
Quoted 8 lines

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1194

Quoted 4 lines
migration/multifd.c +4 -0
+            } else {
+                pkt_buf = (uint8_t *)p->packet + sizeof(hdr);
+                pkt_len = p->packet_len - sizeof(hdr);
+            }

Should we have made the packet an union as well? Would simplify these sorts of operations. Not sure I want to start messing with that at this point to be honest. But OTOH, look at this...

RAM packet length is not constant (at least from the viewpoint of the migration code) so the union allocation would need some kind of a "multifd_ram_packet_size()" runtime size determination.

Also, since RAM and device state packet body size is different then for the extra complexity introduced by that union we'll just get rid of that single pkt_buf assignment.

Quoted 28 lines
Quoted 28 lines
migration/multifd.c +19 -2
+
+            ret = qio_channel_read_all_eof(p->c, (char *)pkt_buf, pkt_len,
+                                           &local_err);
              if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
                  break;
              }
@@ -1181,8 +1239,33 @@ static void *multifd_recv_thread(void *opaque)
              has_data = !!p->data->size;
          }
 
-        if (has_data) {
-            ret = multifd_recv_state->ops->recv(p, &local_err);
+        if (!is_device_state) {
+            if (has_data) {
+                ret = multifd_recv_state->ops->recv(p, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }
+        } else {
+            g_autofree char *idstr = NULL;
+            g_autofree char *dev_state_buf = NULL;
+
+            assert(use_packets);
+
+            if (p->next_packet_size > 0) {
+                dev_state_buf = g_malloc(p->next_packet_size);
+
Quoted 8 lines

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1262

Quoted 5 lines
migration/multifd.c +5 -0
+                ret = qio_channel_read_all(p->c, dev_state_buf, p->next_packet_size, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }

What's the use case for !next_packet_size and still call load_state_buffer below? I can't see it.

Currently, next_packet_size == 0 has not usage indeed - it is a leftover from an early version of the patch set (not public) that had device state packet (chunk) indexing done by the common migration code, rather than by the VFIO consumer.

And then an empty packet could be used to mark the stream boundary - like the max chunk number to expect.

Quoted 13 lines

...because I would suggest to set has_data up there with p->next_packet_size:

if (use_packets) {
    ...
    has_data = p->next_packet_size || p->zero_num;
} else {
    ...
    has_data = !!p->data_size;
}

and this whole block would be:

Quoted 7 lines
if (has_data) {
    if (is_device_state) {
        multifd_device_state_recv(p, &local_err);
    } else {
        ret = multifd_recv_state->ops->recv(p, &local_err);
    }
}
Quoted 1 line

The above block makes sense to me with two caveats:

I have suggestions below, but this is no big deal, so feel free to go with what you think works best.

Quoted 3 lines

1) If empty device state packets (next_packet_size == 0) were to be unsupported they need to be rejected cleanly rather than silently skipped,

Should this be rejected on the send side? That's the most likely source of the problem if it happens. Don't need to send something we know will cause an error when loading.

And for the case of stream corruption of some sort we could hoist the check from load_buffer into here:

 else if (is_device_state) {
    error_setg(errp, "empty device state packet);
    break;
}
Quoted 5 lines

2) has_data has to have its value computed depending on whether this is a RAM or a device state packet since looking at p->normal_num and p->zero_num makes no sense for a device state packet while I am not sure that looking at p->next_packet_size for a RAM packet won't introduce some subtle regression.

It should be ok to use next_packet_size for RAM, it must always be in sync with normal_num.

Quoted 21 lines
Quoted 12 lines
Quoted 12 lines
migration/multifd.c +6 -0
+
+            idstr = g_strndup(p->packet_dev_state->idstr, sizeof(p->packet_dev_state->idstr));
+            ret = qemu_loadvm_load_state_buffer(idstr,
+                                                p->packet_dev_state->instance_id,
+                                                dev_state_buf, p->next_packet_size,
+                                                &local_err);
              if (ret != 0) {
                  break;
              }
@@ -1190,6 +1273,11 @@ static void *multifd_recv_thread(void *opaque)
 
Quoted 8 lines

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1279

Quoted 6 lines
migration/multifd.c +4 -0
          if (use_packets) {
              if (flags & MULTIFD_FLAG_SYNC) {
+                if (is_device_state) {
+                    error_setg(&local_err, "multifd: received SYNC device state packet");
+                    break;
+                }

assert(!is_device_state) enough?

Quoted 6 lines

It's not bug in the receiver code but rather an issue with the remote QEMU sending us wrong data if we get a SYNC device state packet.

So I think returning an error is more appropriate than triggering an assert() failure for that.

ok

Quoted 38 lines
Quoted 20 lines
Quoted 20 lines
migration/multifd.c +2 -0
+
                  qemu_sem_post(&multifd_recv_state->sem_sync);
                  qemu_sem_wait(&p->sem_sync);
              }
@@ -1258,6 +1346,7 @@ int multifd_recv_setup(Error **errp)
              p->packet_len = sizeof(MultiFDPacket_t)
                  + sizeof(uint64_t) * page_count;
              p->packet = g_malloc0(p->packet_len);
+            p->packet_dev_state = g_malloc0(sizeof(*p->packet_dev_state));
          }
          p->name = g_strdup_printf("mig/dst/recv_%d", i);
          p->normal = g_new0(ram_addr_t, page_count);
migration/multifd.h +0 -0
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
  #define MULTIFD_FLAG_QPL (4 << 1)
  #define MULTIFD_FLAG_UADK (8 << 1)
 
Quoted 9 lines

migration/multifd.h MultiFDRecvData *multifd_get_recv_data(void); · line 52

Quoted 5 lines
migration/multifd.h +5 -0
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)

Overlaps with UADK. I assume on purpose because device_state doesn't support compression? Might be worth a comment.

Yes, the device state transfer bit stream does not support compression so it is not a problem since these "compression type" flags will never be set in such bit stream anyway.

Will add a relevant comment here.

Thanks,
Maciej

#65 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

Quoted 31 lines · Fabiano Rosas
Quoted 29 lines · Maciej S. Szmigiero
Quoted 28 lines · Fabiano Rosas
Quoted 26 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
   migration/multifd.c | 127 +++++++++++++++++++++++++++++++++++++-------
   migration/multifd.h |  31 ++++++++++-
   2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +0 -0
index b06a9fab500e..d5a8e5a9c9b5 100644

(..)

Quoted 71 lines
Quoted 66 lines
Quoted 28 lines
Quoted 28 lines
migration/multifd.c +19 -2
+
+            ret = qio_channel_read_all_eof(p->c, (char *)pkt_buf, pkt_len,
+                                           &local_err);
               if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
                   break;
               }
@@ -1181,8 +1239,33 @@ static void *multifd_recv_thread(void *opaque)
               has_data = !!p->data->size;
           }
 
-        if (has_data) {
-            ret = multifd_recv_state->ops->recv(p, &local_err);
+        if (!is_device_state) {
+            if (has_data) {
+                ret = multifd_recv_state->ops->recv(p, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }
+        } else {
+            g_autofree char *idstr = NULL;
+            g_autofree char *dev_state_buf = NULL;
+
+            assert(use_packets);
+
+            if (p->next_packet_size > 0) {
+                dev_state_buf = g_malloc(p->next_packet_size);
+
Quoted 8 lines

migration/multifd.c static void *multifd_recv_thread(void *opaque) · line 1262

Quoted 5 lines
migration/multifd.c +5 -0
+                ret = qio_channel_read_all(p->c, dev_state_buf, p->next_packet_size, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }

What's the use case for !next_packet_size and still call load_state_buffer below? I can't see it.

Currently, next_packet_size == 0 has not usage indeed - it is a leftover from an early version of the patch set (not public) that had device state packet (chunk) indexing done by the common migration code, rather than by the VFIO consumer.

And then an empty packet could be used to mark the stream boundary - like the max chunk number to expect.

Quoted 13 lines

...because I would suggest to set has_data up there with p->next_packet_size:

if (use_packets) {
     ...
     has_data = p->next_packet_size || p->zero_num;
} else {
     ...
     has_data = !!p->data_size;
}

and this whole block would be:

Quoted 7 lines
if (has_data) {
     if (is_device_state) {
         multifd_device_state_recv(p, &local_err);
     } else {
         ret = multifd_recv_state->ops->recv(p, &local_err);
     }
}
Quoted 1 line

The above block makes sense to me with two caveats:

I have suggestions below, but this is no big deal, so feel free to go with what you think works best.

Quoted 7 lines
Quoted 3 lines

1) If empty device state packets (next_packet_size == 0) were to be unsupported they need to be rejected cleanly rather than silently skipped,

Should this be rejected on the send side? That's the most likely source of the problem if it happens. Don't need to send something we know will cause an error when loading.

Definitely we should send correct bit stream :), it was about the case of bit stream corruption or simply using some future bit stream format that the QEMU version with this patch set does not understand yet.

Quoted 7 lines

And for the case of stream corruption of some sort we could hoist the check from load_buffer into here:

  else if (is_device_state) {
     error_setg(errp, "empty device state packet);
     break;
}

Right.

Quoted 8 lines
Quoted 5 lines

2) has_data has to have its value computed depending on whether this is a RAM or a device state packet since looking at p->normal_num and p->zero_num makes no sense for a device state packet while I am not sure that looking at p->next_packet_size for a RAM packet won't introduce some subtle regression.

It should be ok to use next_packet_size for RAM, it must always be in sync with normal_num.

Then it should be ok, but I'll look at this deeper to be sure when I will be preparing the next patch set version.

Thanks,
Maciej

#66 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

In reply to Maciej S. Szmigiero
Quoted 17 lines · Maciej S. Szmigiero
Quoted 7 lines
Quoted 7 lines
migration/multifd.h +0 -0
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
  #define MULTIFD_FLAG_QPL (4 << 1)
  #define MULTIFD_FLAG_UADK (8 << 1)
Quoted 9 lines

migration/multifd.h MultiFDRecvData *multifd_get_recv_data(void); · line 52

Quoted 5 lines
migration/multifd.h +5 -0
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)

Overlaps with UADK. I assume on purpose because device_state doesn't support compression? Might be worth a comment.

Quoted 5 lines

Yes, the device state transfer bit stream does not support compression so it is not a problem since these "compression type" flags will never be set in such bit stream anyway.

Will add a relevant comment here.

Why reuse? Would using a new bit easier if we still have plenty of bits (just to tell what is what directly from a stream dump)?

Signature · 1 line
Peter Xu
#67 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

Quoted 18 lines · Peter Xu
Quoted 17 lines · Maciej S. Szmigiero
Quoted 16 lines

migration/multifd.h MultiFDRecvData *multifd_get_recv_data(void); · line 51

Quoted 12 lines
migration/multifd.h +5 -0
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
   #define MULTIFD_FLAG_QPL (4 << 1)
   #define MULTIFD_FLAG_UADK (8 << 1)
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)

Overlaps with UADK. I assume on purpose because device_state doesn't support compression? Might be worth a comment.

Quoted 9 lines
Quoted 5 lines

Yes, the device state transfer bit stream does not support compression so it is not a problem since these "compression type" flags will never be set in such bit stream anyway.

Will add a relevant comment here.

Why reuse? Would using a new bit easier if we still have plenty of bits (just to tell what is what directly from a stream dump)?

Will move that flag to the next unique bit then.

Thanks,
Maciej

#68 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

In reply to Maciej S. Szmigiero
Quoted 118 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
  migration/multifd.c | 127 +++++++++++++++++++++++++++++++++++++-------
  migration/multifd.h |  31 ++++++++++-
  2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +35 -15
index b06a9fab500e..d5a8e5a9c9b5 100644
@@ -21,6 +21,7 @@
  #include "file.h"
  #include "migration.h"
  #include "migration-stats.h"
+#include "savevm.h"
  #include "socket.h"
  #include "tls.h"
  #include "qemu-file.h"
@@ -209,10 +210,10 @@ void multifd_send_fill_packet(MultiFDSendParams *p)
 
      memset(packet, 0, p->packet_len);
 
-    packet->magic = cpu_to_be32(MULTIFD_MAGIC);
-    packet->version = cpu_to_be32(MULTIFD_VERSION);
+    packet->hdr.magic = cpu_to_be32(MULTIFD_MAGIC);
+    packet->hdr.version = cpu_to_be32(MULTIFD_VERSION);
 
-    packet->flags = cpu_to_be32(p->flags);
+    packet->hdr.flags = cpu_to_be32(p->flags);
      packet->next_packet_size = cpu_to_be32(p->next_packet_size);
 
      packet_num = qatomic_fetch_inc(&multifd_send_state->packet_num);
@@ -228,31 +229,49 @@ void multifd_send_fill_packet(MultiFDSendParams *p)
                              p->flags, p->next_packet_size);
  }
 
-static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
+static int multifd_recv_unfill_packet_header(MultiFDRecvParams *p,
+                                             MultiFDPacketHdr_t *hdr,
+                                             Error **errp)
  {
-    MultiFDPacket_t *packet = p->packet;
-    int ret = 0;
-
-    packet->magic = be32_to_cpu(packet->magic);
-    if (packet->magic != MULTIFD_MAGIC) {
+    hdr->magic = be32_to_cpu(hdr->magic);
+    if (hdr->magic != MULTIFD_MAGIC) {
          error_setg(errp, "multifd: received packet "
                     "magic %x and expected magic %x",
-                   packet->magic, MULTIFD_MAGIC);
+                   hdr->magic, MULTIFD_MAGIC);
          return -1;
      }
 
-    packet->version = be32_to_cpu(packet->version);
-    if (packet->version != MULTIFD_VERSION) {
+    hdr->version = be32_to_cpu(hdr->version);
+    if (hdr->version != MULTIFD_VERSION) {
          error_setg(errp, "multifd: received packet "
                     "version %u and expected version %u",
-                   packet->version, MULTIFD_VERSION);
+                   hdr->version, MULTIFD_VERSION);
          return -1;
      }
 
-    p->flags = be32_to_cpu(packet->flags);
+    p->flags = be32_to_cpu(hdr->flags);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_device_state(MultiFDRecvParams *p,
+                                                   Error **errp)
+{
+    MultiFDPacketDeviceState_t *packet = p->packet_dev_state;
+
+    packet->instance_id = be32_to_cpu(packet->instance_id);
+    p->next_packet_size = be32_to_cpu(packet->next_packet_size);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_ram(MultiFDRecvParams *p, Error **errp)
+{
+    MultiFDPacket_t *packet = p->packet;
+    int ret = 0;
+
      p->next_packet_size = be32_to_cpu(packet->next_packet_size);
      p->packet_num = be64_to_cpu(packet->packet_num);
-    p->packets_recved++;
 
      if (!(p->flags & MULTIFD_FLAG_SYNC)) {
          ret = multifd_ram_unfill_packet(p, errp);
@@ -264,6 +283,19 @@ static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
      return ret;
  }
 
+static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)

migration/multifd.c static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp) · line 296

Quoted 10 lines
migration/multifd.c +10 -0
+{
+    p->packets_recved++;
+
+    if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
+        return multifd_recv_unfill_packet_device_state(p, errp);
+    } else {
+        return multifd_recv_unfill_packet_ram(p, errp);
+    }
+
+    g_assert_not_reached();

We can drop the assert and the "else":
if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
    return multifd_recv_unfill_packet_device_state(p, errp); }

return multifd_recv_unfill_packet_ram(p, errp);

Quoted 132 lines
migration/multifd.c +63 -4
+}
+
  static bool multifd_send_should_exit(void)
  {
      return qatomic_read(&multifd_send_state->exiting);
@@ -1014,6 +1046,7 @@ static void multifd_recv_cleanup_channel(MultiFDRecvParams *p)
      p->packet_len = 0;
      g_free(p->packet);
      p->packet = NULL;
+    g_clear_pointer(&p->packet_dev_state, g_free);
      g_free(p->normal);
      p->normal = NULL;
      g_free(p->zero);
@@ -1126,8 +1159,13 @@ static void *multifd_recv_thread(void *opaque)
      rcu_register_thread();
 
      while (true) {
+        MultiFDPacketHdr_t hdr;
          uint32_t flags = 0;
+        bool is_device_state = false;
          bool has_data = false;
+        uint8_t *pkt_buf;
+        size_t pkt_len;
+
          p->normal_num = 0;
 
          if (use_packets) {
@@ -1135,8 +1173,28 @@ static void *multifd_recv_thread(void *opaque)
                  break;
              }
 
-            ret = qio_channel_read_all_eof(p->c, (void *)p->packet,
-                                           p->packet_len, &local_err);
+            ret = qio_channel_read_all_eof(p->c, (void *)&hdr,
+                                           sizeof(hdr), &local_err);
+            if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
+                break;
+            }
+
+            ret = multifd_recv_unfill_packet_header(p, &hdr, &local_err);
+            if (ret) {
+                break;
+            }
+
+            is_device_state = p->flags & MULTIFD_FLAG_DEVICE_STATE;
+            if (is_device_state) {
+                pkt_buf = (uint8_t *)p->packet_dev_state + sizeof(hdr);
+                pkt_len = sizeof(*p->packet_dev_state) - sizeof(hdr);
+            } else {
+                pkt_buf = (uint8_t *)p->packet + sizeof(hdr);
+                pkt_len = p->packet_len - sizeof(hdr);
+            }
+
+            ret = qio_channel_read_all_eof(p->c, (char *)pkt_buf, pkt_len,
+                                           &local_err);
              if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
                  break;
              }
@@ -1181,8 +1239,33 @@ static void *multifd_recv_thread(void *opaque)
              has_data = !!p->data->size;
          }
 
-        if (has_data) {
-            ret = multifd_recv_state->ops->recv(p, &local_err);
+        if (!is_device_state) {
+            if (has_data) {
+                ret = multifd_recv_state->ops->recv(p, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }
+        } else {
+            g_autofree char *idstr = NULL;
+            g_autofree char *dev_state_buf = NULL;
+
+            assert(use_packets);
+
+            if (p->next_packet_size > 0) {
+                dev_state_buf = g_malloc(p->next_packet_size);
+
+                ret = qio_channel_read_all(p->c, dev_state_buf, p->next_packet_size, &local_err);
+                if (ret != 0) {
+                    break;
+                }
+            }
+
+            idstr = g_strndup(p->packet_dev_state->idstr, sizeof(p->packet_dev_state->idstr));
+            ret = qemu_loadvm_load_state_buffer(idstr,
+                                                p->packet_dev_state->instance_id,
+                                                dev_state_buf, p->next_packet_size,
+                                                &local_err);
              if (ret != 0) {
                  break;
              }
@@ -1190,6 +1273,11 @@ static void *multifd_recv_thread(void *opaque)
 
          if (use_packets) {
              if (flags & MULTIFD_FLAG_SYNC) {
+                if (is_device_state) {
+                    error_setg(&local_err, "multifd: received SYNC device state packet");
+                    break;
+                }
+
                  qemu_sem_post(&multifd_recv_state->sem_sync);
                  qemu_sem_wait(&p->sem_sync);
              }
@@ -1258,6 +1346,7 @@ int multifd_recv_setup(Error **errp)
              p->packet_len = sizeof(MultiFDPacket_t)
                  + sizeof(uint64_t) * page_count;
              p->packet = g_malloc0(p->packet_len);
+            p->packet_dev_state = g_malloc0(sizeof(*p->packet_dev_state));
          }
          p->name = g_strdup_printf("mig/dst/recv_%d", i);
          p->normal = g_new0(ram_addr_t, page_count);
migration/multifd.h +6 -0
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
  #define MULTIFD_FLAG_QPL (4 << 1)
  #define MULTIFD_FLAG_UADK (8 << 1)
 
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)
+
  /* This value needs to be a multiple of qemu_target_page_size() */
  #define MULTIFD_PACKET_SIZE (512 * 1024)
 

migration/multifd.h typedef struct { · line 61

Quoted 4 lines
migration/multifd.h +1 -0
@@ -52,6 +58,11 @@ typedef struct {
      uint32_t magic;
      uint32_t version;
      uint32_t flags;
+} __attribute__((packed)) MultiFDPacketHdr_t;

Maybe split this patch into two: one that adds the packet header concept and another that adds the new device packet?

Quoted 8 lines
migration/multifd.h +4 -0
+
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
      /* maximum number of allocated pages */
      uint32_t pages_alloc;
      /* non zero pages */

migration/multifd.h typedef struct { · line 89

Quoted 7 lines
migration/multifd.h +4 -0
@@ -72,6 +83,16 @@ typedef struct {
      uint64_t offset[];
  } __attribute__((packed)) MultiFDPacket_t;
 
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
+    char idstr[256] QEMU_NONSTRING;

idstr should be null terminated, or am I missing something?

Thanks.

Quoted 34 lines
migration/multifd.h +15 -1
+    uint32_t instance_id;
+
+    /* size of the next packet that contains the actual data */
+    uint32_t next_packet_size;
+} __attribute__((packed)) MultiFDPacketDeviceState_t;
+
  typedef struct {
      /* number of used pages */
      uint32_t num;
@@ -89,6 +110,13 @@ struct MultiFDRecvData {
      off_t file_offset;
  };
 
+typedef struct {
+    char *idstr;
+    uint32_t instance_id;
+    char *buf;
+    size_t buf_len;
+} MultiFDDeviceState_t;
+
  typedef enum {
      MULTIFD_PAYLOAD_NONE,
      MULTIFD_PAYLOAD_RAM,
@@ -204,8 +232,9 @@ typedef struct {
 
      /* thread local variables. No locking required */
 
-    /* pointer to the packet */
+    /* pointers to the possible packet types */
      MultiFDPacket_t *packet;
+    MultiFDPacketDeviceState_t *packet_dev_state;
      /* size of the next packet that contains pages */
      uint32_t next_packet_size;
      /* packets received through this channel */
#69 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

Quoted 136 lines · Avihai Horon
Quoted 118 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
  migration/multifd.c | 127 +++++++++++++++++++++++++++++++++++++------- migration/multifd.h |  31 ++++++++++-

  2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +9 -9
index b06a9fab500e..d5a8e5a9c9b5 100644
@@ -21,6 +21,7 @@
   #include "file.h"
   #include "migration.h"
   #include "migration-stats.h"
+#include "savevm.h"
   #include "socket.h"
   #include "tls.h"
   #include "qemu-file.h"
@@ -209,10 +210,10 @@ void multifd_send_fill_packet(MultiFDSendParams *p)
 
       memset(packet, 0, p->packet_len);
 
-    packet->magic = cpu_to_be32(MULTIFD_MAGIC);
-    packet->version = cpu_to_be32(MULTIFD_VERSION);
+    packet->hdr.magic = cpu_to_be32(MULTIFD_MAGIC);
+    packet->hdr.version = cpu_to_be32(MULTIFD_VERSION);
 
-    packet->flags = cpu_to_be32(p->flags);
+    packet->hdr.flags = cpu_to_be32(p->flags);
       packet->next_packet_size = cpu_to_be32(p->next_packet_size);
 
       packet_num = qatomic_fetch_inc(&multifd_send_state->packet_num);
@@ -228,31 +229,49 @@ void multifd_send_fill_packet(MultiFDSendParams *p)
                               p->flags, p->next_packet_size);
   }
 
-static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
+static int multifd_recv_unfill_packet_header(MultiFDRecvParams *p,
+                                             MultiFDPacketHdr_t *hdr,
+                                             Error **errp)
   {
-    MultiFDPacket_t *packet = p->packet;
-    int ret = 0;
-
-    packet->magic = be32_to_cpu(packet->magic);
-    if (packet->magic != MULTIFD_MAGIC) {
+    hdr->magic = be32_to_cpu(hdr->magic);
+    if (hdr->magic != MULTIFD_MAGIC) {

          error_setg(errp, "multifd: received packet " "magic %x and expected magic %x", -                   packet->magic, MULTIFD_MAGIC); +                   hdr->magic, MULTIFD_MAGIC); return -1;
      }

-    packet->version = be32_to_cpu(packet->version); -    if (packet->version != MULTIFD_VERSION) {
+    hdr->version = be32_to_cpu(hdr->version);
+    if (hdr->version != MULTIFD_VERSION) { error_setg(errp, "multifd: received packet " "version %u and expected version %u", -                   packet->version, MULTIFD_VERSION); +                   hdr->version, MULTIFD_VERSION); return -1;
      }

-    p->flags = be32_to_cpu(packet->flags);
+    p->flags = be32_to_cpu(hdr->flags);

migration/multifd.c +20 -0
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_device_state(MultiFDRecvParams *p,
+                                                   Error **errp)
+{
+    MultiFDPacketDeviceState_t *packet = p->packet_dev_state;
+
+    packet->instance_id = be32_to_cpu(packet->instance_id);
+    p->next_packet_size = be32_to_cpu(packet->next_packet_size);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_ram(MultiFDRecvParams *p, Error **errp)
+{
+    MultiFDPacket_t *packet = p->packet;
+    int ret = 0;
+

      p->next_packet_size = be32_to_cpu(packet->next_packet_size); p->packet_num = be64_to_cpu(packet->packet_num); -    p->packets_recved++;

      if (!(p->flags & MULTIFD_FLAG_SYNC)) { ret = multifd_ram_unfill_packet(p, errp);

migration/multifd.c +1 -0
@@ -264,6 +283,19 @@ static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
       return ret;
   }
 
+static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)

migration/multifd.c static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp) · line 296

Quoted 10 lines
migration/multifd.c +10 -0
+{
+    p->packets_recved++;
+
+    if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
+        return multifd_recv_unfill_packet_device_state(p, errp);
+    } else {
+        return multifd_recv_unfill_packet_ram(p, errp);
+    }
+
+    g_assert_not_reached();

We can drop the assert and the "else":
if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
    return multifd_recv_unfill_packet_device_state(p, errp);
}

Quoted 1 line

return multifd_recv_unfill_packet_ram(p, errp);

Ack.

Quoted 22 lines
Quoted 22 lines
migration/multifd.c +2 -0
+}
+
   static bool multifd_send_should_exit(void)
   {
       return qatomic_read(&multifd_send_state->exiting);
migration/multifd.h +6 -0
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
   #define MULTIFD_FLAG_QPL (4 << 1)
   #define MULTIFD_FLAG_UADK (8 << 1)
 
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)
+
   /* This value needs to be a multiple of qemu_target_page_size() */
   #define MULTIFD_PACKET_SIZE (512 * 1024)
 
Quoted 7 lines

migration/multifd.h typedef struct { · line 61

Quoted 5 lines
migration/multifd.h +1 -0
@@ -52,6 +58,11 @@ typedef struct {
       uint32_t magic;
       uint32_t version;
       uint32_t flags;
+} __attribute__((packed)) MultiFDPacketHdr_t;

Maybe split this patch into two: one that adds the packet header concept and another that adds the new device packet?

Can do.

Quoted 11 lines
Quoted 11 lines
migration/multifd.h +4 -0
+
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
       /* maximum number of allocated pages */
       uint32_t pages_alloc;
       /* non zero pages */
@@ -72,6 +83,16 @@ typedef struct {
       uint64_t offset[];
   } __attribute__((packed)) MultiFDPacket_t;
 
Quoted 6 lines

migration/multifd.h typedef struct { · line 89

Quoted 4 lines
migration/multifd.h +4 -0
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
+    char idstr[256] QEMU_NONSTRING;

idstr should be null terminated, or am I missing something?

There's no need to always NULL-terminate a constant-size field, since the strncpy() already stops at the field size, so we can gain another byte for actual string use this way.

RAM block idstr also uses the same "trick":

Quoted 4 lines

void multifd_ram_fill_packet(MultiFDSendParams *p):
strncpy(packet->ramblock, pages->block->idstr, 256);

Thanks.

Thanks,
Maciej

#70 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

Quoted 202 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

Quoted 144 lines · Avihai Horon
Quoted 126 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
  migration/multifd.c | 127
+++++++++++++++++++++++++++++++++++++-------
  migration/multifd.h |  31 ++++++++++-

  2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +4 -3
index b06a9fab500e..d5a8e5a9c9b5 100644
@@ -21,6 +21,7 @@
   #include "file.h"
   #include "migration.h"
   #include "migration-stats.h"
+#include "savevm.h"
   #include "socket.h"
   #include "tls.h"
   #include "qemu-file.h"
@@ -209,10 +210,10 @@ void 
 multifd_send_fill_packet(MultiFDSendParams *p)
 
       memset(packet, 0, p->packet_len);
 
-    packet->magic = cpu_to_be32(MULTIFD_MAGIC);
-    packet->version = cpu_to_be32(MULTIFD_VERSION);
+    packet->hdr.magic = cpu_to_be32(MULTIFD_MAGIC);
+    packet->hdr.version = cpu_to_be32(MULTIFD_VERSION);
 
-    packet->flags = cpu_to_be32(p->flags);
+    packet->hdr.flags = cpu_to_be32(p->flags);
       packet->next_packet_size = cpu_to_be32(p->next_packet_size);
 

      packet_num = qatomic_fetch_inc(&multifd_send_state->packet_num);

migration/multifd.c +5 -6
@@ -228,31 +229,49 @@ void 
 multifd_send_fill_packet(MultiFDSendParams *p)
                               p->flags, p->next_packet_size);
   }
 
-static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error 
 **errp)
+static int multifd_recv_unfill_packet_header(MultiFDRecvParams *p,
+ MultiFDPacketHdr_t *hdr,
+                                             Error **errp)
   {
-    MultiFDPacket_t *packet = p->packet;
-    int ret = 0;
-
-    packet->magic = be32_to_cpu(packet->magic);
-    if (packet->magic != MULTIFD_MAGIC) {
+    hdr->magic = be32_to_cpu(hdr->magic);
+    if (hdr->magic != MULTIFD_MAGIC) {

          error_setg(errp, "multifd: received packet " "magic %x and expected magic %x", -                   packet->magic, MULTIFD_MAGIC); +                   hdr->magic, MULTIFD_MAGIC); return -1;
      }

-    packet->version = be32_to_cpu(packet->version); -    if (packet->version != MULTIFD_VERSION) {
+    hdr->version = be32_to_cpu(hdr->version);
+    if (hdr->version != MULTIFD_VERSION) { error_setg(errp, "multifd: received packet " "version %u and expected version %u", -                   packet->version, MULTIFD_VERSION); +                   hdr->version, MULTIFD_VERSION); return -1;
      }

-    p->flags = be32_to_cpu(packet->flags);
+    p->flags = be32_to_cpu(hdr->flags);

migration/multifd.c +5 -0
+
+    return 0;
+}
+
+static int 

multifd_recv_unfill_packet_device_state(MultiFDRecvParams *p, +                                                   Error **errp)

migration/multifd.c +10 -0
+{
+    MultiFDPacketDeviceState_t *packet = p->packet_dev_state;
+
+    packet->instance_id = be32_to_cpu(packet->instance_id);
+    p->next_packet_size = be32_to_cpu(packet->next_packet_size);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_ram(MultiFDRecvParams *p, 

Error **errp)

migration/multifd.c +4 -0
+{
+    MultiFDPacket_t *packet = p->packet;
+    int ret = 0;
+

      p->next_packet_size = be32_to_cpu(packet->next_packet_size); p->packet_num = be64_to_cpu(packet->packet_num); -    p->packets_recved++;

      if (!(p->flags & MULTIFD_FLAG_SYNC)) { ret = multifd_ram_unfill_packet(p, errp);

migration/multifd.c +1 -0
@@ -264,6 +283,19 @@ static int 
 multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
       return ret;
   }
 
+static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error 
 **errp)

migration/multifd.c static int · line 298

Quoted 10 lines
migration/multifd.c +10 -0
+{
+    p->packets_recved++;
+
+    if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
+        return multifd_recv_unfill_packet_device_state(p, errp);
+    } else {
+        return multifd_recv_unfill_packet_ram(p, errp);
+    }
+
+    g_assert_not_reached();

We can drop the assert and the "else":
if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
     return multifd_recv_unfill_packet_device_state(p, errp); }

Quoted 1 line

return multifd_recv_unfill_packet_ram(p, errp);

Ack.

Quoted 22 lines
Quoted 22 lines
migration/multifd.c +2 -0
+}
+
   static bool multifd_send_should_exit(void)

  {
      return qatomic_read(&multifd_send_state->exiting);

migration/multifd.h +6 -0
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
   #define MULTIFD_FLAG_QPL (4 << 1)
   #define MULTIFD_FLAG_UADK (8 << 1)
 
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)
+
   /* This value needs to be a multiple of qemu_target_page_size() */
   #define MULTIFD_PACKET_SIZE (512 * 1024)
 
Quoted 7 lines

migration/multifd.h typedef struct { · line 61

Quoted 5 lines
migration/multifd.h +1 -0
@@ -52,6 +58,11 @@ typedef struct {
       uint32_t magic;
       uint32_t version;
       uint32_t flags;
+} __attribute__((packed)) MultiFDPacketHdr_t;

Maybe split this patch into two: one that adds the packet header concept and another that adds the new device packet?

Can do.

Quoted 11 lines
Quoted 11 lines
migration/multifd.h +4 -0
+
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
       /* maximum number of allocated pages */
       uint32_t pages_alloc;
       /* non zero pages */
@@ -72,6 +83,16 @@ typedef struct {
       uint64_t offset[];
   } __attribute__((packed)) MultiFDPacket_t;
 
Quoted 6 lines

migration/multifd.h typedef struct { · line 89

Quoted 4 lines
migration/multifd.h +4 -0
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
+    char idstr[256] QEMU_NONSTRING;

idstr should be null terminated, or am I missing something?

Quoted 8 lines

There's no need to always NULL-terminate a constant-size field, since the strncpy() already stops at the field size, so we can gain another byte for actual string use this way.

RAM block idstr also uses the same "trick":

Quoted 2 lines

void multifd_ram_fill_packet(MultiFDSendParams *p):
strncpy(packet->ramblock, pages->block->idstr, 256);

But can idstr actually be 256 bytes long without null byte?
There are a lot of places where idstr is a parameter for functions that expect null terminated string and it is also printed as such.

Thanks.

#71 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

Quoted 209 lines · Avihai Horon
Quoted 208 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

Quoted 145 lines · Avihai Horon
Quoted 127 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the
packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
  migration/multifd.c | 127
+++++++++++++++++++++++++++++++++++++-------
  migration/multifd.h |  31 ++++++++++-

  2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +4 -3
index b06a9fab500e..d5a8e5a9c9b5 100644
@@ -21,6 +21,7 @@
   #include "file.h"
   #include "migration.h"
   #include "migration-stats.h"
+#include "savevm.h"
   #include "socket.h"
   #include "tls.h"
   #include "qemu-file.h"
@@ -209,10 +210,10 @@ void 
 multifd_send_fill_packet(MultiFDSendParams *p)
 
       memset(packet, 0, p->packet_len);
 
-    packet->magic = cpu_to_be32(MULTIFD_MAGIC);
-    packet->version = cpu_to_be32(MULTIFD_VERSION);
+    packet->hdr.magic = cpu_to_be32(MULTIFD_MAGIC);
+    packet->hdr.version = cpu_to_be32(MULTIFD_VERSION);
 
-    packet->flags = cpu_to_be32(p->flags);
+    packet->hdr.flags = cpu_to_be32(p->flags);
       packet->next_packet_size = cpu_to_be32(p->next_packet_size);
 

      packet_num = qatomic_fetch_inc(&multifd_send_state->packet_num);

migration/multifd.c +5 -6
@@ -228,31 +229,49 @@ void 
 multifd_send_fill_packet(MultiFDSendParams *p)
                               p->flags, p->next_packet_size);
   }
 
-static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error 
 **errp)
+static int multifd_recv_unfill_packet_header(MultiFDRecvParams *p,
+ MultiFDPacketHdr_t *hdr,
+                                             Error **errp)
   {
-    MultiFDPacket_t *packet = p->packet;
-    int ret = 0;
-
-    packet->magic = be32_to_cpu(packet->magic);
-    if (packet->magic != MULTIFD_MAGIC) {
+    hdr->magic = be32_to_cpu(hdr->magic);
+    if (hdr->magic != MULTIFD_MAGIC) {

          error_setg(errp, "multifd: received packet " "magic %x and expected magic %x", -                   packet->magic, MULTIFD_MAGIC); +                   hdr->magic, MULTIFD_MAGIC); return -1;
      }

-    packet->version = be32_to_cpu(packet->version); -    if (packet->version != MULTIFD_VERSION) {
+    hdr->version = be32_to_cpu(hdr->version);
+    if (hdr->version != MULTIFD_VERSION) { error_setg(errp, "multifd: received packet " "version %u and expected version %u", -                   packet->version, MULTIFD_VERSION); +                   hdr->version, MULTIFD_VERSION); return -1;
      }

-    p->flags = be32_to_cpu(packet->flags);
+    p->flags = be32_to_cpu(hdr->flags);

migration/multifd.c +5 -0
+
+    return 0;
+}
+
+static int 

multifd_recv_unfill_packet_device_state(MultiFDRecvParams *p, +                                                   Error **errp)

migration/multifd.c +10 -0
+{
+    MultiFDPacketDeviceState_t *packet = p->packet_dev_state;
+
+    packet->instance_id = be32_to_cpu(packet->instance_id);
+    p->next_packet_size = be32_to_cpu(packet->next_packet_size);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_ram(MultiFDRecvParams *p, 

Error **errp)

migration/multifd.c +4 -0
+{
+    MultiFDPacket_t *packet = p->packet;
+    int ret = 0;
+

      p->next_packet_size = be32_to_cpu(packet->next_packet_size); p->packet_num = be64_to_cpu(packet->packet_num); -    p->packets_recved++;

      if (!(p->flags & MULTIFD_FLAG_SYNC)) { ret = multifd_ram_unfill_packet(p, errp);

migration/multifd.c +1 -0
@@ -264,6 +283,19 @@ static int 
 multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
       return ret;
   }
 
+static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error 
 **errp)

migration/multifd.c static int · line 298

Quoted 10 lines
migration/multifd.c +10 -0
+{
+    p->packets_recved++;
+
+    if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
+        return multifd_recv_unfill_packet_device_state(p, errp);
+    } else {
+        return multifd_recv_unfill_packet_ram(p, errp);
+    }
+
+    g_assert_not_reached();

We can drop the assert and the "else":
if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
     return multifd_recv_unfill_packet_device_state(p, errp); }

Quoted 1 line

return multifd_recv_unfill_packet_ram(p, errp);

Ack.

Quoted 22 lines
Quoted 22 lines
migration/multifd.c +2 -0
+}
+
   static bool multifd_send_should_exit(void)

  {
      return qatomic_read(&multifd_send_state->exiting);

migration/multifd.h +6 -0
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
   #define MULTIFD_FLAG_QPL (4 << 1)
   #define MULTIFD_FLAG_UADK (8 << 1)
 
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)
+
   /* This value needs to be a multiple of qemu_target_page_size() */
   #define MULTIFD_PACKET_SIZE (512 * 1024)
 
Quoted 8 lines

migration/multifd.h typedef struct { · line 61

Quoted 5 lines
migration/multifd.h +1 -0
@@ -52,6 +58,11 @@ typedef struct {
       uint32_t magic;
       uint32_t version;
       uint32_t flags;
+} __attribute__((packed)) MultiFDPacketHdr_t;

Maybe split this patch into two: one that adds the packet header concept and another that adds the new device packet?

Can do.

Quoted 11 lines
Quoted 11 lines
migration/multifd.h +4 -0
+
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
       /* maximum number of allocated pages */
       uint32_t pages_alloc;
       /* non zero pages */
@@ -72,6 +83,16 @@ typedef struct {
       uint64_t offset[];
   } __attribute__((packed)) MultiFDPacket_t;
 
Quoted 6 lines

migration/multifd.h typedef struct { · line 89

Quoted 4 lines
migration/multifd.h +4 -0
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
+    char idstr[256] QEMU_NONSTRING;

idstr should be null terminated, or am I missing something?

There's no need to always NULL-terminate a constant-size field, since the strncpy() already stops at the field size, so we can gain another byte for actual string use this way.

Quoted 7 lines
Quoted 4 lines

RAM block idstr also uses the same "trick":

Quoted 2 lines

void multifd_ram_fill_packet(MultiFDSendParams *p):
strncpy(packet->ramblock, pages->block->idstr, 256);

But can idstr actually be 256 bytes long without null byte? There are a lot of places where idstr is a parameter for functions that expect null terminated string and it is also printed as such.

Yeah, and I actually don't see the "trick" being used in RAMBlock. Anyway, it's best to null terminate to be more predictable. We also had Coverity reports about similar things:

https://lore.kernel.org/r/CAFEAcA_F2qrSAacY=V5Hez1qFGuNW0-XqL2LQ=Y_UKYuHEJWhw@mail.gmail.com

I haven't got the time to send that patch yet.

Quoted 2 lines

Thanks.

#72 lore raw

Re: [PATCH v2 09/17] migration/multifd: Device state transfer support - receive side

Quoted 219 lines · Fabiano Rosas
Quoted 209 lines · Avihai Horon
Quoted 208 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

Quoted 145 lines · Avihai Horon
Quoted 127 lines · Maciej S. Szmigiero

External email: Use caution opening links or attachments

From: "Maciej S. Szmigiero" <[email protected]>

Add a basic support for receiving device state via multifd channels - channels that are shared with RAM transfers.

To differentiate between a device state and a RAM packet the packet header is read first.

Depending whether MULTIFD_FLAG_DEVICE_STATE flag is present or not in the
packet header either device state (MultiFDPacketDeviceState_t) or RAM data (existing MultiFDPacket_t) is then read.

The received device state data is provided to qemu_loadvm_load_state_buffer() function for processing in the device's load_state_buffer handler.

---
   migration/multifd.c | 127
+++++++++++++++++++++++++++++++++++++-------
   migration/multifd.h |  31 ++++++++++-
   2 files changed, 138 insertions(+), 20 deletions(-)
migration/multifd.c +4 -3
index b06a9fab500e..d5a8e5a9c9b5 100644
@@ -21,6 +21,7 @@
   #include "file.h"
   #include "migration.h"
   #include "migration-stats.h"
+#include "savevm.h"
   #include "socket.h"
   #include "tls.h"
   #include "qemu-file.h"
@@ -209,10 +210,10 @@ void
 multifd_send_fill_packet(MultiFDSendParams *p)
 
       memset(packet, 0, p->packet_len);
 
-    packet->magic = cpu_to_be32(MULTIFD_MAGIC);
-    packet->version = cpu_to_be32(MULTIFD_VERSION);
+    packet->hdr.magic = cpu_to_be32(MULTIFD_MAGIC);
+    packet->hdr.version = cpu_to_be32(MULTIFD_VERSION);
 
-    packet->flags = cpu_to_be32(p->flags);
+    packet->hdr.flags = cpu_to_be32(p->flags);
       packet->next_packet_size = cpu_to_be32(p->next_packet_size);
 

      packet_num = qatomic_fetch_inc(&multifd_send_state->packet_num);

migration/multifd.c +31 -12
@@ -228,31 +229,49 @@ void
 multifd_send_fill_packet(MultiFDSendParams *p)
                               p->flags, p->next_packet_size);
   }
 
-static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error
 **errp)
+static int multifd_recv_unfill_packet_header(MultiFDRecvParams *p,
+ MultiFDPacketHdr_t *hdr,
+                                             Error **errp)
   {
-    MultiFDPacket_t *packet = p->packet;
-    int ret = 0;
-
-    packet->magic = be32_to_cpu(packet->magic);
-    if (packet->magic != MULTIFD_MAGIC) {
+    hdr->magic = be32_to_cpu(hdr->magic);
+    if (hdr->magic != MULTIFD_MAGIC) {
           error_setg(errp, "multifd: received packet "
                      "magic %x and expected magic %x",
-                   packet->magic, MULTIFD_MAGIC);
+                   hdr->magic, MULTIFD_MAGIC);
           return -1;
       }
 
-    packet->version = be32_to_cpu(packet->version);
-    if (packet->version != MULTIFD_VERSION) {
+    hdr->version = be32_to_cpu(hdr->version);
+    if (hdr->version != MULTIFD_VERSION) {
           error_setg(errp, "multifd: received packet "
                      "version %u and expected version %u",
-                   packet->version, MULTIFD_VERSION);
+                   hdr->version, MULTIFD_VERSION);
           return -1;
       }
 
-    p->flags = be32_to_cpu(packet->flags);
+    p->flags = be32_to_cpu(hdr->flags);
+
+    return 0;
+}
+
+static int
 multifd_recv_unfill_packet_device_state(MultiFDRecvParams *p,
+                                                   Error **errp)
+{
+    MultiFDPacketDeviceState_t *packet = p->packet_dev_state;
+
+    packet->instance_id = be32_to_cpu(packet->instance_id);
+    p->next_packet_size = be32_to_cpu(packet->next_packet_size);
+
+    return 0;
+}
+
+static int multifd_recv_unfill_packet_ram(MultiFDRecvParams *p,
 Error **errp)
+{
+    MultiFDPacket_t *packet = p->packet;
+    int ret = 0;
+
       p->next_packet_size = be32_to_cpu(packet->next_packet_size);
       p->packet_num = be64_to_cpu(packet->packet_num);
-    p->packets_recved++;
 
       if (!(p->flags & MULTIFD_FLAG_SYNC)) {
           ret = multifd_ram_unfill_packet(p, errp);
@@ -264,6 +283,19 @@ static int
 multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
       return ret;
   }
 
+static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error
 **errp)

migration/multifd.c static int · line 298

Quoted 10 lines
migration/multifd.c +10 -0
+{
+    p->packets_recved++;
+
+    if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
+        return multifd_recv_unfill_packet_device_state(p, errp);
+    } else {
+        return multifd_recv_unfill_packet_ram(p, errp);
+    }
+
+    g_assert_not_reached();

We can drop the assert and the "else":
if (p->flags & MULTIFD_FLAG_DEVICE_STATE) {
     return multifd_recv_unfill_packet_device_state(p, errp);
}

Quoted 1 line

return multifd_recv_unfill_packet_ram(p, errp);

Ack.

Quoted 22 lines
Quoted 22 lines
migration/multifd.c +2 -0
+}
+
   static bool multifd_send_should_exit(void)

  {
      return qatomic_read(&multifd_send_state->exiting);

migration/multifd.h +6 -0
index a3e35196d179..a8f3e4838c01 100644
@@ -45,6 +45,12 @@ MultiFDRecvData *multifd_get_recv_data(void);
   #define MULTIFD_FLAG_QPL (4 << 1)
   #define MULTIFD_FLAG_UADK (8 << 1)
 
+/*
+ * If set it means that this packet contains device state
+ * (MultiFDPacketDeviceState_t), not RAM data (MultiFDPacket_t).
+ */
+#define MULTIFD_FLAG_DEVICE_STATE (1 << 4)
+
   /* This value needs to be a multiple of qemu_target_page_size() */
   #define MULTIFD_PACKET_SIZE (512 * 1024)
 
Quoted 8 lines

migration/multifd.h typedef struct { · line 61

Quoted 5 lines
migration/multifd.h +1 -0
@@ -52,6 +58,11 @@ typedef struct {
       uint32_t magic;
       uint32_t version;
       uint32_t flags;
+} __attribute__((packed)) MultiFDPacketHdr_t;

Maybe split this patch into two: one that adds the packet header concept and another that adds the new device packet?

Can do.

Quoted 11 lines
Quoted 11 lines
migration/multifd.h +4 -0
+
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
       /* maximum number of allocated pages */
       uint32_t pages_alloc;
       /* non zero pages */
@@ -72,6 +83,16 @@ typedef struct {
       uint64_t offset[];
   } __attribute__((packed)) MultiFDPacket_t;
 
Quoted 6 lines

migration/multifd.h typedef struct { · line 89

Quoted 4 lines
migration/multifd.h +4 -0
+typedef struct {
+    MultiFDPacketHdr_t hdr;
+
+    char idstr[256] QEMU_NONSTRING;

idstr should be null terminated, or am I missing something?

There's no need to always NULL-terminate a constant-size field, since the strncpy() already stops at the field size, so we can gain another byte for actual string use this way.

Quoted 7 lines
Quoted 4 lines

RAM block idstr also uses the same "trick":

Quoted 2 lines

void multifd_ram_fill_packet(MultiFDSendParams *p):
strncpy(packet->ramblock, pages->block->idstr, 256);

But can idstr actually be 256 bytes long without null byte? There are a lot of places where idstr is a parameter for functions that expect null terminated string and it is also printed as such.

Quoted 5 lines

Yeah, and I actually don't see the "trick" being used in RAMBlock. Anyway, it's best to null terminate to be more predictable. We also had Coverity reports about similar things:

https://lore.kernel.org/r/CAFEAcA_F2qrSAacY=V5Hez1qFGuNW0-XqL2LQ=Y_UKYuHEJWhw@mail.gmail.com

That's because MultiFDPacket_t::ramblock is missing QEMU_NONSTRING annotation (like the proposed MultiFDPacketDeviceState_t::idstr has) so Coverity assumes it was meant to be a NULL-terminated C-string.

Quoted 1 line

I haven't got the time to send that patch yet.

Thanks,
Maciej

#73 lore raw

PATCH v2 10/17 migration/multifd: Convert multifd_send()::next_channel to atomic

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This is necessary for multifd_send() to be able to be called from multiple threads.

---
 migration/multifd.c | 24 ++++++++++++++++++------
 1 file changed, 18 insertions(+), 6 deletions(-)
migration/multifd.c +18 -6
index d5a8e5a9c9b5..b25789dde0b3 100644
@@ -343,26 +343,38 @@ bool multifd_send(MultiFDSendData **send_data)
         return false;
     }
 
-    /* We wait here, until at least one channel is ready */
-    qemu_sem_wait(&multifd_send_state->channels_ready);
-
     /*
      * next_channel can remain from a previous migration that was
      * using more channels, so ensure it doesn't overflow if the
      * limit is lower now.
      */
-    next_channel %= migrate_multifd_channels();
-    for (i = next_channel;; i = (i + 1) % migrate_multifd_channels()) {
+    i = qatomic_load_acquire(&next_channel);
+    if (unlikely(i >= migrate_multifd_channels())) {
+        qatomic_cmpxchg(&next_channel, i, 0);
+    }
+
+    /* We wait here, until at least one channel is ready */
+    qemu_sem_wait(&multifd_send_state->channels_ready);
+
+    while (true) {
+        int i_next;
+
         if (multifd_send_should_exit()) {
             return false;
         }
+
+        i = qatomic_load_acquire(&next_channel);
+        i_next = (i + 1) % migrate_multifd_channels();
+        if (qatomic_cmpxchg(&next_channel, i, i_next) != i) {
+            continue;
+        }
+
         p = &multifd_send_state->params[i];
         /*
          * Lockless read to p->pending_job is safe, because only multifd
          * sender thread can clear it.
          */
         if (qatomic_read(&p->pending_job) == false) {
-            next_channel = (i + 1) % migrate_multifd_channels();
             break;
         }
     }
#74 lore raw

Re: [PATCH v2 10/17] migration/multifd: Convert multifd_send()::next_channel to atomic

Quoted 22 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This is necessary for multifd_send() to be able to be called from multiple threads.

---
 migration/multifd.c | 24 ++++++++++++++++++------
 1 file changed, 18 insertions(+), 6 deletions(-)
migration/multifd.c +0 -3
index d5a8e5a9c9b5..b25789dde0b3 100644
@@ -343,26 +343,38 @@ bool multifd_send(MultiFDSendData **send_data)
         return false;
     }
 
-    /* We wait here, until at least one channel is ready */
-    qemu_sem_wait(&multifd_send_state->channels_ready);
-
     /*

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 354

Quoted 10 lines
migration/multifd.c +4 -2
      * next_channel can remain from a previous migration that was
      * using more channels, so ensure it doesn't overflow if the
      * limit is lower now.
      */
-    next_channel %= migrate_multifd_channels();
-    for (i = next_channel;; i = (i + 1) % migrate_multifd_channels()) {
+    i = qatomic_load_acquire(&next_channel);
+    if (unlikely(i >= migrate_multifd_channels())) {
+        qatomic_cmpxchg(&next_channel, i, 0);
+    }

Do we still need this? It seems not, because the mod down below would already truncate to a value less than the number of channels. We don't need it to start at 0 always, the channels are equivalent.

Quoted 6 lines
migration/multifd.c +6 -0
+
+    /* We wait here, until at least one channel is ready */
+    qemu_sem_wait(&multifd_send_state->channels_ready);
+
+    while (true) {
+        int i_next;

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 370

Quoted 10 lines
migration/multifd.c +7 -0
+
         if (multifd_send_should_exit()) {
             return false;
         }
+
+        i = qatomic_load_acquire(&next_channel);
+        i_next = (i + 1) % migrate_multifd_channels();
+        if (qatomic_cmpxchg(&next_channel, i, i_next) != i) {
+            continue;
+        }

Say channel 'i' is the only one that's idle. What's stopping the other thread(s) to race at this point and loop around to the same index?

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 377

Quoted 7 lines
migration/multifd.c +1 -0
+
         p = &multifd_send_state->params[i];
         /*
          * Lockless read to p->pending_job is safe, because only multifd
          * sender thread can clear it.
          */
         if (qatomic_read(&p->pending_job) == false) {

With the cmpxchg your other patch adds here, then the race I mentioned above should be harmless. But we'd need to bring that code into this patch.

Quoted 4 lines
migration/multifd.c +0 -1
-            next_channel = (i + 1) % migrate_multifd_channels();
             break;
         }
     }
#75 lore raw

Re: [PATCH v2 10/17] migration/multifd: Convert multifd_send()::next_channel to atomic

Quoted 30 lines · Fabiano Rosas
Quoted 28 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This is necessary for multifd_send() to be able to be called from multiple threads.

---
  migration/multifd.c | 24 ++++++++++++++++++------
  1 file changed, 18 insertions(+), 6 deletions(-)
migration/multifd.c +0 -5
index d5a8e5a9c9b5..b25789dde0b3 100644
@@ -343,26 +343,38 @@ bool multifd_send(MultiFDSendData **send_data)
          return false;
      }
 
-    /* We wait here, until at least one channel is ready */
-    qemu_sem_wait(&multifd_send_state->channels_ready);
-
      /*
       * next_channel can remain from a previous migration that was
       * using more channels, so ensure it doesn't overflow if the
       * limit is lower now.
       */
-    next_channel %= migrate_multifd_channels();
-    for (i = next_channel;; i = (i + 1) % migrate_multifd_channels()) {
Quoted 8 lines

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 354

Quoted 4 lines
migration/multifd.c +4 -0
+    i = qatomic_load_acquire(&next_channel);
+    if (unlikely(i >= migrate_multifd_channels())) {
+        qatomic_cmpxchg(&next_channel, i, 0);
+    }

Do we still need this? It seems not, because the mod down below would already truncate to a value less than the number of channels. We don't need it to start at 0 always, the channels are equivalent.

The "modulo" operation below forces i_next to be in the proper range, not i.

If the qatomic_cmpxchg() ends up succeeding then we use the (now out of bounds) i value to index multifd_send_state->params[].

Quoted 11 lines
Quoted 11 lines
migration/multifd.c +8 -0
+
+    /* We wait here, until at least one channel is ready */
+    qemu_sem_wait(&multifd_send_state->channels_ready);
+
+    while (true) {
+        int i_next;
+
          if (multifd_send_should_exit()) {
              return false;
          }
+
Quoted 8 lines

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 370

Quoted 5 lines
migration/multifd.c +5 -0
+        i = qatomic_load_acquire(&next_channel);
+        i_next = (i + 1) % migrate_multifd_channels();
+        if (qatomic_cmpxchg(&next_channel, i, i_next) != i) {
+            continue;
+        }

Say channel 'i' is the only one that's idle. What's stopping the other thread(s) to race at this point and loop around to the same index?

See the reply below.

Quoted 8 lines

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 377

Quoted 7 lines
migration/multifd.c +1 -0
+
          p = &multifd_send_state->params[i];
          /*
           * Lockless read to p->pending_job is safe, because only multifd
           * sender thread can clear it.
           */
          if (qatomic_read(&p->pending_job) == false) {
Quoted 4 lines

With the cmpxchg your other patch adds here, then the race I mentioned above should be harmless. But we'd need to bring that code into this patch.

You're right - the sender code with this patch alone isn't thread safe yet but this commit is only literally about "converting multifd_send()::next_channel to atomic".

At the time of this patch there aren't any multifd_send() calls from multiple threads, and the commit that introduces such possible call site (multifd_queue_device_state()) also modifies multifd_send() to be fully thread safe by introducing p->pending_job_preparing.

Thanks,
Maciej

#76 lore raw

Re: [PATCH v2 10/17] migration/multifd: Convert multifd_send()::next_channel to atomic

Quoted 40 lines · Maciej S. Szmigiero
Quoted 30 lines · Fabiano Rosas
Quoted 28 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This is necessary for multifd_send() to be able to be called from multiple threads.

---
  migration/multifd.c | 24 ++++++++++++++++++------
  1 file changed, 18 insertions(+), 6 deletions(-)
migration/multifd.c +0 -5
index d5a8e5a9c9b5..b25789dde0b3 100644
@@ -343,26 +343,38 @@ bool multifd_send(MultiFDSendData **send_data)
          return false;
      }
 
-    /* We wait here, until at least one channel is ready */
-    qemu_sem_wait(&multifd_send_state->channels_ready);
-
      /*
       * next_channel can remain from a previous migration that was
       * using more channels, so ensure it doesn't overflow if the
       * limit is lower now.
       */
-    next_channel %= migrate_multifd_channels();
-    for (i = next_channel;; i = (i + 1) % migrate_multifd_channels()) {
Quoted 8 lines

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 354

Quoted 4 lines
migration/multifd.c +4 -0
+    i = qatomic_load_acquire(&next_channel);
+    if (unlikely(i >= migrate_multifd_channels())) {
+        qatomic_cmpxchg(&next_channel, i, 0);
+    }

Do we still need this? It seems not, because the mod down below would already truncate to a value less than the number of channels. We don't need it to start at 0 always, the channels are equivalent.

Quoted 5 lines

The "modulo" operation below forces i_next to be in the proper range, not i.

If the qatomic_cmpxchg() ends up succeeding then we use the (now out of bounds) i value to index multifd_send_state->params[].

Indeed.

Quoted 36 lines
Quoted 12 lines
Quoted 12 lines
migration/multifd.c +8 -0
+
+    /* We wait here, until at least one channel is ready */
+    qemu_sem_wait(&multifd_send_state->channels_ready);
+
+    while (true) {
+        int i_next;
+
          if (multifd_send_should_exit()) {
              return false;
          }
+
Quoted 8 lines

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 370

Quoted 5 lines
migration/multifd.c +5 -0
+        i = qatomic_load_acquire(&next_channel);
+        i_next = (i + 1) % migrate_multifd_channels();
+        if (qatomic_cmpxchg(&next_channel, i, i_next) != i) {
+            continue;
+        }

Say channel 'i' is the only one that's idle. What's stopping the other thread(s) to race at this point and loop around to the same index?

See the reply below.

Quoted 8 lines

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 377

Quoted 7 lines
migration/multifd.c +1 -0
+
          p = &multifd_send_state->params[i];
          /*
           * Lockless read to p->pending_job is safe, because only multifd
           * sender thread can clear it.
           */
          if (qatomic_read(&p->pending_job) == false) {
Quoted 4 lines

With the cmpxchg your other patch adds here, then the race I mentioned above should be harmless. But we'd need to bring that code into this patch.

Quoted 8 lines

You're right - the sender code with this patch alone isn't thread safe yet but this commit is only literally about "converting multifd_send()::next_channel to atomic".

At the time of this patch there aren't any multifd_send() calls from multiple threads, and the commit that introduces such possible call site (multifd_queue_device_state()) also modifies multifd_send() to be fully thread safe by introducing p->pending_job_preparing.

In general this would be a bad practice because this commit can end up being moved around due to backporting or bisecting. It would be better if it were complete from the start. It also affects backporting due to ambiguity on where the Fixes tag should point to if someone eventually finds a bug.

I already asked you to extract the other code into a separate patch, so it's not that bad. If you prefer to keep both changes separate for clarity, please note on the commit message that the next patch is necessary for correctness.

Quoted 3 lines

Thanks,
Maciej

#77 lore raw

Re: [PATCH v2 10/17] migration/multifd: Convert multifd_send()::next_channel to atomic

Quoted 19 lines · Fabiano Rosas
Quoted 17 lines · Maciej S. Szmigiero
Quoted 16 lines · Fabiano Rosas
Quoted 14 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This is necessary for multifd_send() to be able to be called from multiple threads.

---
   migration/multifd.c | 24 ++++++++++++++++++------
   1 file changed, 18 insertions(+), 6 deletions(-)
migration/multifd.c +0 -0
index d5a8e5a9c9b5..b25789dde0b3 100644

(..)

Quoted 50 lines
Quoted 35 lines
Quoted 11 lines
Quoted 11 lines
migration/multifd.c +8 -0
+
+    /* We wait here, until at least one channel is ready */
+    qemu_sem_wait(&multifd_send_state->channels_ready);
+
+    while (true) {
+        int i_next;
+
           if (multifd_send_should_exit()) {
               return false;
           }
+
Quoted 8 lines

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 370

Quoted 5 lines
migration/multifd.c +5 -0
+        i = qatomic_load_acquire(&next_channel);
+        i_next = (i + 1) % migrate_multifd_channels();
+        if (qatomic_cmpxchg(&next_channel, i, i_next) != i) {
+            continue;
+        }

Say channel 'i' is the only one that's idle. What's stopping the other thread(s) to race at this point and loop around to the same index?

See the reply below.

Quoted 8 lines
Quoted 7 lines

+

           p = &multifd_send_state->params[i];
           /*
            * Lockless read to p->pending_job is safe, because only multifd
            * sender thread can clear it.
            */
           if (qatomic_read(&p->pending_job) == false) {
Quoted 4 lines

With the cmpxchg your other patch adds here, then the race I mentioned above should be harmless. But we'd need to bring that code into this patch.

Quoted 8 lines

You're right - the sender code with this patch alone isn't thread safe yet but this commit is only literally about "converting multifd_send()::next_channel to atomic".

At the time of this patch there aren't any multifd_send() calls from multiple threads, and the commit that introduces such possible call site (multifd_queue_device_state()) also modifies multifd_send() to be fully thread safe by introducing p->pending_job_preparing.

In general this would be a bad practice because this commit can end up being moved around due to backporting or bisecting. It would be better if it were complete from the start. It also affects backporting due to ambiguity on where the Fixes tag should point to if someone eventually finds a bug.

Quoted 5 lines

I already asked you to extract the other code into a separate patch, so it's not that bad. If you prefer to keep both changes separate for clarity, please note on the commit message that the next patch is necessary for correctness.

If someone picks parts of a patch set or reorders commits then I guess in many cases things can break indeed.

But it looks like I will be able to move code changes around to have multifd_send() already thread safe by the time of this commit so I will do that.

Thanks,
Maciej

#78 lore raw

Re: [PATCH v2 10/17] migration/multifd: Convert multifd_send()::next_channel to atomic

In reply to Maciej S. Szmigiero
Quoted 6 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This is necessary for multifd_send() to be able to be called from multiple threads.

Would it be much simpler to just use a mutex for enqueue?

Something like:

===8<===

migration/multifd.c +5 -0
index 9b200f4ad9..979c9748b5 100644
@@ -69,6 +69,8 @@ struct {
     QemuSemaphore channels_created;
     /* send channels ready */
     QemuSemaphore channels_ready;
+    /* Mutex to serialize multifd enqueues */
+    QemuMutex multifd_send_mutex;
     /*
      * Have we already run terminate threads.  There is a race when it
      * happens that we got one error while we are exiting.
@@ -305,6 +307,8 @@ bool multifd_send(MultiFDSendData **send_data)
     MultiFDSendParams *p = NULL; /* make happy gcc */
     MultiFDSendData *tmp;
 
+    QEMU_LOCK_GUARD(&multifd_send_mutex);
+
     if (multifd_send_should_exit()) {
         return false;
     }
@@ -824,6 +828,7 @@ bool multifd_send_setup(void)
     multifd_send_state->params = g_new0(MultiFDSendParams, thread_count);
     qemu_sem_init(&multifd_send_state->channels_created, 0);
     qemu_sem_init(&multifd_send_state->channels_ready, 0);
+    qemu_mutex_init(&multifd_send_state->multifd_send_mutex);
     qatomic_set(&multifd_send_state->exiting, 0);
     multifd_send_state->ops = multifd_ops[migrate_multifd_compression()];

===8<===

Then all the details doesn't need change (meanwhile the perf should be similar)?

Signature · 1 line
Peter Xu
#79 lore raw

PATCH v2 11/17 migration/multifd: Add an explicit MultiFDSendData destructor

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This way if there are fields there that needs explicit disposal (like, for example, some attached buffers) they will be handled appropriately.

Add a related assert to multifd_set_payload_type() in order to make sure that this function is only used to fill a previously empty MultiFDSendData with some payload, not the other way around.

---
 migration/multifd-nocomp.c |  3 +--
 migration/multifd.c        | 31 ++++++++++++++++++++++++++++---
 migration/multifd.h        |  5 +++++
 3 files changed, 34 insertions(+), 5 deletions(-)
migration/multifd-nocomp.c +1 -2
index 53ea9f9c8371..39eb77c9b3b7 100644
@@ -40,8 +40,7 @@ void multifd_ram_save_setup(void)
 
 void multifd_ram_save_cleanup(void)
 {
-    g_free(multifd_ram_send);
-    multifd_ram_send = NULL;
+    g_clear_pointer(&multifd_ram_send, multifd_send_data_free);
 }
 
 static void multifd_set_file_bitmap(MultiFDSendParams *p)
migration/multifd.c +28 -3
index b25789dde0b3..a74e8a5cc891 100644
@@ -119,6 +119,32 @@ MultiFDSendData *multifd_send_data_alloc(void)
     return g_malloc0(size_minus_payload + max_payload_size);
 }
 
+void multifd_send_data_clear(MultiFDSendData *data)
+{
+    if (multifd_payload_empty(data)) {
+        return;
+    }
+
+    switch (data->type) {
+    default:
+        /* Nothing to do */
+        break;
+    }
+
+    data->type = MULTIFD_PAYLOAD_NONE;
+}
+
+void multifd_send_data_free(MultiFDSendData *data)
+{
+    if (!data) {
+        return;
+    }
+
+    multifd_send_data_clear(data);
+
+    g_free(data);
+}
+
 static bool multifd_use_packets(void)
 {
     return !migrate_mapped_ram();
@@ -506,8 +532,7 @@ static bool multifd_send_cleanup_channel(MultiFDSendParams *p, Error **errp)
     qemu_sem_destroy(&p->sem_sync);
     g_free(p->name);
     p->name = NULL;
-    g_free(p->data);
-    p->data = NULL;
+    g_clear_pointer(&p->data, multifd_send_data_free);
     p->packet_len = 0;
     g_free(p->packet);
     p->packet = NULL;
@@ -671,7 +696,7 @@ static void *multifd_send_thread(void *opaque)
                        p->next_packet_size + p->packet_len);
 
             p->next_packet_size = 0;
-            multifd_set_payload_type(p->data, MULTIFD_PAYLOAD_NONE);
+            multifd_send_data_clear(p->data);
 
             /*
              * Making sure p->data is published before saying "we're
migration/multifd.h +5 -0
index a8f3e4838c01..a0853622153e 100644
@@ -139,6 +139,9 @@ static inline bool multifd_payload_empty(MultiFDSendData *data)
 static inline void multifd_set_payload_type(MultiFDSendData *data,
                                             MultiFDPayloadType type)
 {
+    assert(multifd_payload_empty(data));
+    assert(type != MULTIFD_PAYLOAD_NONE);
+
     data->type = type;
 }
 
@@ -288,6 +291,8 @@ static inline void multifd_send_prepare_header(MultiFDSendParams *p)
 void multifd_channel_connect(MultiFDSendParams *p, QIOChannel *ioc);
 bool multifd_send(MultiFDSendData **send_data);
 MultiFDSendData *multifd_send_data_alloc(void);
+void multifd_send_data_clear(MultiFDSendData *data);
+void multifd_send_data_free(MultiFDSendData *data);
 
 static inline uint32_t multifd_ram_page_size(void)
 {
Reviewed-by on v2 11/17
#80 lore raw

Re: [PATCH v2 11/17] migration/multifd: Add an explicit MultiFDSendData destructor

Quoted 10 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

This way if there are fields there that needs explicit disposal (like, for example, some attached buffers) they will be handled appropriately.

Add a related assert to multifd_set_payload_type() in order to make sure that this function is only used to fill a previously empty MultiFDSendData with some payload, not the other way around.

#81 lore raw

PATCH v2 12/17 migration/multifd: Device state transfer support - send side

In reply to Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

A new function multifd_queue_device_state() is provided for device to queue its state for transmission via a multifd channel.

---
 include/migration/misc.h         |  4 ++
 migration/meson.build            |  1 +
 migration/multifd-device-state.c | 99 ++++++++++++++++++++++++++++++++
 migration/multifd-nocomp.c       |  6 +-
 migration/multifd-qpl.c          |  2 +-
 migration/multifd-uadk.c         |  2 +-
 migration/multifd-zlib.c         |  2 +-
 migration/multifd-zstd.c         |  2 +-
 migration/multifd.c              | 65 +++++++++++++++------
 migration/multifd.h              | 29 +++++++++-
 10 files changed, 184 insertions(+), 28 deletions(-)
 create mode 100644 migration/multifd-device-state.c
include/migration/misc.h +4 -0
index bfadc5613bac..7266b1b77d1f 100644
@@ -111,4 +111,8 @@ bool migration_in_bg_snapshot(void);
 /* migration/block-dirty-bitmap.c */
 void dirty_bitmap_mig_init(void);
 
+/* migration/multifd-device-state.c */
+bool multifd_queue_device_state(char *idstr, uint32_t instance_id,
+                                char *data, size_t len);
+
 #endif
migration/meson.build +1 -0
index 77f3abf08eb1..00853595894f 100644
@@ -21,6 +21,7 @@ system_ss.add(files(
   'migration-hmp-cmds.c',
   'migration.c',
   'multifd.c',
+  'multifd-device-state.c',
   'multifd-nocomp.c',
   'multifd-zlib.c',
   'multifd-zero-page.c',
migration/multifd-device-state.c new file +99 -0

99 lines not on this page · raw message

migration/multifd-nocomp.c +3 -3
index 39eb77c9b3b7..0b7b543f44db 100644
@@ -116,13 +116,13 @@ static int multifd_nocomp_send_prepare(MultiFDSendParams *p, Error **errp)
          * Only !zerocopy needs the header in IOV; zerocopy will
          * send it separately.
          */
-        multifd_send_prepare_header(p);
+        multifd_send_prepare_header_ram(p);
     }
 
     multifd_send_prepare_iovs(p);
     p->flags |= MULTIFD_FLAG_NOCOMP;
 
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
 
     if (use_zero_copy_send) {
         /* Send header first, without zerocopy */
@@ -371,7 +371,7 @@ bool multifd_send_prepare_common(MultiFDSendParams *p)
         return false;
     }
 
-    multifd_send_prepare_header(p);
+    multifd_send_prepare_header_ram(p);
 
     return true;
 }
migration/multifd-qpl.c +1 -1
index 75041a4c4dfe..bd6b5b6a3868 100644
@@ -490,7 +490,7 @@ static int multifd_qpl_send_prepare(MultiFDSendParams *p, Error **errp)
 
 out:
     p->flags |= MULTIFD_FLAG_QPL;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
     return 0;
 }
 
migration/multifd-uadk.c +1 -1
index db2549f59bfe..6e2d26010742 100644
@@ -198,7 +198,7 @@ static int multifd_uadk_send_prepare(MultiFDSendParams *p, Error **errp)
     }
 out:
     p->flags |= MULTIFD_FLAG_UADK;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
     return 0;
 }
 
migration/multifd-zlib.c +1 -1
index 6787538762d2..62a1fe59ad3e 100644
@@ -156,7 +156,7 @@ static int multifd_zlib_send_prepare(MultiFDSendParams *p, Error **errp)
 
 out:
     p->flags |= MULTIFD_FLAG_ZLIB;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
     return 0;
 }
 
migration/multifd-zstd.c +1 -1
index 1576b1e2adc6..f98b07e7f9f5 100644
@@ -143,7 +143,7 @@ static int multifd_zstd_send_prepare(MultiFDSendParams *p, Error **errp)
 
 out:
     p->flags |= MULTIFD_FLAG_ZSTD;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
     return 0;
 }
 
migration/multifd.c +47 -18

167 lines not on this page · raw message

migration/multifd.h +26 -3
index a0853622153e..c15c83104c8b 100644
@@ -120,10 +120,12 @@ typedef struct {
 typedef enum {
     MULTIFD_PAYLOAD_NONE,
     MULTIFD_PAYLOAD_RAM,
+    MULTIFD_PAYLOAD_DEVICE_STATE,
 } MultiFDPayloadType;
 
 typedef union MultiFDPayload {
     MultiFDPages_t ram;
+    MultiFDDeviceState_t device_state;
 } MultiFDPayload;
 
 struct MultiFDSendData {
@@ -136,6 +138,11 @@ static inline bool multifd_payload_empty(MultiFDSendData *data)
     return data->type == MULTIFD_PAYLOAD_NONE;
 }
 
+static inline bool multifd_payload_device_state(MultiFDSendData *data)
+{
+    return data->type == MULTIFD_PAYLOAD_DEVICE_STATE;
+}
+
 static inline void multifd_set_payload_type(MultiFDSendData *data,
                                             MultiFDPayloadType type)
 {
@@ -182,13 +189,15 @@ typedef struct {
      * cleared by the multifd sender threads.
      */
     bool pending_job;
+    bool pending_job_preparing;
     bool pending_sync;
     MultiFDSendData *data;
 
     /* thread local variables. No locking required */
 
-    /* pointer to the packet */
+    /* pointers to the possible packet types */
     MultiFDPacket_t *packet;
+    MultiFDPacketDeviceState_t *packet_device_state;
     /* size of the next packet that contains pages */
     uint32_t next_packet_size;
     /* packets sent through this channel */
@@ -276,18 +285,25 @@ typedef struct {
 } MultiFDMethods;
 
 void multifd_register_ops(int method, MultiFDMethods *ops);
-void multifd_send_fill_packet(MultiFDSendParams *p);
+void multifd_send_fill_packet_ram(MultiFDSendParams *p);
 bool multifd_send_prepare_common(MultiFDSendParams *p);
 void multifd_send_zero_page_detect(MultiFDSendParams *p);
 void multifd_recv_zero_page_process(MultiFDRecvParams *p);
 
-static inline void multifd_send_prepare_header(MultiFDSendParams *p)
+static inline void multifd_send_prepare_header_ram(MultiFDSendParams *p)
 {
     p->iov[0].iov_len = p->packet_len;
     p->iov[0].iov_base = p->packet;
     p->iovs_num++;
 }
 
+static inline void multifd_send_prepare_header_device_state(MultiFDSendParams *p)
+{
+    p->iov[0].iov_len = sizeof(*p->packet_device_state);
+    p->iov[0].iov_base = p->packet_device_state;
+    p->iovs_num++;
+}
+
 void multifd_channel_connect(MultiFDSendParams *p, QIOChannel *ioc);
 bool multifd_send(MultiFDSendData **send_data);
 MultiFDSendData *multifd_send_data_alloc(void);
@@ -310,4 +326,11 @@ int multifd_ram_flush_and_sync(void);
 size_t multifd_ram_payload_size(void);
 void multifd_ram_fill_packet(MultiFDSendParams *p);
 int multifd_ram_unfill_packet(MultiFDRecvParams *p, Error **errp);
+
+size_t multifd_device_state_payload_size(void);
+void multifd_device_state_save_setup(void);
+void multifd_device_state_clear(MultiFDDeviceState_t *device_state);
+void multifd_device_state_save_cleanup(void);
+void multifd_device_state_send_prepare(MultiFDSendParams *p);
+
 #endif
#82 lore raw

Re: [PATCH v2 12/17] migration/multifd: Device state transfer support - send side

Quoted 63 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

A new function multifd_queue_device_state() is provided for device to queue its state for transmission via a multifd channel.

---
 include/migration/misc.h         |  4 ++
 migration/meson.build            |  1 +
 migration/multifd-device-state.c | 99 ++++++++++++++++++++++++++++++++
 migration/multifd-nocomp.c       |  6 +-
 migration/multifd-qpl.c          |  2 +-
 migration/multifd-uadk.c         |  2 +-
 migration/multifd-zlib.c         |  2 +-
 migration/multifd-zstd.c         |  2 +-
 migration/multifd.c              | 65 +++++++++++++++------
 migration/multifd.h              | 29 +++++++++-
 10 files changed, 184 insertions(+), 28 deletions(-)
 create mode 100644 migration/multifd-device-state.c
include/migration/misc.h +4 -0
index bfadc5613bac..7266b1b77d1f 100644
@@ -111,4 +111,8 @@ bool migration_in_bg_snapshot(void);
 /* migration/block-dirty-bitmap.c */
 void dirty_bitmap_mig_init(void);
 
+/* migration/multifd-device-state.c */
+bool multifd_queue_device_state(char *idstr, uint32_t instance_id,
+                                char *data, size_t len);
+
 #endif
migration/meson.build +1 -0
index 77f3abf08eb1..00853595894f 100644
@@ -21,6 +21,7 @@ system_ss.add(files(
   'migration-hmp-cmds.c',
   'migration.c',
   'multifd.c',
+  'multifd-device-state.c',
   'multifd-nocomp.c',
   'multifd-zlib.c',
   'multifd-zero-page.c',
migration/multifd-device-state.c new file +12 -0
new file mode 100644
index 000000000000..c9b44f0b5ab9
@@ -0,0 +1,99 @@
+/*
+ * Multifd device state migration
+ *
+ * Copyright (C) 2024 Oracle and/or its affiliates.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu/osdep.h"
+#include "qemu/lockable.h"
+#include "migration/misc.h"

migration/multifd-device-state.c line 22

Quoted 10 lines
migration/multifd-device-state.c new file +10 -0
+#include "multifd.h"
+
+static QemuMutex queue_job_mutex;
+
+static MultiFDSendData *device_state_send;
+
+size_t multifd_device_state_payload_size(void)
+{
+    return sizeof(MultiFDDeviceState_t);
+}

This will not be necessary because the payload size is the same as the data type. We only need it for the special case where the MultiFDPages_t is smaller than the total ram payload size.

migration/multifd-device-state.c line 24

Quoted 2 lines
migration/multifd-device-state.c new file +2 -0
+
+void multifd_device_state_save_setup(void)

s/save/send/. The ram ones are only called "save" because they're called from ram_save_setup(), but we then have the proper nocomp_send_setup hook.

migration/multifd-device-state.c line 37

Quoted 13 lines
migration/multifd-device-state.c new file +13 -0
+{
+    qemu_mutex_init(&queue_job_mutex);
+
+    device_state_send = multifd_send_data_alloc();
+}
+
+void multifd_device_state_clear(MultiFDDeviceState_t *device_state)
+{
+    g_clear_pointer(&device_state->idstr, g_free);
+    g_clear_pointer(&device_state->buf, g_free);
+}
+
+void multifd_device_state_save_cleanup(void)

s/save/send/

Quoted 164 lines
migration/multifd-device-state.c new file +62 -0
+{
+    g_clear_pointer(&device_state_send, multifd_send_data_free);
+
+    qemu_mutex_destroy(&queue_job_mutex);
+}
+
+static void multifd_device_state_fill_packet(MultiFDSendParams *p)
+{
+    MultiFDDeviceState_t *device_state = &p->data->u.device_state;
+    MultiFDPacketDeviceState_t *packet = p->packet_device_state;
+
+    packet->hdr.flags = cpu_to_be32(p->flags);
+    strncpy(packet->idstr, device_state->idstr, sizeof(packet->idstr));
+    packet->instance_id = cpu_to_be32(device_state->instance_id);
+    packet->next_packet_size = cpu_to_be32(p->next_packet_size);
+}
+
+void multifd_device_state_send_prepare(MultiFDSendParams *p)
+{
+    MultiFDDeviceState_t *device_state = &p->data->u.device_state;
+
+    assert(multifd_payload_device_state(p->data));
+
+    multifd_send_prepare_header_device_state(p);
+
+    assert(!(p->flags & MULTIFD_FLAG_SYNC));
+
+    p->next_packet_size = device_state->buf_len;
+    if (p->next_packet_size > 0) {
+        p->iov[p->iovs_num].iov_base = device_state->buf;
+        p->iov[p->iovs_num].iov_len = p->next_packet_size;
+        p->iovs_num++;
+    }
+
+    p->flags |= MULTIFD_FLAG_NOCOMP | MULTIFD_FLAG_DEVICE_STATE;
+
+    multifd_device_state_fill_packet(p);
+}
+
+bool multifd_queue_device_state(char *idstr, uint32_t instance_id,
+                                char *data, size_t len)
+{
+    /* Device state submissions can come from multiple threads */
+    QEMU_LOCK_GUARD(&queue_job_mutex);
+    MultiFDDeviceState_t *device_state;
+
+    assert(multifd_payload_empty(device_state_send));
+
+    multifd_set_payload_type(device_state_send, MULTIFD_PAYLOAD_DEVICE_STATE);
+    device_state = &device_state_send->u.device_state;
+    device_state->idstr = g_strdup(idstr);
+    device_state->instance_id = instance_id;
+    device_state->buf = g_memdup2(data, len);
+    device_state->buf_len = len;
+
+    if (!multifd_send(&device_state_send)) {
+        multifd_send_data_clear(device_state_send);
+        return false;
+    }
+
+    return true;
+}
migration/multifd-nocomp.c +3 -3
index 39eb77c9b3b7..0b7b543f44db 100644
@@ -116,13 +116,13 @@ static int multifd_nocomp_send_prepare(MultiFDSendParams *p, Error **errp)
          * Only !zerocopy needs the header in IOV; zerocopy will
          * send it separately.
          */
-        multifd_send_prepare_header(p);
+        multifd_send_prepare_header_ram(p);
     }
 
     multifd_send_prepare_iovs(p);
     p->flags |= MULTIFD_FLAG_NOCOMP;
 
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
 
     if (use_zero_copy_send) {
         /* Send header first, without zerocopy */
@@ -371,7 +371,7 @@ bool multifd_send_prepare_common(MultiFDSendParams *p)
         return false;
     }
 
-    multifd_send_prepare_header(p);
+    multifd_send_prepare_header_ram(p);
 
     return true;
 }
migration/multifd-qpl.c +1 -1
index 75041a4c4dfe..bd6b5b6a3868 100644
@@ -490,7 +490,7 @@ static int multifd_qpl_send_prepare(MultiFDSendParams *p, Error **errp)
 
 out:
     p->flags |= MULTIFD_FLAG_QPL;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
     return 0;
 }
 
migration/multifd-uadk.c +1 -1
index db2549f59bfe..6e2d26010742 100644
@@ -198,7 +198,7 @@ static int multifd_uadk_send_prepare(MultiFDSendParams *p, Error **errp)
     }
 out:
     p->flags |= MULTIFD_FLAG_UADK;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
     return 0;
 }
 
migration/multifd-zlib.c +1 -1
index 6787538762d2..62a1fe59ad3e 100644
@@ -156,7 +156,7 @@ static int multifd_zlib_send_prepare(MultiFDSendParams *p, Error **errp)
 
 out:
     p->flags |= MULTIFD_FLAG_ZLIB;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
     return 0;
 }
 
migration/multifd-zstd.c +1 -1
index 1576b1e2adc6..f98b07e7f9f5 100644
@@ -143,7 +143,7 @@ static int multifd_zstd_send_prepare(MultiFDSendParams *p, Error **errp)
 
 out:
     p->flags |= MULTIFD_FLAG_ZSTD;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
     return 0;
 }
 
migration/multifd.c +2 -0
index a74e8a5cc891..bebe5b5a9b9c 100644
@@ -12,6 +12,7 @@
 
 #include "qemu/osdep.h"
 #include "qemu/cutils.h"
+#include "qemu/iov.h"
 #include "qemu/rcu.h"
 #include "exec/target_page.h"
 #include "sysemu/sysemu.h"
@@ -19,6 +20,7 @@
 #include "qemu/error-report.h"
 #include "qapi/error.h"
 #include "file.h"
+#include "migration/misc.h"
 #include "migration.h"
 #include "migration-stats.h"
 #include "savevm.h"

migration/multifd.c MultiFDSendData *multifd_send_data_alloc(void) · line 113

Quoted 6 lines
migration/multifd.c +2 -1
@@ -107,7 +109,9 @@ MultiFDSendData *multifd_send_data_alloc(void)
      * added to the union in the future are larger than
      * (MultiFDPages_t + flex array).
      */
-    max_payload_size = MAX(multifd_ram_payload_size(), sizeof(MultiFDPayload));
+    max_payload_size = MAX(multifd_ram_payload_size(),
+                           multifd_device_state_payload_size());

This is not needed, the sizeof(MultiFDPayload) below already has the same effect.

Quoted 15 lines
migration/multifd.c +4 -0
+    max_payload_size = MAX(max_payload_size, sizeof(MultiFDPayload));
 
     /*
      * Account for any holes the compiler might insert. We can't pack
@@ -126,6 +130,9 @@ void multifd_send_data_clear(MultiFDSendData *data)
     }
 
     switch (data->type) {
+    case MULTIFD_PAYLOAD_DEVICE_STATE:
+        multifd_device_state_clear(&data->u.device_state);
+        break;
     default:
         /* Nothing to do */
         break;

migration/multifd.c static int multifd_recv_initial_packet(QIOChannel *c, Error **errp) · line 238

Quoted 5 lines
migration/multifd.c +1 -1
@@ -228,7 +235,7 @@ static int multifd_recv_initial_packet(QIOChannel *c, Error **errp)
     return msg.id;
 }
 
-void multifd_send_fill_packet(MultiFDSendParams *p)
+void multifd_send_fill_packet_ram(MultiFDSendParams *p)

Do we need this change if there's no counterpart for device_state? It might be less confusing to just leave this one as it is.

Quoted 6 lines
migration/multifd.c +0 -0
 {
     MultiFDPacket_t *packet = p->packet;
     uint64_t packet_num;
@@ -397,20 +404,16 @@ bool multifd_send(MultiFDSendData **send_data)
 
         p = &multifd_send_state->params[i];

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 412

Quoted 10 lines
migration/multifd.c +5 -3
         /*
-         * Lockless read to p->pending_job is safe, because only multifd
-         * sender thread can clear it.
+         * Lockless RMW on p->pending_job_preparing is safe, because only multifd
+         * sender thread can clear it after it had seen p->pending_job being set.
+         *
+         * Pairs with qatomic_store_release() in multifd_send_thread().
          */
-        if (qatomic_read(&p->pending_job) == false) {
+        if (qatomic_cmpxchg(&p->pending_job_preparing, false, true) == false) {

What's the motivation for this change? It would be better to have it in a separate patch with a proper justification.

Quoted 67 lines
migration/multifd.c +15 -10
             break;
         }
     }
 
-    /*
-     * Make sure we read p->pending_job before all the rest.  Pairs with
-     * qatomic_store_release() in multifd_send_thread().
-     */
-    smp_mb_acquire();
-
     assert(multifd_payload_empty(p->data));
 
     /*
@@ -534,6 +537,7 @@ static bool multifd_send_cleanup_channel(MultiFDSendParams *p, Error **errp)
     p->name = NULL;
     g_clear_pointer(&p->data, multifd_send_data_free);
     p->packet_len = 0;
+    g_clear_pointer(&p->packet_device_state, g_free);
     g_free(p->packet);
     p->packet = NULL;
     multifd_send_state->ops->send_cleanup(p, errp);
@@ -545,6 +549,7 @@ static void multifd_send_cleanup_state(void)
 {
     file_cleanup_outgoing_migration();
     socket_cleanup_outgoing_migration();
+    multifd_device_state_save_cleanup();
     qemu_sem_destroy(&multifd_send_state->channels_created);
     qemu_sem_destroy(&multifd_send_state->channels_ready);
     g_free(multifd_send_state->params);
@@ -670,19 +675,29 @@ static void *multifd_send_thread(void *opaque)
          * qatomic_store_release() in multifd_send().
          */
         if (qatomic_load_acquire(&p->pending_job)) {
+            bool is_device_state = multifd_payload_device_state(p->data);
+            size_t total_size;
+
             p->flags = 0;
             p->iovs_num = 0;
             assert(!multifd_payload_empty(p->data));
 
-            ret = multifd_send_state->ops->send_prepare(p, &local_err);
-            if (ret != 0) {
-                break;
+            if (is_device_state) {
+                multifd_device_state_send_prepare(p);
+            } else {
+                ret = multifd_send_state->ops->send_prepare(p, &local_err);
+                if (ret != 0) {
+                    break;
+                }
             }
 
             if (migrate_mapped_ram()) {
+                assert(!is_device_state);
+
                 ret = file_write_ramblock_iov(p->c, p->iov, p->iovs_num,
                                               &p->data->u.ram, &local_err);
             } else {
+                total_size = iov_size(p->iov, p->iovs_num);
                 ret = qio_channel_writev_full_all(p->c, p->iov, p->iovs_num,
                                                   NULL, 0, p->write_flags,
                                                   &local_err);
@@ -692,18 +707,27 @@ static void *multifd_send_thread(void *opaque)
                 break;
             }
 
-            stat64_add(&mig_stats.multifd_bytes,

migration/multifd.c static void *multifd_send_thread(void *opaque) · line 718

Quoted 10 lines
migration/multifd.c +9 -1
-                       p->next_packet_size + p->packet_len);
+            if (is_device_state) {
+                stat64_add(&mig_stats.multifd_bytes, total_size);
+            } else {
+                /*
+                 * Can't just always add total_size since IOVs do not include
+                 * packet header in the zerocopy RAM case.
+                 */
+                stat64_add(&mig_stats.multifd_bytes,
+                           p->next_packet_size + p->packet_len);

You could set total_size for both branches after send_prepare and use it here unconditionally.

Quoted 92 lines
migration/multifd.c +9 -2
+            }
 
             p->next_packet_size = 0;
             multifd_send_data_clear(p->data);
 
             /*
              * Making sure p->data is published before saying "we're
-             * free".  Pairs with the smp_mb_acquire() in
+             * free".  Pairs with the qatomic_cmpxchg() in
              * multifd_send().
              */
             qatomic_store_release(&p->pending_job, false);
+            qatomic_store_release(&p->pending_job_preparing, false);
         } else {
             /*
              * If not a normal job, must be a sync request.  Note that
@@ -714,7 +738,7 @@ static void *multifd_send_thread(void *opaque)
 
             if (use_packets) {
                 p->flags = MULTIFD_FLAG_SYNC;
-                multifd_send_fill_packet(p);
+                multifd_send_fill_packet_ram(p);
                 ret = qio_channel_write_all(p->c, (void *)p->packet,
                                             p->packet_len, &local_err);
                 if (ret != 0) {
@@ -910,6 +934,9 @@ bool multifd_send_setup(void)
             p->packet_len = sizeof(MultiFDPacket_t)
                           + sizeof(uint64_t) * page_count;
             p->packet = g_malloc0(p->packet_len);
+            p->packet_device_state = g_malloc0(sizeof(*p->packet_device_state));
+            p->packet_device_state->hdr.magic = cpu_to_be32(MULTIFD_MAGIC);
+            p->packet_device_state->hdr.version = cpu_to_be32(MULTIFD_VERSION);
         }
         p->name = g_strdup_printf("mig/src/send_%d", i);
         p->write_flags = 0;
@@ -944,6 +971,8 @@ bool multifd_send_setup(void)
         }
     }
 
+    multifd_device_state_save_setup();
+
     return true;
 
 err:
migration/multifd.h +10 -1
index a0853622153e..c15c83104c8b 100644
@@ -120,10 +120,12 @@ typedef struct {
 typedef enum {
     MULTIFD_PAYLOAD_NONE,
     MULTIFD_PAYLOAD_RAM,
+    MULTIFD_PAYLOAD_DEVICE_STATE,
 } MultiFDPayloadType;
 
 typedef union MultiFDPayload {
     MultiFDPages_t ram;
+    MultiFDDeviceState_t device_state;
 } MultiFDPayload;
 
 struct MultiFDSendData {
@@ -136,6 +138,11 @@ static inline bool multifd_payload_empty(MultiFDSendData *data)
     return data->type == MULTIFD_PAYLOAD_NONE;
 }
 
+static inline bool multifd_payload_device_state(MultiFDSendData *data)
+{
+    return data->type == MULTIFD_PAYLOAD_DEVICE_STATE;
+}
+
 static inline void multifd_set_payload_type(MultiFDSendData *data,
                                             MultiFDPayloadType type)
 {
@@ -182,13 +189,15 @@ typedef struct {
      * cleared by the multifd sender threads.
      */
     bool pending_job;
+    bool pending_job_preparing;
     bool pending_sync;
     MultiFDSendData *data;
 
     /* thread local variables. No locking required */
 
-    /* pointer to the packet */
+    /* pointers to the possible packet types */
     MultiFDPacket_t *packet;
+    MultiFDPacketDeviceState_t *packet_device_state;
     /* size of the next packet that contains pages */
     uint32_t next_packet_size;
     /* packets sent through this channel */
@@ -276,18 +285,25 @@ typedef struct {
 } MultiFDMethods;

migration/multifd.h typedef struct { · line 293

Quoted 10 lines
migration/multifd.h +2 -2
 
 void multifd_register_ops(int method, MultiFDMethods *ops);
-void multifd_send_fill_packet(MultiFDSendParams *p);
+void multifd_send_fill_packet_ram(MultiFDSendParams *p);
 bool multifd_send_prepare_common(MultiFDSendParams *p);
 void multifd_send_zero_page_detect(MultiFDSendParams *p);
 void multifd_recv_zero_page_process(MultiFDRecvParams *p);
 
-static inline void multifd_send_prepare_header(MultiFDSendParams *p)
+static inline void multifd_send_prepare_header_ram(MultiFDSendParams *p)

This could instead go to multifd-nocomp.c and become multifd_ram_prepare_header.

migration/multifd.h typedef struct { · line 300

Quoted 7 lines
migration/multifd.h +1 -0
 {
     p->iov[0].iov_len = p->packet_len;
     p->iov[0].iov_base = p->packet;
     p->iovs_num++;
 }
 
+static inline void multifd_send_prepare_header_device_state(MultiFDSendParams *p)

Seem like this could also move to multifd-device-state.c and drop the "send" part.

Quoted 21 lines
migration/multifd.h +13 -0
+{
+    p->iov[0].iov_len = sizeof(*p->packet_device_state);
+    p->iov[0].iov_base = p->packet_device_state;
+    p->iovs_num++;
+}
+
 void multifd_channel_connect(MultiFDSendParams *p, QIOChannel *ioc);
 bool multifd_send(MultiFDSendData **send_data);
 MultiFDSendData *multifd_send_data_alloc(void);
@@ -310,4 +326,11 @@ int multifd_ram_flush_and_sync(void);
 size_t multifd_ram_payload_size(void);
 void multifd_ram_fill_packet(MultiFDSendParams *p);
 int multifd_ram_unfill_packet(MultiFDRecvParams *p, Error **errp);
+
+size_t multifd_device_state_payload_size(void);
+void multifd_device_state_save_setup(void);
+void multifd_device_state_clear(MultiFDDeviceState_t *device_state);
+void multifd_device_state_save_cleanup(void);
+void multifd_device_state_send_prepare(MultiFDSendParams *p);
+
 #endif
#83 lore raw

Re: [PATCH v2 12/17] migration/multifd: Device state transfer support - send side

Quoted 71 lines · Fabiano Rosas
Quoted 69 lines · Maciej S. Szmigiero

From: "Maciej S. Szmigiero" <[email protected]>

A new function multifd_queue_device_state() is provided for device to queue its state for transmission via a multifd channel.

---
  include/migration/misc.h         |  4 ++
  migration/meson.build            |  1 +
  migration/multifd-device-state.c | 99 ++++++++++++++++++++++++++++++++
  migration/multifd-nocomp.c       |  6 +-
  migration/multifd-qpl.c          |  2 +-
  migration/multifd-uadk.c         |  2 +-
  migration/multifd-zlib.c         |  2 +-
  migration/multifd-zstd.c         |  2 +-
  migration/multifd.c              | 65 +++++++++++++++------
  migration/multifd.h              | 29 +++++++++-
  10 files changed, 184 insertions(+), 28 deletions(-)

create mode 100644 migration/multifd-device-state.c

include/migration/misc.h +4 -0
index bfadc5613bac..7266b1b77d1f 100644
@@ -111,4 +111,8 @@ bool migration_in_bg_snapshot(void);
  /* migration/block-dirty-bitmap.c */
  void dirty_bitmap_mig_init(void);
 
+/* migration/multifd-device-state.c */
+bool multifd_queue_device_state(char *idstr, uint32_t instance_id,
+                                char *data, size_t len);
+
  #endif
migration/meson.build +1 -0
index 77f3abf08eb1..00853595894f 100644
@@ -21,6 +21,7 @@ system_ss.add(files(
    'migration-hmp-cmds.c',
    'migration.c',
    'multifd.c',
+  'multifd-device-state.c',
    'multifd-nocomp.c',
    'multifd-zlib.c',
    'multifd-zero-page.c',
migration/multifd-device-state.c new file +18 -0
new file mode 100644
index 000000000000..c9b44f0b5ab9
@@ -0,0 +1,99 @@
+/*
+ * Multifd device state migration
+ *
+ * Copyright (C) 2024 Oracle and/or its affiliates.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu/osdep.h"
+#include "qemu/lockable.h"
+#include "migration/misc.h"
+#include "multifd.h"
+
+static QemuMutex queue_job_mutex;
+
+static MultiFDSendData *device_state_send;
+
Quoted 8 lines

migration/multifd-device-state.c line 22

Quoted 4 lines
migration/multifd-device-state.c new file +4 -0
+size_t multifd_device_state_payload_size(void)
+{
+    return sizeof(MultiFDDeviceState_t);
+}

This will not be necessary because the payload size is the same as the data type. We only need it for the special case where the MultiFDPages_t is smaller than the total ram payload size.

I know - I just wanted to make the API consistent with the one RAM handler provides since these multifd_send_data_alloc() calls are done just once per migration - it isn't any kind of a hot path.

Quoted 6 lines

migration/multifd-device-state.c line 24

Quoted 2 lines
migration/multifd-device-state.c new file +2 -0
+
+void multifd_device_state_save_setup(void)

s/save/send/. The ram ones are only called "save" because they're called from ram_save_setup(), but we then have the proper nocomp_send_setup hook.

Ack.

Quoted 7 lines
Quoted 7 lines
migration/multifd-device-state.c new file +7 -0
+{
+    qemu_mutex_init(&queue_job_mutex);
+
+    device_state_send = multifd_send_data_alloc();
+}
+
+void multifd_device_state_clear(MultiFDDeviceState_t *device_state)
Quoted 8 lines

migration/multifd-device-state.c line 37

Quoted 6 lines
migration/multifd-device-state.c new file +6 -0
+{
+    g_clear_pointer(&device_state->idstr, g_free);
+    g_clear_pointer(&device_state->buf, g_free);
+}
+
+void multifd_device_state_save_cleanup(void)

s/save/send/

Ack.

Quoted 165 lines
Quoted 165 lines
migration/multifd-device-state.c new file +62 -0
+{
+    g_clear_pointer(&device_state_send, multifd_send_data_free);
+
+    qemu_mutex_destroy(&queue_job_mutex);
+}
+
+static void multifd_device_state_fill_packet(MultiFDSendParams *p)
+{
+    MultiFDDeviceState_t *device_state = &p->data->u.device_state;
+    MultiFDPacketDeviceState_t *packet = p->packet_device_state;
+
+    packet->hdr.flags = cpu_to_be32(p->flags);
+    strncpy(packet->idstr, device_state->idstr, sizeof(packet->idstr));
+    packet->instance_id = cpu_to_be32(device_state->instance_id);
+    packet->next_packet_size = cpu_to_be32(p->next_packet_size);
+}
+
+void multifd_device_state_send_prepare(MultiFDSendParams *p)
+{
+    MultiFDDeviceState_t *device_state = &p->data->u.device_state;
+
+    assert(multifd_payload_device_state(p->data));
+
+    multifd_send_prepare_header_device_state(p);
+
+    assert(!(p->flags & MULTIFD_FLAG_SYNC));
+
+    p->next_packet_size = device_state->buf_len;
+    if (p->next_packet_size > 0) {
+        p->iov[p->iovs_num].iov_base = device_state->buf;
+        p->iov[p->iovs_num].iov_len = p->next_packet_size;
+        p->iovs_num++;
+    }
+
+    p->flags |= MULTIFD_FLAG_NOCOMP | MULTIFD_FLAG_DEVICE_STATE;
+
+    multifd_device_state_fill_packet(p);
+}
+
+bool multifd_queue_device_state(char *idstr, uint32_t instance_id,
+                                char *data, size_t len)
+{
+    /* Device state submissions can come from multiple threads */
+    QEMU_LOCK_GUARD(&queue_job_mutex);
+    MultiFDDeviceState_t *device_state;
+
+    assert(multifd_payload_empty(device_state_send));
+
+    multifd_set_payload_type(device_state_send, MULTIFD_PAYLOAD_DEVICE_STATE);
+    device_state = &device_state_send->u.device_state;
+    device_state->idstr = g_strdup(idstr);
+    device_state->instance_id = instance_id;
+    device_state->buf = g_memdup2(data, len);
+    device_state->buf_len = len;
+
+    if (!multifd_send(&device_state_send)) {
+        multifd_send_data_clear(device_state_send);
+        return false;
+    }
+
+    return true;
+}
migration/multifd-nocomp.c +3 -3
index 39eb77c9b3b7..0b7b543f44db 100644
@@ -116,13 +116,13 @@ static int multifd_nocomp_send_prepare(MultiFDSendParams *p, Error **errp)
           * Only !zerocopy needs the header in IOV; zerocopy will
           * send it separately.
           */
-        multifd_send_prepare_header(p);
+        multifd_send_prepare_header_ram(p);
      }
 
      multifd_send_prepare_iovs(p);
      p->flags |= MULTIFD_FLAG_NOCOMP;
 
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
 
      if (use_zero_copy_send) {
          /* Send header first, without zerocopy */
@@ -371,7 +371,7 @@ bool multifd_send_prepare_common(MultiFDSendParams *p)
          return false;
      }
 
-    multifd_send_prepare_header(p);
+    multifd_send_prepare_header_ram(p);
 
      return true;
  }
migration/multifd-qpl.c +1 -1
index 75041a4c4dfe..bd6b5b6a3868 100644
@@ -490,7 +490,7 @@ static int multifd_qpl_send_prepare(MultiFDSendParams *p, Error **errp)
 
  out:
      p->flags |= MULTIFD_FLAG_QPL;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
      return 0;
  }
 
migration/multifd-uadk.c +1 -1
index db2549f59bfe..6e2d26010742 100644
@@ -198,7 +198,7 @@ static int multifd_uadk_send_prepare(MultiFDSendParams *p, Error **errp)
      }
  out:
      p->flags |= MULTIFD_FLAG_UADK;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
      return 0;
  }
 
migration/multifd-zlib.c +1 -1
index 6787538762d2..62a1fe59ad3e 100644
@@ -156,7 +156,7 @@ static int multifd_zlib_send_prepare(MultiFDSendParams *p, Error **errp)
 
  out:
      p->flags |= MULTIFD_FLAG_ZLIB;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
      return 0;
  }
 
migration/multifd-zstd.c +1 -1
index 1576b1e2adc6..f98b07e7f9f5 100644
@@ -143,7 +143,7 @@ static int multifd_zstd_send_prepare(MultiFDSendParams *p, Error **errp)
 
  out:
      p->flags |= MULTIFD_FLAG_ZSTD;
-    multifd_send_fill_packet(p);
+    multifd_send_fill_packet_ram(p);
      return 0;
  }
 
migration/multifd.c +2 -0
index a74e8a5cc891..bebe5b5a9b9c 100644
@@ -12,6 +12,7 @@
 
  #include "qemu/osdep.h"
  #include "qemu/cutils.h"
+#include "qemu/iov.h"
  #include "qemu/rcu.h"
  #include "exec/target_page.h"
  #include "sysemu/sysemu.h"
@@ -19,6 +20,7 @@
  #include "qemu/error-report.h"
  #include "qapi/error.h"
  #include "file.h"
+#include "migration/misc.h"
  #include "migration.h"
  #include "migration-stats.h"
  #include "savevm.h"
@@ -107,7 +109,9 @@ MultiFDSendData *multifd_send_data_alloc(void)
       * added to the union in the future are larger than
Quoted 8 lines

migration/multifd.c MultiFDSendData *multifd_send_data_alloc(void) · line 113

Quoted 5 lines
migration/multifd.c +2 -1
       * (MultiFDPages_t + flex array).
       */
-    max_payload_size = MAX(multifd_ram_payload_size(), sizeof(MultiFDPayload));
+    max_payload_size = MAX(multifd_ram_payload_size(),
+                           multifd_device_state_payload_size());

This is not needed, the sizeof(MultiFDPayload) below already has the same effect.

Same as above, I think it's good for consistency, but I don't mind removing it either (maybe by replacing it with a comment describing that it isn't currently needed).

Quoted 18 lines
Quoted 18 lines
migration/multifd.c +4 -0
+    max_payload_size = MAX(max_payload_size, sizeof(MultiFDPayload));
 
      /*
       * Account for any holes the compiler might insert. We can't pack
@@ -126,6 +130,9 @@ void multifd_send_data_clear(MultiFDSendData *data)
      }
 
      switch (data->type) {
+    case MULTIFD_PAYLOAD_DEVICE_STATE:
+        multifd_device_state_clear(&data->u.device_state);
+        break;
      default:
          /* Nothing to do */
          break;
@@ -228,7 +235,7 @@ static int multifd_recv_initial_packet(QIOChannel *c, Error **errp)
      return msg.id;
  }
 
Quoted 5 lines

migration/multifd.c static int multifd_recv_initial_packet(QIOChannel *c, Error **errp) · line 238

Quoted 2 lines
migration/multifd.c +1 -1
-void multifd_send_fill_packet(MultiFDSendParams *p)
+void multifd_send_fill_packet_ram(MultiFDSendParams *p)

Do we need this change if there's no counterpart for device_state? It might be less confusing to just leave this one as it is.

Not really, will drop this change in the next patch set version.

Quoted 5 lines
Quoted 5 lines
migration/multifd.c +0 -0
  {
      MultiFDPacket_t *packet = p->packet;
      uint64_t packet_num;
@@ -397,20 +404,16 @@ bool multifd_send(MultiFDSendData **send_data)
 
Quoted 14 lines

migration/multifd.c bool multifd_send(MultiFDSendData **send_data) · line 412

Quoted 11 lines
migration/multifd.c +5 -3
          p = &multifd_send_state->params[i];
          /*
-         * Lockless read to p->pending_job is safe, because only multifd
-         * sender thread can clear it.
+         * Lockless RMW on p->pending_job_preparing is safe, because only multifd
+         * sender thread can clear it after it had seen p->pending_job being set.
+         *
+         * Pairs with qatomic_store_release() in multifd_send_thread().
           */
-        if (qatomic_read(&p->pending_job) == false) {
+        if (qatomic_cmpxchg(&p->pending_job_preparing, false, true) == false) {

What's the motivation for this change? It would be better to have it in a separate patch with a proper justification.

The original RFC patch set used dedicated device state multifd channels.

Peter and other people wanted this functionality removed, however this caused a performance (downtime) regression.

One of the things that seemed to help mitigate this regression was making the multifd channel selection more fair via this change.

But I can split out it to a separate commit in the next patch set version and then see what performance improvement it currently brings.

Quoted 66 lines
Quoted 66 lines
migration/multifd.c +15 -9
              break;
          }
      }
 
-    /*
-     * Make sure we read p->pending_job before all the rest.  Pairs with
-     * qatomic_store_release() in multifd_send_thread().
-     */
-    smp_mb_acquire();
-
      assert(multifd_payload_empty(p->data));
 
      /*
@@ -534,6 +537,7 @@ static bool multifd_send_cleanup_channel(MultiFDSendParams *p, Error **errp)
      p->name = NULL;
      g_clear_pointer(&p->data, multifd_send_data_free);
      p->packet_len = 0;
+    g_clear_pointer(&p->packet_device_state, g_free);
      g_free(p->packet);
      p->packet = NULL;
      multifd_send_state->ops->send_cleanup(p, errp);
@@ -545,6 +549,7 @@ static void multifd_send_cleanup_state(void)
  {
      file_cleanup_outgoing_migration();
      socket_cleanup_outgoing_migration();
+    multifd_device_state_save_cleanup();
      qemu_sem_destroy(&multifd_send_state->channels_created);
      qemu_sem_destroy(&multifd_send_state->channels_ready);
      g_free(multifd_send_state->params);
@@ -670,19 +675,29 @@ static void *multifd_send_thread(void *opaque)
           * qatomic_store_release() in multifd_send().
           */
          if (qatomic_load_acquire(&p->pending_job)) {
+            bool is_device_state = multifd_payload_device_state(p->data);
+            size_t total_size;
+
              p->flags = 0;
              p->iovs_num = 0;
              assert(!multifd_payload_empty(p->data));
 
-            ret = multifd_send_state->ops->send_prepare(p, &local_err);
-            if (ret != 0) {
-                break;
+            if (is_device_state) {
+                multifd_device_state_send_prepare(p);
+            } else {
+                ret = multifd_send_state->ops->send_prepare(p, &local_err);
+                if (ret != 0) {
+                    break;
+                }
              }
 
              if (migrate_mapped_ram()) {
+                assert(!is_device_state);
+
                  ret = file_write_ramblock_iov(p->c, p->iov, p->iovs_num,
                                                &p->data->u.ram, &local_err);
              } else {
+                total_size = iov_size(p->iov, p->iovs_num);
                  ret = qio_channel_writev_full_all(p->c, p->iov, p->iovs_num,
                                                    NULL, 0, p->write_flags,
                                                    &local_err);
@@ -692,18 +707,27 @@ static void *multifd_send_thread(void *opaque)
                  break;
              }
 
Quoted 14 lines

migration/multifd.c static void *multifd_send_thread(void *opaque) · line 718

Quoted 11 lines
migration/multifd.c +9 -2
-            stat64_add(&mig_stats.multifd_bytes,
-                       p->next_packet_size + p->packet_len);
+            if (is_device_state) {
+                stat64_add(&mig_stats.multifd_bytes, total_size);
+            } else {
+                /*
+                 * Can't just always add total_size since IOVs do not include
+                 * packet header in the zerocopy RAM case.
+                 */
+                stat64_add(&mig_stats.multifd_bytes,
+                           p->next_packet_size + p->packet_len);

You could set total_size for both branches after send_prepare and use it here unconditionally.

Ack.

Quoted 100 lines
Quoted 100 lines
migration/multifd.c +9 -2
+            }
 
              p->next_packet_size = 0;
              multifd_send_data_clear(p->data);
 
              /*
               * Making sure p->data is published before saying "we're
-             * free".  Pairs with the smp_mb_acquire() in
+             * free".  Pairs with the qatomic_cmpxchg() in
               * multifd_send().
               */
              qatomic_store_release(&p->pending_job, false);
+            qatomic_store_release(&p->pending_job_preparing, false);
          } else {
              /*
               * If not a normal job, must be a sync request.  Note that
@@ -714,7 +738,7 @@ static void *multifd_send_thread(void *opaque)
 
              if (use_packets) {
                  p->flags = MULTIFD_FLAG_SYNC;
-                multifd_send_fill_packet(p);
+                multifd_send_fill_packet_ram(p);
                  ret = qio_channel_write_all(p->c, (void *)p->packet,
                                              p->packet_len, &local_err);
                  if (ret != 0) {
@@ -910,6 +934,9 @@ bool multifd_send_setup(void)
              p->packet_len = sizeof(MultiFDPacket_t)
                            + sizeof(uint64_t) * page_count;
              p->packet = g_malloc0(p->packet_len);
+            p->packet_device_state = g_malloc0(sizeof(*p->packet_device_state));
+            p->packet_device_state->hdr.magic = cpu_to_be32(MULTIFD_MAGIC);
+            p->packet_device_state->hdr.version = cpu_to_be32(MULTIFD_VERSION);
          }
          p->name = g_strdup_printf("mig/src/send_%d", i);
          p->write_flags = 0;
@@ -944,6 +971,8 @@ bool multifd_send_setup(void)
          }
      }
 
+    multifd_device_state_save_setup();
+
      return true;
 
  err:
migration/multifd.h +11 -2
index a0853622153e..c15c83104c8b 100644
@@ -120,10 +120,12 @@ typedef struct {
  typedef enum {
      MULTIFD_PAYLOAD_NONE,
      MULTIFD_PAYLOAD_RAM,
+    MULTIFD_PAYLOAD_DEVICE_STATE,
  } MultiFDPayloadType;
 
  typedef union MultiFDPayload {
      MultiFDPages_t ram;
+    MultiFDDeviceState_t device_state;
  } MultiFDPayload;
 
  struct MultiFDSendData {
@@ -136,6 +138,11 @@ static inline bool multifd_payload_empty(MultiFDSendData *data)
      return data->type == MULTIFD_PAYLOAD_NONE;
  }
 
+static inline bool multifd_payload_device_state(MultiFDSendData *data)
+{
+    return data->type == MULTIFD_PAYLOAD_DEVICE_STATE;
+}
+
  static inline void multifd_set_payload_type(MultiFDSendData *data,
                                              MultiFDPayloadType type)
  {
@@ -182,13 +189,15 @@ typedef struct {
       * cleared by the multifd sender threads.
       */
      bool pending_job;
+    bool pending_job_preparing;
      bool pending_sync;
      MultiFDSendData *data;
 
      /* thread local variables. No locking required */
 
-    /* pointer to the packet */
+    /* pointers to the possible packet types */
      MultiFDPacket_t *packet;
+    MultiFDPacketDeviceState_t *packet_device_state;
      /* size of the next packet that contains pages */
      uint32_t next_packet_size;
      /* packets sent through this channel */
@@ -276,18 +285,25 @@ typedef struct {
  } MultiFDMethods;
 
  void multifd_register_ops(int method, MultiFDMethods *ops);
-void multifd_send_fill_packet(MultiFDSendParams *p);
+void multifd_send_fill_packet_ram(MultiFDSendParams *p);
  bool multifd_send_prepare_common(MultiFDSendParams *p);
  void multifd_send_zero_page_detect(MultiFDSendParams *p);
  void multifd_recv_zero_page_process(MultiFDRecvParams *p);
 
Quoted 4 lines

migration/multifd.h typedef struct { · line 293

Quoted 2 lines
migration/multifd.h +1 -1
-static inline void multifd_send_prepare_header(MultiFDSendParams *p)
+static inline void multifd_send_prepare_header_ram(MultiFDSendParams *p)

This could instead go to multifd-nocomp.c and become multifd_ram_prepare_header.

Ack.

Quoted 11 lines

migration/multifd.h typedef struct { · line 300

Quoted 7 lines
migration/multifd.h +1 -0
  {
      p->iov[0].iov_len = p->packet_len;
      p->iov[0].iov_base = p->packet;
      p->iovs_num++;
  }
 
+static inline void multifd_send_prepare_header_device_state(MultiFDSendParams *p)

Seem like this could also move to multifd-device-state.c and drop the "send" part.

Ack.

Thanks,
Maciej