Skip to contentSkip to conversation

vfio/migration: Implement VFIO migration protocol v2

PATCH Superseded Avihai Horon 7 participants 43 messages May 12, 2022 – May 24, 2022

v1 of 11 Superseded Latest is v11 →

lore
Share & tools
lore
#0 lore raw

cover vfio/migration: Implement VFIO migration protocol v2

Hello,

Following VFIO migration protocol v2 acceptance in kernel, this series implements VFIO migration according to the new v2 protocol and replaces the now deprecated v1 implementation.

The main differences between v1 and v2 migration protocols are:
1. VFIO device state is represented as a finite state machine instead of a bitmap.

2. The migration interface with kernel is done using VFIO_DEVICE_FEATURE ioctl and normal read() and write() instead of the migration region used in v1.

3. Migration protocol v2 currently doesn't support the pre-copy phase of migration.

Full description of the v2 protocol and the differences from v1 can be found here [1].

Patches 1-5 are prep patches importing the new uAPI headers, fixing bugs and adding QEMUFile function that will be used later.

Patches 6-9 are the main patches that replace the v1 implementation with v2.

Thanks.

[1]
https://lore.kernel.org/all/[email protected]/

Avihai Horon (9):
linux-headers: Update headers to v5.18-rc6
vfio: Fix compilation errors caused by VFIO migration v1 deprecation vfio/migration: Fix NULL pointer dereference bug vfio/migration: Skip pre-copy if dirty page tracking is not supported migration/qemu-file: Add qemu_file_get_to_fd() vfio/migration: Implement VFIO migration protocol v2 vfio/migration: Reset device if setting recover state fails
vfio: Alphabetize migration section of VFIO trace-events file docs/devel: Align vfio-migration docs to VFIO migration v2

 docs/devel/vfio-migration.rst                 |  77 +--
 hw/vfio/common.c                              |  21 +-
 hw/vfio/migration.c                           | 640 ++++--------------
 hw/vfio/trace-events                          |  25 +-
 include/hw/vfio/vfio-common.h                 |   8 +-
 .../linux/input-event-codes.h                 |  25 +-
 .../standard-headers/linux/virtio_config.h    |   6 +
 .../standard-headers/linux/virtio_crypto.h    |  82 ++-
 linux-headers/asm-arm64/kvm.h                 |  16 +
 linux-headers/asm-generic/mman-common.h       |   2 +
 linux-headers/asm-mips/mman.h                 |   2 +
 linux-headers/linux/kvm.h                     |  27 +-
 linux-headers/linux/psci.h                    |   4 +
 linux-headers/linux/userfaultfd.h             |   8 +-
 linux-headers/linux/vfio.h                    | 406 ++++++-----
 linux-headers/linux/vhost.h                   |   7 +
 migration/migration.c                         |   5 +
 migration/migration.h                         |   3 +
 migration/qemu-file.c                         |  34 +
 migration/qemu-file.h                         |   1 +
 20 files changed, 618 insertions(+), 781 deletions(-)
Signature · 1 line
2.21.3
#1 lore raw

PATCH 1/9 linux-headers: Update headers to v5.18-rc6

---
 .../linux/input-event-codes.h                 |  25 +-
 .../standard-headers/linux/virtio_config.h    |   6 +
 .../standard-headers/linux/virtio_crypto.h    |  82 +++-
 linux-headers/asm-arm64/kvm.h                 |  16 +
 linux-headers/asm-generic/mman-common.h       |   2 +
 linux-headers/asm-mips/mman.h                 |   2 +
 linux-headers/linux/kvm.h                     |  27 +-
 linux-headers/linux/psci.h                    |   4 +
 linux-headers/linux/userfaultfd.h             |   8 +-
 linux-headers/linux/vfio.h                    | 406 +++++++++---------
 linux-headers/linux/vhost.h                   |   7 +
 11 files changed, 365 insertions(+), 220 deletions(-)
include/standard-headers/linux/input-event-codes.h +24 -1
index b5e86b40ab..50790aee5a 100644
@@ -278,7 +278,8 @@
 #define KEY_PAUSECD		201
 #define KEY_PROG3		202
 #define KEY_PROG4		203
-#define KEY_DASHBOARD		204	/* AL Dashboard */
+#define KEY_ALL_APPLICATIONS	204	/* AC Desktop Show All Applications */
+#define KEY_DASHBOARD		KEY_ALL_APPLICATIONS
 #define KEY_SUSPEND		205
 #define KEY_CLOSE		206	/* AC Close */
 #define KEY_PLAY		207
@@ -612,6 +613,7 @@
 #define KEY_ASSISTANT		0x247	/* AL Context-aware desktop assistant */
 #define KEY_KBD_LAYOUT_NEXT	0x248	/* AC Next Keyboard Layout Select */
 #define KEY_EMOJI_PICKER	0x249	/* Show/hide emoji picker (HUTRR101) */
+#define KEY_DICTATE		0x24a	/* Start or Stop Voice Dictation Session (HUTRR99) */
 
 #define KEY_BRIGHTNESS_MIN		0x250	/* Set Brightness to Minimum */
 #define KEY_BRIGHTNESS_MAX		0x251	/* Set Brightness to Maximum */
@@ -660,6 +662,27 @@
 /* Select an area of screen to be copied */
 #define KEY_SELECTIVE_SCREENSHOT	0x27a
 
+/* Move the focus to the next or previous user controllable element within a UI container */
+#define KEY_NEXT_ELEMENT               0x27b
+#define KEY_PREVIOUS_ELEMENT           0x27c
+
+/* Toggle Autopilot engagement */
+#define KEY_AUTOPILOT_ENGAGE_TOGGLE    0x27d
+
+/* Shortcut Keys */
+#define KEY_MARK_WAYPOINT              0x27e
+#define KEY_SOS                                0x27f
+#define KEY_NAV_CHART                  0x280
+#define KEY_FISHING_CHART              0x281
+#define KEY_SINGLE_RANGE_RADAR         0x282
+#define KEY_DUAL_RANGE_RADAR           0x283
+#define KEY_RADAR_OVERLAY              0x284
+#define KEY_TRADITIONAL_SONAR          0x285
+#define KEY_CLEARVU_SONAR              0x286
+#define KEY_SIDEVU_SONAR               0x287
+#define KEY_NAV_INFO                   0x288
+#define KEY_BRIGHTNESS_MENU            0x289
+
 /*
  * Some keyboards have keys which do not have a defined meaning, these keys
  * are intended to be programmed / bound to macros by the user. For most
include/standard-headers/linux/virtio_config.h +6 -0
index 22e3a85f67..7acd8d4abc 100644
@@ -80,6 +80,12 @@
 /* This feature indicates support for the packed virtqueue layout. */
 #define VIRTIO_F_RING_PACKED		34
 
+/*
+ * Inorder feature indicates that all buffers are used by the device
+ * in the same order in which they have been made available.
+ */
+#define VIRTIO_F_IN_ORDER		35
+
 /*
  * This feature indicates that memory accesses by the driver and the
  * device are ordered in a way described by the platform.
include/standard-headers/linux/virtio_crypto.h +81 -1

136 lines not on this page · raw message

linux-headers/asm-arm64/kvm.h +16 -0
index 3d2ce9912d..5c28a9737a 100644
@@ -281,6 +281,11 @@ struct kvm_arm_copy_mte_tags {
 #define KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_2_NOT_REQUIRED	3
 #define KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_2_ENABLED     	(1U << 4)
 
+#define KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_3	KVM_REG_ARM_FW_REG(3)
+#define KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_3_NOT_AVAIL		0
+#define KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_3_AVAIL		1
+#define KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_3_NOT_REQUIRED	2
+
 /* SVE registers */
 #define KVM_REG_ARM64_SVE		(0x15 << KVM_REG_ARM_COPROC_SHIFT)
 
@@ -362,6 +367,7 @@ struct kvm_arm_copy_mte_tags {
 #define   KVM_ARM_VCPU_PMU_V3_IRQ	0
 #define   KVM_ARM_VCPU_PMU_V3_INIT	1
 #define   KVM_ARM_VCPU_PMU_V3_FILTER	2
+#define   KVM_ARM_VCPU_PMU_V3_SET_PMU	3
 #define KVM_ARM_VCPU_TIMER_CTRL		1
 #define   KVM_ARM_VCPU_TIMER_IRQ_VTIMER		0
 #define   KVM_ARM_VCPU_TIMER_IRQ_PTIMER		1
@@ -411,6 +417,16 @@ struct kvm_arm_copy_mte_tags {
 #define KVM_PSCI_RET_INVAL		PSCI_RET_INVALID_PARAMS
 #define KVM_PSCI_RET_DENIED		PSCI_RET_DENIED
 
+/* arm64-specific kvm_run::system_event flags */
+/*
+ * Reset caused by a PSCI v1.1 SYSTEM_RESET2 call.
+ * Valid only when the system event has a type of KVM_SYSTEM_EVENT_RESET.
+ */
+#define KVM_SYSTEM_EVENT_RESET_FLAG_PSCI_RESET2	(1ULL << 0)
+
+/* run->fail_entry.hardware_entry_failure_reason codes. */
+#define KVM_EXIT_FAIL_ENTRY_CPU_UNSUPPORTED	(1ULL << 0)
+
 #endif
 
 #endif /* __ARM_KVM_H__ */
linux-headers/asm-generic/mman-common.h +2 -0
index 1567a3294c..6c1aa92a92 100644
@@ -75,6 +75,8 @@
 #define MADV_POPULATE_READ	22	/* populate (prefault) page tables readable */
 #define MADV_POPULATE_WRITE	23	/* populate (prefault) page tables writable */
 
+#define MADV_DONTNEED_LOCKED	24	/* like DONTNEED, but drop locked pages too */
+
 /* compatibility flags */
 #define MAP_FILE	0
 
linux-headers/asm-mips/mman.h +2 -0
index 40b210c65a..1be428663c 100644
@@ -101,6 +101,8 @@
 #define MADV_POPULATE_READ	22	/* populate (prefault) page tables readable */
 #define MADV_POPULATE_WRITE	23	/* populate (prefault) page tables writable */
 
+#define MADV_DONTNEED_LOCKED	24	/* like DONTNEED, but drop locked pages too */
+
 /* compatibility flags */
 #define MAP_FILE	0
 
linux-headers/linux/kvm.h +21 -6
index d232feaae9..0d05d02ee4 100644
@@ -445,7 +445,11 @@ struct kvm_run {
 #define KVM_SYSTEM_EVENT_RESET          2
 #define KVM_SYSTEM_EVENT_CRASH          3
 			__u32 type;
-			__u64 flags;
+			__u32 ndata;
+			union {
+				__u64 flags;
+				__u64 data[16];
+			};
 		} system_event;
 		/* KVM_EXIT_S390_STSI */
 		struct {
@@ -562,9 +566,12 @@ struct kvm_s390_mem_op {
 	__u32 op;		/* type of operation */
 	__u64 buf;		/* buffer in userspace */
 	union {
-		__u8 ar;	/* the access register number */
+		struct {
+			__u8 ar;	/* the access register number */
+			__u8 key;	/* access key, ignored if flag unset */
+		};
 		__u32 sida_offset; /* offset into the sida */
-		__u8 reserved[32]; /* should be set to 0 */
+		__u8 reserved[32]; /* ignored */
 	};
 };
 /* types for kvm_s390_mem_op->op */
@@ -572,9 +579,12 @@ struct kvm_s390_mem_op {
 #define KVM_S390_MEMOP_LOGICAL_WRITE	1
 #define KVM_S390_MEMOP_SIDA_READ	2
 #define KVM_S390_MEMOP_SIDA_WRITE	3
+#define KVM_S390_MEMOP_ABSOLUTE_READ	4
+#define KVM_S390_MEMOP_ABSOLUTE_WRITE	5
 /* flags for kvm_s390_mem_op->flags */
 #define KVM_S390_MEMOP_F_CHECK_ONLY		(1ULL << 0)
 #define KVM_S390_MEMOP_F_INJECT_EXCEPTION	(1ULL << 1)
+#define KVM_S390_MEMOP_F_SKEY_PROTECTION	(1ULL << 2)
 
 /* for KVM_INTERRUPT */
 struct kvm_interrupt {
@@ -1134,6 +1144,12 @@ struct kvm_ppc_resize_hpt {
 #define KVM_CAP_VM_GPA_BITS 207
 #define KVM_CAP_XSAVE2 208
 #define KVM_CAP_SYS_ATTRIBUTES 209
+#define KVM_CAP_PPC_AIL_MODE_3 210
+#define KVM_CAP_S390_MEM_OP_EXTENSION 211
+#define KVM_CAP_PMU_CAPABILITY 212
+#define KVM_CAP_DISABLE_QUIRKS2 213
+/* #define KVM_CAP_VM_TSC_CONTROL 214 */
+#define KVM_CAP_SYSTEM_EVENT_DATA 215
 
 #ifdef KVM_CAP_IRQ_ROUTING
 
@@ -1624,9 +1640,6 @@ struct kvm_enc_region {
 #define KVM_S390_NORMAL_RESET	_IO(KVMIO,   0xc3)
 #define KVM_S390_CLEAR_RESET	_IO(KVMIO,   0xc4)
 
-/* Available with KVM_CAP_XSAVE2 */
-#define KVM_GET_XSAVE2		  _IOR(KVMIO,  0xcf, struct kvm_xsave)
-
 struct kvm_s390_pv_sec_parm {
 	__u64 origin;
 	__u64 length;
@@ -1973,6 +1986,8 @@ struct kvm_dirty_gfn {
 #define KVM_BUS_LOCK_DETECTION_OFF             (1 << 0)
 #define KVM_BUS_LOCK_DETECTION_EXIT            (1 << 1)
 
+#define KVM_PMU_CAP_DISABLE                    (1 << 0)
+
 /**
  * struct kvm_stats_header - Header of per vm/vcpu binary statistics data.
  * @flags: Some extra information for header, always 0 for now.
linux-headers/linux/psci.h +4 -0
index a6772d508b..213b2a0f70 100644
@@ -82,6 +82,10 @@
 #define PSCI_0_2_TOS_UP_NO_MIGRATE		1
 #define PSCI_0_2_TOS_MP				2
 
+/* PSCI v1.1 reset type encoding for SYSTEM_RESET2 */
+#define PSCI_1_1_RESET_TYPE_SYSTEM_WARM_RESET	0
+#define PSCI_1_1_RESET_TYPE_VENDOR_START	0x80000000U
+
 /* PSCI version decoding (independent of PSCI version) */
 #define PSCI_VERSION_MAJOR_SHIFT		16
 #define PSCI_VERSION_MINOR_MASK			\
linux-headers/linux/userfaultfd.h +7 -1
index 8479af5f4c..769b8379e4 100644
@@ -32,7 +32,8 @@
 			   UFFD_FEATURE_SIGBUS |		\
 			   UFFD_FEATURE_THREAD_ID |		\
 			   UFFD_FEATURE_MINOR_HUGETLBFS |	\
-			   UFFD_FEATURE_MINOR_SHMEM)
+			   UFFD_FEATURE_MINOR_SHMEM |		\
+			   UFFD_FEATURE_EXACT_ADDRESS)
 #define UFFD_API_IOCTLS				\
 	((__u64)1 << _UFFDIO_REGISTER |		\
 	 (__u64)1 << _UFFDIO_UNREGISTER |	\
@@ -189,6 +190,10 @@ struct uffdio_api {
 	 *
 	 * UFFD_FEATURE_MINOR_SHMEM indicates the same support as
 	 * UFFD_FEATURE_MINOR_HUGETLBFS, but for shmem-backed pages instead.
+	 *
+	 * UFFD_FEATURE_EXACT_ADDRESS indicates that the exact address of page
+	 * faults would be provided and the offset within the page would not be
+	 * masked.
 	 */
 #define UFFD_FEATURE_PAGEFAULT_FLAG_WP		(1<<0)
 #define UFFD_FEATURE_EVENT_FORK			(1<<1)
@@ -201,6 +206,7 @@ struct uffdio_api {
 #define UFFD_FEATURE_THREAD_ID			(1<<8)
 #define UFFD_FEATURE_MINOR_HUGETLBFS		(1<<9)
 #define UFFD_FEATURE_MINOR_SHMEM		(1<<10)
+#define UFFD_FEATURE_EXACT_ADDRESS		(1<<11)
 	__u64 features;
 
 	__u64 ioctls;
linux-headers/linux/vfio.h +195 -211

433 lines not on this page · raw message

linux-headers/linux/vhost.h +7 -0
index c998860d7b..5d99e7c242 100644
@@ -150,4 +150,11 @@
 /* Get the valid iova range */
 #define VHOST_VDPA_GET_IOVA_RANGE	_IOR(VHOST_VIRTIO, 0x78, \
 					     struct vhost_vdpa_iova_range)
+
+/* Get the config size */
+#define VHOST_VDPA_GET_CONFIG_SIZE	_IOR(VHOST_VIRTIO, 0x79, __u32)
+
+/* Get the count of all virtqueues */
+#define VHOST_VDPA_GET_VQS_COUNT	_IOR(VHOST_VIRTIO, 0x80, __u32)
+
 #endif
Signature · 1 line
2.21.3
#2 lore raw

PATCH 2/9 vfio: Fix compilation errors caused by VFIO migration v1 deprecation

In reply to Avihai Horon

VFIO migration protocol v1 was deprecated and as part of it some of the uAPI definitions were renamed. This caused compilation errors. Fix them.

---
 hw/vfio/common.c    |  6 +++---
 hw/vfio/migration.c | 29 ++++++++++++++++-------------
 2 files changed, 19 insertions(+), 16 deletions(-)
hw/vfio/common.c +3 -3
index 159f910421..29982c7af8 100644
@@ -355,7 +355,7 @@ static bool vfio_devices_all_dirty_tracking(VFIOContainer *container)
             }
 
             if ((vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF)
-                && (migration->device_state & VFIO_DEVICE_STATE_RUNNING)) {
+                && (migration->device_state & VFIO_DEVICE_STATE_V1_RUNNING)) {
                 return false;
             }
         }
@@ -381,8 +381,8 @@ static bool vfio_devices_all_running_and_saving(VFIOContainer *container)
                 return false;
             }
 
-            if ((migration->device_state & VFIO_DEVICE_STATE_SAVING) &&
-                (migration->device_state & VFIO_DEVICE_STATE_RUNNING)) {
+            if ((migration->device_state & VFIO_DEVICE_STATE_V1_SAVING) &&
+                (migration->device_state & VFIO_DEVICE_STATE_V1_RUNNING)) {
                 continue;
             } else {
                 return false;
hw/vfio/migration.c +16 -13
index ff6b45de6b..835608cd23 100644
@@ -432,7 +432,7 @@ static int vfio_save_setup(QEMUFile *f, void *opaque)
     }
 
     ret = vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_MASK,
-                                   VFIO_DEVICE_STATE_SAVING);
+                                   VFIO_DEVICE_STATE_V1_SAVING);
     if (ret) {
         error_report("%s: Failed to set state SAVING", vbasedev->name);
         return ret;
@@ -531,8 +531,8 @@ static int vfio_save_complete_precopy(QEMUFile *f, void *opaque)
     uint64_t data_size;
     int ret;
 
-    ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_RUNNING,
-                                   VFIO_DEVICE_STATE_SAVING);
+    ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_V1_RUNNING,
+                                   VFIO_DEVICE_STATE_V1_SAVING);
     if (ret) {
         error_report("%s: Failed to set state STOP and SAVING",
                      vbasedev->name);
@@ -569,7 +569,7 @@ static int vfio_save_complete_precopy(QEMUFile *f, void *opaque)
         return ret;
     }
 
-    ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_SAVING, 0);
+    ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_V1_SAVING, 0);
     if (ret) {
         error_report("%s: Failed to set state STOPPED", vbasedev->name);
         return ret;
@@ -609,7 +609,7 @@ static int vfio_load_setup(QEMUFile *f, void *opaque)
     }
 
     ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_MASK,
-                                   VFIO_DEVICE_STATE_RESUMING);
+                                   VFIO_DEVICE_STATE_V1_RESUMING);
     if (ret) {
         error_report("%s: Failed to set state RESUMING", vbasedev->name);
         if (migration->region.mmaps) {
@@ -717,20 +717,20 @@ static void vfio_vmstate_change(void *opaque, bool running, RunState state)
          * In both the above cases, set _RUNNING bit.
          */
         mask = ~VFIO_DEVICE_STATE_MASK;
-        value = VFIO_DEVICE_STATE_RUNNING;
+        value = VFIO_DEVICE_STATE_V1_RUNNING;
     } else {
         /*
          * Here device state could be either _RUNNING or _SAVING|_RUNNING. Reset
          * _RUNNING bit
          */
-        mask = ~VFIO_DEVICE_STATE_RUNNING;
+        mask = ~VFIO_DEVICE_STATE_V1_RUNNING;
 
         /*
          * When VM state transition to stop for savevm command, device should
          * start saving data.
          */
         if (state == RUN_STATE_SAVE_VM) {
-            value = VFIO_DEVICE_STATE_SAVING;
+            value = VFIO_DEVICE_STATE_V1_SAVING;
         } else {
             value = 0;
         }
@@ -767,9 +767,10 @@ static void vfio_migration_state_notifier(Notifier *notifier, void *data)
     case MIGRATION_STATUS_CANCELLED:
     case MIGRATION_STATUS_FAILED:
         bytes_transferred = 0;
-        ret = vfio_migration_set_state(vbasedev,
-                      ~(VFIO_DEVICE_STATE_SAVING | VFIO_DEVICE_STATE_RESUMING),
-                      VFIO_DEVICE_STATE_RUNNING);
+        ret = vfio_migration_set_state(
+            vbasedev,
+            ~(VFIO_DEVICE_STATE_V1_SAVING | VFIO_DEVICE_STATE_V1_RESUMING),
+            VFIO_DEVICE_STATE_V1_RUNNING);
         if (ret) {
             error_report("%s: Failed to set state RUNNING", vbasedev->name);
         }
@@ -864,8 +865,10 @@ int vfio_migration_probe(VFIODevice *vbasedev, Error **errp)
         goto add_blocker;
     }
 
-    ret = vfio_get_dev_region_info(vbasedev, VFIO_REGION_TYPE_MIGRATION,
-                                   VFIO_REGION_SUBTYPE_MIGRATION, &info);
+    ret = vfio_get_dev_region_info(vbasedev,
+                                   VFIO_REGION_TYPE_MIGRATION_DEPRECATED,
+                                   VFIO_REGION_SUBTYPE_MIGRATION_DEPRECATED,
+                                   &info);
     if (ret) {
         goto add_blocker;
     }
Signature · 1 line
2.21.3
#3 lore raw

Re: [PATCH 2/9] vfio: Fix compilation errors caused by VFIO migration v1 deprecation

Quoted 101 lines · On Thu, 12 May 2022 18:43:13 +0300 Avihai Horon <[email protected]> wrote:

VFIO migration protocol v1 was deprecated and as part of it some of the uAPI definitions were renamed. This caused compilation errors. Fix them.

---
 hw/vfio/common.c    |  6 +++---
 hw/vfio/migration.c | 29 ++++++++++++++++-------------
 2 files changed, 19 insertions(+), 16 deletions(-)
hw/vfio/common.c +3 -3
index 159f910421..29982c7af8 100644
@@ -355,7 +355,7 @@ static bool vfio_devices_all_dirty_tracking(VFIOContainer *container)
             }
 
             if ((vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF)
-                && (migration->device_state & VFIO_DEVICE_STATE_RUNNING)) {
+                && (migration->device_state & VFIO_DEVICE_STATE_V1_RUNNING)) {
                 return false;
             }
         }
@@ -381,8 +381,8 @@ static bool vfio_devices_all_running_and_saving(VFIOContainer *container)
                 return false;
             }
 
-            if ((migration->device_state & VFIO_DEVICE_STATE_SAVING) &&
-                (migration->device_state & VFIO_DEVICE_STATE_RUNNING)) {
+            if ((migration->device_state & VFIO_DEVICE_STATE_V1_SAVING) &&
+                (migration->device_state & VFIO_DEVICE_STATE_V1_RUNNING)) {
                 continue;
             } else {
                 return false;
hw/vfio/migration.c +8 -8
index ff6b45de6b..835608cd23 100644
@@ -432,7 +432,7 @@ static int vfio_save_setup(QEMUFile *f, void *opaque)
     }
 
     ret = vfio_migration_set_state(vbasedev, VFIO_DEVICE_STATE_MASK,
-                                   VFIO_DEVICE_STATE_SAVING);
+                                   VFIO_DEVICE_STATE_V1_SAVING);
     if (ret) {
         error_report("%s: Failed to set state SAVING", vbasedev->name);
         return ret;
@@ -531,8 +531,8 @@ static int vfio_save_complete_precopy(QEMUFile *f, void *opaque)
     uint64_t data_size;
     int ret;
 
-    ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_RUNNING,
-                                   VFIO_DEVICE_STATE_SAVING);
+    ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_V1_RUNNING,
+                                   VFIO_DEVICE_STATE_V1_SAVING);
     if (ret) {
         error_report("%s: Failed to set state STOP and SAVING",
                      vbasedev->name);
@@ -569,7 +569,7 @@ static int vfio_save_complete_precopy(QEMUFile *f, void *opaque)
         return ret;
     }
 
-    ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_SAVING, 0);
+    ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_V1_SAVING, 0);
     if (ret) {
         error_report("%s: Failed to set state STOPPED", vbasedev->name);
         return ret;
@@ -609,7 +609,7 @@ static int vfio_load_setup(QEMUFile *f, void *opaque)
     }
 
     ret = vfio_migration_set_state(vbasedev, ~VFIO_DEVICE_STATE_MASK,
-                                   VFIO_DEVICE_STATE_RESUMING);
+                                   VFIO_DEVICE_STATE_V1_RESUMING);
     if (ret) {
         error_report("%s: Failed to set state RESUMING", vbasedev->name);
         if (migration->region.mmaps) {
@@ -717,20 +717,20 @@ static void vfio_vmstate_change(void *opaque, bool running, RunState state)
          * In both the above cases, set _RUNNING bit.
          */
         mask = ~VFIO_DEVICE_STATE_MASK;
-        value = VFIO_DEVICE_STATE_RUNNING;
+        value = VFIO_DEVICE_STATE_V1_RUNNING;
     } else {
         /*
          * Here device state could be either _RUNNING or _SAVING|_RUNNING. Reset
          * _RUNNING bit
          */
-        mask = ~VFIO_DEVICE_STATE_RUNNING;
+        mask = ~VFIO_DEVICE_STATE_V1_RUNNING;
 
         /*
          * When VM state transition to stop for savevm command, device should
          * start saving data.
          */
         if (state == RUN_STATE_SAVE_VM) {
-            value = VFIO_DEVICE_STATE_SAVING;
+            value = VFIO_DEVICE_STATE_V1_SAVING;
         } else {
             value = 0;
         }

hw/vfio/migration.c static void vfio_migration_state_notifier(Notifier *notifier, void *data) · line 773

Quoted 10 lines
hw/vfio/migration.c +4 -3
@@ -767,9 +767,10 @@ static void vfio_migration_state_notifier(Notifier *notifier, void *data)
     case MIGRATION_STATUS_CANCELLED:
     case MIGRATION_STATUS_FAILED:
         bytes_transferred = 0;
-        ret = vfio_migration_set_state(vbasedev,
-                      ~(VFIO_DEVICE_STATE_SAVING | VFIO_DEVICE_STATE_RESUMING),
-                      VFIO_DEVICE_STATE_RUNNING);
+        ret = vfio_migration_set_state(
+            vbasedev,
+            ~(VFIO_DEVICE_STATE_V1_SAVING | VFIO_DEVICE_STATE_V1_RESUMING),
+            VFIO_DEVICE_STATE_V1_RUNNING);

Yikes! Please follow the line wrapping used elsewhere. There's no need to put the first arg on a new line and subsequent wrapped lines should be indented to match the previous line, or at least to avoid wrapping itself. Here we can use something like:

        ret = vfio_migration_set_state(vbasedev,
                                       ~(VFIO_DEVICE_STATE_V1_SAVING |
                                         VFIO_DEVICE_STATE_V1_RESUMING),
                                       VFIO_DEVICE_STATE_V1_RUNNING);

Thanks,
Alex

Quoted 16 lines
hw/vfio/migration.c +4 -2
         if (ret) {
             error_report("%s: Failed to set state RUNNING", vbasedev->name);
         }
@@ -864,8 +865,10 @@ int vfio_migration_probe(VFIODevice *vbasedev, Error **errp)
         goto add_blocker;
     }
 
-    ret = vfio_get_dev_region_info(vbasedev, VFIO_REGION_TYPE_MIGRATION,
-                                   VFIO_REGION_SUBTYPE_MIGRATION, &info);
+    ret = vfio_get_dev_region_info(vbasedev,
+                                   VFIO_REGION_TYPE_MIGRATION_DEPRECATED,
+                                   VFIO_REGION_SUBTYPE_MIGRATION_DEPRECATED,
+                                   &info);
     if (ret) {
         goto add_blocker;
     }
#4 lore raw

Re: [PATCH 2/9] vfio: Fix compilation errors caused by VFIO migration v1 deprecation

Quoted 8 lines · Alex Williamson
Quoted 8 lines
hw/vfio/migration.c +1 -3
@@ -767,9 +767,10 @@ static void vfio_migration_state_notifier(Notifier *notifier, void *data)
     case MIGRATION_STATUS_CANCELLED:
     case MIGRATION_STATUS_FAILED:
         bytes_transferred = 0;
-        ret = vfio_migration_set_state(vbasedev,
-                      ~(VFIO_DEVICE_STATE_SAVING | VFIO_DEVICE_STATE_RESUMING),
-                      VFIO_DEVICE_STATE_RUNNING);
+        ret = vfio_migration_set_state(
Quoted 8 lines

hw/vfio/migration.c static void vfio_migration_state_notifier(Notifier *notifier, void *data) · line 773

Quoted 3 lines
hw/vfio/migration.c +3 -0
+            vbasedev,
+            ~(VFIO_DEVICE_STATE_V1_SAVING | VFIO_DEVICE_STATE_V1_RESUMING),
+            VFIO_DEVICE_STATE_V1_RUNNING);

Yikes! Please follow the line wrapping used elsewhere. There's no need to put the first arg on a new line and subsequent wrapped lines should be indented to match the previous line, or at least to avoid wrapping itself. Here we can use something like:

This is generated by clang-format with one of the qmeu styles, it follows the documented guide:

In case of function, there are several variants:

- 4 spaces indent from the beginning
- align the secondary lines just after the opening parenthesis of the first

clang-format selected the first option due to its optimization algorithm.

Knowing nothing about qmeu, I am confused??

Jason

#5 lore raw

Re: [PATCH 2/9] vfio: Fix compilation errors caused by VFIO migration v1 deprecation

Quoted 23 lines · On Thu, 12 May 2022 15:25:32 -0300 Jason Gunthorpe <[email protected]> wrote:
Quoted 8 lines · Alex Williamson
Quoted 8 lines
hw/vfio/migration.c +1 -3
@@ -767,9 +767,10 @@ static void vfio_migration_state_notifier(Notifier *notifier, void *data)
     case MIGRATION_STATUS_CANCELLED:
     case MIGRATION_STATUS_FAILED:
         bytes_transferred = 0;
-        ret = vfio_migration_set_state(vbasedev,
-                      ~(VFIO_DEVICE_STATE_SAVING | VFIO_DEVICE_STATE_RESUMING),
-                      VFIO_DEVICE_STATE_RUNNING);
+        ret = vfio_migration_set_state(
Quoted 8 lines

hw/vfio/migration.c static void vfio_migration_state_notifier(Notifier *notifier, void *data) · line 773

Quoted 3 lines
hw/vfio/migration.c +3 -0
+            vbasedev,
+            ~(VFIO_DEVICE_STATE_V1_SAVING | VFIO_DEVICE_STATE_V1_RESUMING),
+            VFIO_DEVICE_STATE_V1_RUNNING);  

Yikes! Please follow the line wrapping used elsewhere. There's no need to put the first arg on a new line and subsequent wrapped lines should be indented to match the previous line, or at least to avoid wrapping itself. Here we can use something like:

This is generated by clang-format with one of the qmeu styles, it follows the documented guide:

In case of function, there are several variants:

Quoted 8 lines

- 4 spaces indent from the beginning
- align the secondary lines just after the opening parenthesis of the first

clang-format selected the first option due to its optimization algorithm.

Knowing nothing about qmeu, I am confused??

Maybe someone needs to throw more AI models at clang-format so that it considers the more readable option? QEMU does a lot wrong with style imo, and maybe it's technically compliant as written, but I think what I proposed is also compliant, as well as more readable and more consistent with the existing file. Thanks,

Alex

#6 lore raw

Re: [PATCH 2/9] vfio: Fix compilation errors caused by VFIO migration v1 deprecation

Quoted 33 lines · Alex Williamson
Quoted 30 lines · On Thu, 12 May 2022 15:25:32 -0300 Jason Gunthorpe <[email protected]> wrote:
Quoted 8 lines · Alex Williamson
Quoted 8 lines
hw/vfio/migration.c +1 -3
@@ -767,9 +767,10 @@ static void vfio_migration_state_notifier(Notifier *notifier, void *data)
     case MIGRATION_STATUS_CANCELLED:
     case MIGRATION_STATUS_FAILED:
         bytes_transferred = 0;
-        ret = vfio_migration_set_state(vbasedev,
-                      ~(VFIO_DEVICE_STATE_SAVING | VFIO_DEVICE_STATE_RESUMING),
-                      VFIO_DEVICE_STATE_RUNNING);
+        ret = vfio_migration_set_state(
Quoted 8 lines

hw/vfio/migration.c static void vfio_migration_state_notifier(Notifier *notifier, void *data) · line 773

Quoted 3 lines
hw/vfio/migration.c +3 -0
+            vbasedev,
+            ~(VFIO_DEVICE_STATE_V1_SAVING | VFIO_DEVICE_STATE_V1_RESUMING),
+            VFIO_DEVICE_STATE_V1_RUNNING);  

Yikes! Please follow the line wrapping used elsewhere. There's no need to put the first arg on a new line and subsequent wrapped lines should be indented to match the previous line, or at least to avoid wrapping itself. Here we can use something like:

This is generated by clang-format with one of the qmeu styles, it follows the documented guide:

In case of function, there are several variants:

- 4 spaces indent from the beginning
- align the secondary lines just after the opening parenthesis of the first

clang-format selected the first option due to its optimization algorithm.

Quoted 7 lines
Quoted 1 line

Knowing nothing about qmeu, I am confused??

Maybe someone needs to throw more AI models at clang-format so that it considers the more readable option? QEMU does a lot wrong with style imo, and maybe it's technically compliant as written, but I think what I proposed is also compliant, as well as more readable and more consistent with the existing file. Thanks,

Let Avihai know any indenting you don't like he will fix it.

IIRC clang scores line-breaking an expression as worse than going to the smaller indent. Personally I would agree with this.

Thanks,
Jason

#7 lore raw

Re: [PATCH 2/9] vfio: Fix compilation errors caused by VFIO migration v1 deprecation

In reply to Alex Williamson
Quoted 20 lines · Alex Williamson

hw/vfio/migration.c static void vfio_migration_state_notifier(Notifier *notifier, void *data) · line 773

Quoted 11 lines · On Thu, 12 May 2022 18:43:13 +0300 Avihai Horon <[email protected]> wrote:
hw/vfio/migration.c +4 -3
@@ -767,9 +767,10 @@ static void vfio_migration_state_notifier(Notifier *notifier, void *data)
     case MIGRATION_STATUS_CANCELLED:
     case MIGRATION_STATUS_FAILED:
         bytes_transferred = 0;
-        ret = vfio_migration_set_state(vbasedev,
-                      ~(VFIO_DEVICE_STATE_SAVING | VFIO_DEVICE_STATE_RESUMING),
-                      VFIO_DEVICE_STATE_RUNNING);
+        ret = vfio_migration_set_state(
+            vbasedev,
+            ~(VFIO_DEVICE_STATE_V1_SAVING | VFIO_DEVICE_STATE_V1_RESUMING),
+            VFIO_DEVICE_STATE_V1_RUNNING);

Yikes! Please follow the line wrapping used elsewhere. There's no need to put the first arg on a new line and subsequent wrapped lines should be indented to match the previous line, or at least to avoid wrapping itself. Here we can use something like:

Quoted 4 lines
        ret = vfio_migration_set_state(vbasedev,
                                       ~(VFIO_DEVICE_STATE_V1_SAVING |
                                         VFIO_DEVICE_STATE_V1_RESUMING),
                                       VFIO_DEVICE_STATE_V1_RUNNING);

FWIW, I'd prefer this variant as well.

#8 lore raw

PATCH 3/9 vfio/migration: Fix NULL pointer dereference bug

In reply to Avihai Horon

As part of its error flow, vfio_vmstate_change() accesses MigrationState->to_dst_file without any checks. This can cause a NULL pointer dereference if the error flow is taken and MigrationState->to_dst_file is not set.

For example, this can happen if VM is started or stopped not during migration and vfio_vmstate_change() error flow is taken, as MigrationState->to_dst_file is not set at that time.

Fix it by checking that MigrationState->to_dst_file is set before using it.

Fixes 02a7e71b1e5b ("vfio: Add VM state change handler to know state of VM")
---
 hw/vfio/migration.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
hw/vfio/migration.c +3 -1
index 835608cd23..21e8f9d4d4 100644
@@ -744,7 +744,9 @@ static void vfio_vmstate_change(void *opaque, bool running, RunState state)
          */
         error_report("%s: Failed to set device state 0x%x", vbasedev->name,
                      (migration->device_state & mask) | value);
-        qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
+        if (migrate_get_current()->to_dst_file) {
+            qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
+        }
     }
     vbasedev->migration->vm_running = running;
     trace_vfio_vmstate_change(vbasedev->name, running, RunState_str(state),
Signature · 1 line
2.21.3
Reviewed-by on v1 3/9
#9 lore raw

Re: [PATCH 3/9] vfio/migration: Fix NULL pointer dereference bug

Quoted 23 lines · Avihai Horon

As part of its error flow, vfio_vmstate_change() accesses MigrationState->to_dst_file without any checks. This can cause a NULL pointer dereference if the error flow is taken and MigrationState->to_dst_file is not set.

For example, this can happen if VM is started or stopped not during migration and vfio_vmstate_change() error flow is taken, as MigrationState->to_dst_file is not set at that time.

Fix it by checking that MigrationState->to_dst_file is set before using it.

Fixes 02a7e71b1e5b ("vfio: Add VM state change handler to know state of VM")
---
 hw/vfio/migration.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
hw/vfio/migration.c +0 -0
index 835608cd23..21e8f9d4d4 100644

hw/vfio/migration.c static void vfio_vmstate_change(void *opaque, bool running, RunState state) · line 750

Quoted 8 lines
hw/vfio/migration.c +3 -1
@@ -744,7 +744,9 @@ static void vfio_vmstate_change(void *opaque, bool running, RunState state)
          */
         error_report("%s: Failed to set device state 0x%x", vbasedev->name,
                      (migration->device_state & mask) | value);
-        qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
+        if (migrate_get_current()->to_dst_file) {
+            qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
+        }
     }

I mean that the change is right.

But I am not so sure about using qemu_file_* operations outside of the migration_thread. I *think* that everything else that uses qemu_file_* functions is operating inside the migration_thread, and this one don't look like it. Furthermore, a fast look at qemu source, I can't see anyplace where we setup an error in a vmstate_change.

Later, Juan.

Quoted 2 lines
hw/vfio/migration.c +0 -0
     vbasedev->migration->vm_running = running;
     trace_vfio_vmstate_change(vbasedev->name, running, RunState_str(state),
#10 lore raw

Re: [PATCH 3/9] vfio/migration: Fix NULL pointer dereference bug

Quoted 37 lines · Juan Quintela

External email: Use caution opening links or attachments

Quoted 23 lines · Avihai Horon

As part of its error flow, vfio_vmstate_change() accesses MigrationState->to_dst_file without any checks. This can cause a NULL pointer dereference if the error flow is taken and MigrationState->to_dst_file is not set.

For example, this can happen if VM is started or stopped not during migration and vfio_vmstate_change() error flow is taken, as MigrationState->to_dst_file is not set at that time.

Fix it by checking that MigrationState->to_dst_file is set before using it.

Fixes 02a7e71b1e5b ("vfio: Add VM state change handler to know state of VM")
---
  hw/vfio/migration.c | 4 +++-
  1 file changed, 3 insertions(+), 1 deletion(-)
hw/vfio/migration.c +0 -0
index 835608cd23..21e8f9d4d4 100644

hw/vfio/migration.c static void vfio_vmstate_change(void *opaque, bool running, RunState state) · line 750

Quoted 8 lines
hw/vfio/migration.c +3 -1
@@ -744,7 +744,9 @@ static void vfio_vmstate_change(void *opaque, bool running, RunState state)
           */
          error_report("%s: Failed to set device state 0x%x", vbasedev->name,
                       (migration->device_state & mask) | value);
-        qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
+        if (migrate_get_current()->to_dst_file) {
+            qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
+        }
      }
Quoted 7 lines

I mean that the change is right.

But I am not so sure about using qemu_file_* operations outside of the migration_thread. I *think* that everything else that uses qemu_file_* functions is operating inside the migration_thread, and this one don't look like it. Furthermore, a fast look at qemu source, I can't see anyplace where we setup an error in a vmstate_change.

vfio_vmstate_change() will operate inside migration_thread if migration_thread is the one that called vm start/stop.

In cases where vm start/stop was not called by migration_thread, it will operate outside of migration_thread. But I think in such cases to_dst_file should not be set.

Ideally we should have returned error, but vm_state_notify() doesn't report errors.

Maybe later we can change vm_state_notify() to support error reporting, or instead of using to_dst_file to indicate an error, update some flag in VFIOMigration.

Thanks.

Quoted 5 lines

Later, Juan.

Quoted 2 lines
hw/vfio/migration.c +0 -0
      vbasedev->migration->vm_running = running;
      trace_vfio_vmstate_change(vbasedev->name, running, RunState_str(state),
#11 lore raw

Re: [PATCH 3/9] vfio/migration: Fix NULL pointer dereference bug

Quoted 53 lines · Avihai Horon
Quoted 37 lines · Juan Quintela

External email: Use caution opening links or attachments

Quoted 23 lines · Avihai Horon

As part of its error flow, vfio_vmstate_change() accesses MigrationState->to_dst_file without any checks. This can cause a NULL pointer dereference if the error flow is taken and MigrationState->to_dst_file is not set.

For example, this can happen if VM is started or stopped not during migration and vfio_vmstate_change() error flow is taken, as MigrationState->to_dst_file is not set at that time.

Fix it by checking that MigrationState->to_dst_file is set before using it.

Fixes 02a7e71b1e5b ("vfio: Add VM state change handler to know state of VM")
---
  hw/vfio/migration.c | 4 +++-
  1 file changed, 3 insertions(+), 1 deletion(-)
hw/vfio/migration.c +0 -0
index 835608cd23..21e8f9d4d4 100644

hw/vfio/migration.c static void vfio_vmstate_change(void *opaque, bool running, RunState state) · line 750

Quoted 8 lines
hw/vfio/migration.c +3 -1
@@ -744,7 +744,9 @@ static void vfio_vmstate_change(void *opaque, bool running, RunState state)
           */
          error_report("%s: Failed to set device state 0x%x", vbasedev->name,
                       (migration->device_state & mask) | value);
-        qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
+        if (migrate_get_current()->to_dst_file) {
+            qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
+        }
      }
Quoted 7 lines

I mean that the change is right.

But I am not so sure about using qemu_file_* operations outside of the migration_thread. I *think* that everything else that uses qemu_file_* functions is operating inside the migration_thread, and this one don't look like it. Furthermore, a fast look at qemu source, I can't see anyplace where we setup an error in a vmstate_change.

vfio_vmstate_change() will operate inside migration_thread if migration_thread is the one that called vm start/stop.

In cases where vm start/stop was not called by migration_thread, it will operate outside of migration_thread. But I think in such cases to_dst_file should not be set.

Quoted 6 lines

Ideally we should have returned error, but vm_state_notify() doesn't report errors.

Maybe later we can change vm_state_notify() to support error reporting, or instead of using to_dst_file to indicate an error, update some flag in VFIOMigration.

I think that sounds like a better option.

There are only two callers of vm_state_notify():

do_vm_stop()

and

vm_prepare_start()

Both already support returning one error.

Thanks, Juan.

#12 lore raw

PATCH 4/9 vfio/migration: Skip pre-copy if dirty page tracking is not supported

In reply to Avihai Horon

Currently, if IOMMU of a VFIO container doesn't support dirty page tracking, migration is blocked completely. This is because a DMA-able VFIO device can dirty RAM pages without updating QEMU about it, thus breaking the migration.

However, this doesn't mean that migration can't be done at all. If migration pre-copy phase is skipped, the VFIO device doesn't have a chance to dirty RAM pages that have been migrated already, thus eliminating the problem previously mentioned.

Hence, in such case allow migration but skip pre-copy phase.

---
 hw/vfio/migration.c   | 9 ++++++++-
 migration/migration.c | 5 +++++
 migration/migration.h | 3 +++
 3 files changed, 16 insertions(+), 1 deletion(-)
hw/vfio/migration.c +8 -1
index 21e8f9d4d4..d4b6653026 100644
@@ -863,10 +863,17 @@ int vfio_migration_probe(VFIODevice *vbasedev, Error **errp)
     struct vfio_region_info *info = NULL;
     int ret = -ENOTSUP;
 
-    if (!vbasedev->enable_migration || !container->dirty_pages_supported) {
+    if (!vbasedev->enable_migration) {
         goto add_blocker;
     }
 
+    if (!container->dirty_pages_supported) {
+        warn_report(
+            "%s: IOMMU of the device's VFIO container doesn't support dirty page tracking, migration pre-copy phase will be skipped",
+            vbasedev->name);
+        migrate_get_current()->skip_precopy = true;
+    }
+
     ret = vfio_get_dev_region_info(vbasedev,
                                    VFIO_REGION_TYPE_MIGRATION_DEPRECATED,
                                    VFIO_REGION_SUBTYPE_MIGRATION_DEPRECATED,
migration/migration.c +5 -0
index 5a31b23bd6..668343508d 100644
@@ -3593,6 +3593,11 @@ static MigIterateState migration_iteration_run(MigrationState *s)
     uint64_t pending_size, pend_pre, pend_compat, pend_post;
     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
 
+    if (s->skip_precopy) {
+        migration_completion(s);
+        return MIG_ITERATE_BREAK;
+    }
+
     qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
                               &pend_compat, &pend_post);
     pending_size = pend_pre + pend_compat + pend_post;
migration/migration.h +3 -0
index a863032b71..876713e7e1 100644
@@ -332,6 +332,9 @@ struct MigrationState {
      * This save hostname when out-going migration starts
      */
     char *hostname;
+
+    /* Whether to skip pre-copy phase of migration or not */
+    bool skip_precopy;
 };
 
 void migrate_set_state(int *state, int old_state, int new_state);
Signature · 1 line
2.21.3
#13 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 5 lines · Avihai Horon

Currently, if IOMMU of a VFIO container doesn't support dirty page tracking, migration is blocked completely. This is because a DMA-able VFIO device can dirty RAM pages without updating QEMU about it, thus breaking the migration.

Quoted 8 lines

However, this doesn't mean that migration can't be done at all. If migration pre-copy phase is skipped, the VFIO device doesn't have a chance to dirty RAM pages that have been migrated already, thus eliminating the problem previously mentioned.

Hence, in such case allow migration but skip pre-copy phase.

I don't know (TM).
Several issues:
- Patch is ugly as hell (ok, that depends on taste)
- It changes migration_iteration_run() instead of directly migration_thread.
- There is already another case where we skip the sending of RAM (localhost migration with shared memory)

In migration/ram.c:

static int ram_find_and_save_block(RAMState *rs, bool last_stage)

{
    PageSearchStatus pss;
    int pages = 0;
    bool again, found;

    /* No dirty page as there is zero RAM */
    if (!ram_bytes_total()) {
        return pages;
    }

This is the other place where we _don't_ send any RAM at all.

I don't have a great idea about how to make things clear at a higher level, I have to think about this.

Later, Juan.

Quoted 59 lines
---
 hw/vfio/migration.c   | 9 ++++++++-
 migration/migration.c | 5 +++++
 migration/migration.h | 3 +++
 3 files changed, 16 insertions(+), 1 deletion(-)
hw/vfio/migration.c +8 -1
index 21e8f9d4d4..d4b6653026 100644
@@ -863,10 +863,17 @@ int vfio_migration_probe(VFIODevice *vbasedev, Error **errp)
     struct vfio_region_info *info = NULL;
     int ret = -ENOTSUP;
 
-    if (!vbasedev->enable_migration || !container->dirty_pages_supported) {
+    if (!vbasedev->enable_migration) {
         goto add_blocker;
     }
 
+    if (!container->dirty_pages_supported) {
+        warn_report(
+            "%s: IOMMU of the device's VFIO container doesn't support dirty page tracking, migration pre-copy phase will be skipped",
+            vbasedev->name);
+        migrate_get_current()->skip_precopy = true;
+    }
+
     ret = vfio_get_dev_region_info(vbasedev,
                                    VFIO_REGION_TYPE_MIGRATION_DEPRECATED,
                                    VFIO_REGION_SUBTYPE_MIGRATION_DEPRECATED,
migration/migration.c +5 -0
index 5a31b23bd6..668343508d 100644
@@ -3593,6 +3593,11 @@ static MigIterateState migration_iteration_run(MigrationState *s)
     uint64_t pending_size, pend_pre, pend_compat, pend_post;
     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
 
+    if (s->skip_precopy) {
+        migration_completion(s);
+        return MIG_ITERATE_BREAK;
+    }
+
     qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
                               &pend_compat, &pend_post);
     pending_size = pend_pre + pend_compat + pend_post;
migration/migration.h +3 -0
index a863032b71..876713e7e1 100644
@@ -332,6 +332,9 @@ struct MigrationState {
      * This save hostname when out-going migration starts
      */
     char *hostname;
+
+    /* Whether to skip pre-copy phase of migration or not */
+    bool skip_precopy;
 };
 
 void migrate_set_state(int *state, int old_state, int new_state);
#14 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 36 lines · On Mon, 16 May 2022 13:22:14 +0200 Juan Quintela <[email protected]> wrote:
Quoted 5 lines · Avihai Horon

Currently, if IOMMU of a VFIO container doesn't support dirty page tracking, migration is blocked completely. This is because a DMA-able VFIO device can dirty RAM pages without updating QEMU about it, thus breaking the migration.

Quoted 8 lines

However, this doesn't mean that migration can't be done at all. If migration pre-copy phase is skipped, the VFIO device doesn't have a chance to dirty RAM pages that have been migrated already, thus eliminating the problem previously mentioned.

Hence, in such case allow migration but skip pre-copy phase.

I don't know (TM).
Several issues:
- Patch is ugly as hell (ok, that depends on taste)
- It changes migration_iteration_run() instead of directly migration_thread.
- There is already another case where we skip the sending of RAM (localhost migration with shared memory)

In migration/ram.c:

static int ram_find_and_save_block(RAMState *rs, bool last_stage)

{
    PageSearchStatus pss;
    int pages = 0;
    bool again, found;

    /* No dirty page as there is zero RAM */
    if (!ram_bytes_total()) {
        return pages;
    }
Quoted 4 lines

This is the other place where we _don't_ send any RAM at all.

I don't have a great idea about how to make things clear at a higher level, I have to think about this.

It seems like if we have devices dictating what type of migrations can be performed then there probably needs to be a switch to restrict use of such devices just as we have the -only-migratable switch now to prevent attaching devices that don't support migration. I'd guess that we need the switch to opt-in to allowing such devices to maintain compatibility. There's probably a whole pile of qapi things missing to expose this to management tools as well. Thanks,

Alex

Quoted 60 lines
Quoted 59 lines
---
 hw/vfio/migration.c   | 9 ++++++++-
 migration/migration.c | 5 +++++
 migration/migration.h | 3 +++
 3 files changed, 16 insertions(+), 1 deletion(-)
hw/vfio/migration.c +8 -1
index 21e8f9d4d4..d4b6653026 100644
@@ -863,10 +863,17 @@ int vfio_migration_probe(VFIODevice *vbasedev, Error **errp)
     struct vfio_region_info *info = NULL;
     int ret = -ENOTSUP;
 
-    if (!vbasedev->enable_migration || !container->dirty_pages_supported) {
+    if (!vbasedev->enable_migration) {
         goto add_blocker;
     }
 
+    if (!container->dirty_pages_supported) {
+        warn_report(
+            "%s: IOMMU of the device's VFIO container doesn't support dirty page tracking, migration pre-copy phase will be skipped",
+            vbasedev->name);
+        migrate_get_current()->skip_precopy = true;
+    }
+
     ret = vfio_get_dev_region_info(vbasedev,
                                    VFIO_REGION_TYPE_MIGRATION_DEPRECATED,
                                    VFIO_REGION_SUBTYPE_MIGRATION_DEPRECATED,
migration/migration.c +5 -0
index 5a31b23bd6..668343508d 100644
@@ -3593,6 +3593,11 @@ static MigIterateState migration_iteration_run(MigrationState *s)
     uint64_t pending_size, pend_pre, pend_compat, pend_post;
     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
 
+    if (s->skip_precopy) {
+        migration_completion(s);
+        return MIG_ITERATE_BREAK;
+    }
+
     qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
                               &pend_compat, &pend_post);
     pending_size = pend_pre + pend_compat + pend_post;
migration/migration.h +3 -0
index a863032b71..876713e7e1 100644
@@ -332,6 +332,9 @@ struct MigrationState {
      * This save hostname when out-going migration starts
      */
     char *hostname;
+
+    /* Whether to skip pre-copy phase of migration or not */
+    bool skip_precopy;
 };
 
 void migrate_set_state(int *state, int old_state, int new_state);  
#15 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 44 lines · Alex Williamson
Quoted 36 lines · On Mon, 16 May 2022 13:22:14 +0200 Juan Quintela <[email protected]> wrote:
Quoted 5 lines · Avihai Horon

Currently, if IOMMU of a VFIO container doesn't support dirty page tracking, migration is blocked completely. This is because a DMA-able VFIO device can dirty RAM pages without updating QEMU about it, thus breaking the migration.

Quoted 8 lines

However, this doesn't mean that migration can't be done at all. If migration pre-copy phase is skipped, the VFIO device doesn't have a chance to dirty RAM pages that have been migrated already, thus eliminating the problem previously mentioned.

Hence, in such case allow migration but skip pre-copy phase.

I don't know (TM).
Several issues:
- Patch is ugly as hell (ok, that depends on taste)
- It changes migration_iteration_run() instead of directly migration_thread.
- There is already another case where we skip the sending of RAM (localhost migration with shared memory)

In migration/ram.c:

static int ram_find_and_save_block(RAMState *rs, bool last_stage)

{
    PageSearchStatus pss;
    int pages = 0;
    bool again, found;

    /* No dirty page as there is zero RAM */
    if (!ram_bytes_total()) {
        return pages;
    }
Quoted 4 lines

This is the other place where we _don't_ send any RAM at all.

I don't have a great idea about how to make things clear at a higher level, I have to think about this.

Quoted 7 lines

It seems like if we have devices dictating what type of migrations can be performed then there probably needs to be a switch to restrict use of such devices just as we have the -only-migratable switch now to prevent attaching devices that don't support migration. I'd guess that we need the switch to opt-in to allowing such devices to maintain compatibility. There's probably a whole pile of qapi things missing to expose this to management tools as well. Thanks,

This is really intended to be a NOP from where things are now, as if you use mlx5 live migration without a patch like this then it causes a botched pre-copy since everything just ends up permanently dirty.

If it makes more sense we could abort the pre-copy too - in the end there will be dirty tracking so I don't know if I'd invest in a big adventure to fully define non-dirty tracking migration.

Jason

#16 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 53 lines · On Mon, 16 May 2022 20:08:32 -0300 Jason Gunthorpe <[email protected]> wrote:
Quoted 44 lines · Alex Williamson
Quoted 36 lines · On Mon, 16 May 2022 13:22:14 +0200 Juan Quintela <[email protected]> wrote:
Quoted 5 lines · Avihai Horon

Currently, if IOMMU of a VFIO container doesn't support dirty page tracking, migration is blocked completely. This is because a DMA-able VFIO device can dirty RAM pages without updating QEMU about it, thus breaking the migration.

Quoted 8 lines

However, this doesn't mean that migration can't be done at all. If migration pre-copy phase is skipped, the VFIO device doesn't have a chance to dirty RAM pages that have been migrated already, thus eliminating the problem previously mentioned.

Hence, in such case allow migration but skip pre-copy phase.

I don't know (TM).
Several issues:
- Patch is ugly as hell (ok, that depends on taste)
- It changes migration_iteration_run() instead of directly migration_thread.
- There is already another case where we skip the sending of RAM (localhost migration with shared memory)

In migration/ram.c:

static int ram_find_and_save_block(RAMState *rs, bool last_stage)

{
    PageSearchStatus pss;
    int pages = 0;
    bool again, found;

    /* No dirty page as there is zero RAM */
    if (!ram_bytes_total()) {
        return pages;
    }
Quoted 4 lines

This is the other place where we _don't_ send any RAM at all.

I don't have a great idea about how to make things clear at a higher level, I have to think about this.

Quoted 7 lines

It seems like if we have devices dictating what type of migrations can be performed then there probably needs to be a switch to restrict use of such devices just as we have the -only-migratable switch now to prevent attaching devices that don't support migration. I'd guess that we need the switch to opt-in to allowing such devices to maintain compatibility. There's probably a whole pile of qapi things missing to expose this to management tools as well. Thanks,

Quoted 7 lines

This is really intended to be a NOP from where things are now, as if you use mlx5 live migration without a patch like this then it causes a botched pre-copy since everything just ends up permanently dirty.

If it makes more sense we could abort the pre-copy too - in the end there will be dirty tracking so I don't know if I'd invest in a big adventure to fully define non-dirty tracking migration.

How is pre-copy currently "botched" without a patch like this? If it's simply that the pre-copy doesn't converge and the downtime constraints don't allow the VM to enter stop-and-copy, that's the expected behavior AIUI, and supports backwards compatibility with existing SLAs.

I'm assuming that by setting this new skip_precopy flag that we're forcing the VM to move to stop-and-copy, regardless of any other SLA constraints placed on the migration. It seems like a better solution would be to expose to management tools that the VM contains a device that does not support the pre-copy phase so that downtime expectations can be adjusted. Thanks,

Alex

#17 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 4 lines · Alex Williamson
Quoted 4 lines

This is really intended to be a NOP from where things are now, as if you use mlx5 live migration without a patch like this then it causes a botched pre-copy since everything just ends up permanently dirty.

Quoted 8 lines
Quoted 3 lines

If it makes more sense we could abort the pre-copy too - in the end there will be dirty tracking so I don't know if I'd invest in a big adventure to fully define non-dirty tracking migration.

How is pre-copy currently "botched" without a patch like this? If it's simply that the pre-copy doesn't converge and the downtime constraints don't allow the VM to enter stop-and-copy, that's the expected behavior AIUI, and supports backwards compatibility with existing SLAs.

It means it always fails - that certainly isn't working live migration. There is no point in trying to converge something that we already know will never converge.

Quoted 3 lines

I'm assuming that by setting this new skip_precopy flag that we're forcing the VM to move to stop-and-copy, regardless of any other SLA constraints placed on the migration.

That does seem like a defect in this patch, any SLA constraints should still all be checked under the assumption all ram is dirty.

Quoted 3 lines

It seems like a better solution would be to expose to management tools that the VM contains a device that does not support the pre-copy phase so that downtime expectations can be adjusted.

I don't expect this to be a real use case though..

Remember, you asked for this patch when you wanted qemu to have good behavior when kernel support for legacy dirty tracking is removed before we merge v2 support.

Thanks,
Jason

#18 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 10 lines · On Tue, 17 May 2022 13:08:44 -0300 Jason Gunthorpe <[email protected]> wrote:
Quoted 8 lines · Alex Williamson
Quoted 7 lines

This is really intended to be a NOP from where things are now, as if you use mlx5 live migration without a patch like this then it causes a botched pre-copy since everything just ends up permanently dirty.

If it makes more sense we could abort the pre-copy too - in the end there will be dirty tracking so I don't know if I'd invest in a big adventure to fully define non-dirty tracking migration.

Quoted 8 lines
Quoted 4 lines

How is pre-copy currently "botched" without a patch like this? If it's simply that the pre-copy doesn't converge and the downtime constraints don't allow the VM to enter stop-and-copy, that's the expected behavior AIUI, and supports backwards compatibility with existing SLAs.

It means it always fails - that certainly isn't working live migration. There is no point in trying to converge something that we already know will never converge.

If we eliminate the pre-copy phase then it's not so much live migration anyway. Trying to converge is indeed useless work, but afaik it's that useless work that generates the data that management tools can use to determine that SLAs cannot be achieved in a compatible way.

Quoted 6 lines
Quoted 3 lines

I'm assuming that by setting this new skip_precopy flag that we're forcing the VM to move to stop-and-copy, regardless of any other SLA constraints placed on the migration.

That does seem like a defect in this patch, any SLA constraints should still all be checked under the assumption all ram is dirty.

The migration iteration function certainly tries to compare remaining bytes to a threshold based on bandwidth and downtime. The exit path added here is the same as it would take if we had achieved our threshold limit. It's not clear to me that we're checking the downtime limit elsewhere or have the data to do it if we don't transfer anything estimate bandwidth.

Quoted 9 lines
Quoted 3 lines

It seems like a better solution would be to expose to management tools that the VM contains a device that does not support the pre-copy phase so that downtime expectations can be adjusted.

I don't expect this to be a real use case though..

Remember, you asked for this patch when you wanted qemu to have good behavior when kernel support for legacy dirty tracking is removed before we merge v2 support.

Is wanting good behavior a controversial point? Did we define this as the desired good behavior? Ref? Thanks,

Alex

#19 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 4 lines · Alex Williamson
Quoted 4 lines
Quoted 3 lines

It seems like a better solution would be to expose to management tools that the VM contains a device that does not support the pre-copy phase so that downtime expectations can be adjusted.

Quoted 8 lines
Quoted 5 lines

I don't expect this to be a real use case though..

Remember, you asked for this patch when you wanted qemu to have good behavior when kernel support for legacy dirty tracking is removed before we merge v2 support.

Is wanting good behavior a controversial point? Did we define this as the desired good behavior? Ref?

As I said, this was intended as a NOP, which is what I thought we agreed to. Missing the SLA checking that existed before seems like something to fix in this patch. This is the discussion thread:

https://lore.kernel.org/kvm/[email protected]/

"I guess I was assuming that enabling v2 migration in QEMU was dependent
on the existing type1 dirty tracking because it's the only means we have to tell QEMU that all memory is perpetually dirty when we have a DMA device. Is that not correct?"

The only point was to prepare qemu for kernel's that don't support the legacy dirty tracking API but do have a v2 migration interface. IIRC something undesired happens if you do that right now.

We could also just dirty all memory in qemu and keep it exactly the same so every SLA detail works. Or completely block pre-copy based flows.

It it not intended to be a useful configuration, this is just covering off backwards compat issues - so I'm not keen to do a bunch of management work to support it.

Thanks,
Jason

#20 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 12 lines · On Tue, 17 May 2022 14:39:37 -0300 Jason Gunthorpe <[email protected]> wrote:
Quoted 10 lines · Alex Williamson
Quoted 9 lines
Quoted 3 lines

It seems like a better solution would be to expose to management tools that the VM contains a device that does not support the pre-copy phase so that downtime expectations can be adjusted.

I don't expect this to be a real use case though..

Remember, you asked for this patch when you wanted qemu to have good behavior when kernel support for legacy dirty tracking is removed before we merge v2 support.

Quoted 6 lines
Quoted 2 lines

Is wanting good behavior a controversial point? Did we define this as the desired good behavior? Ref?

As I said, this was intended as a NOP, which is what I thought we agreed to. Missing the SLA checking that existed before seems like something to fix in this patch.

But even if we have the SLA check, how does a management tool know that pre-copy will be skipped and that the downtime needs to account for that? The current solution is obviously non-optimal, it was mainly meant for backwards compatibility, but this seems like a fail faster solution, with less useless work, but also providing less indication how to configure the migration to succeed.

Quoted 8 lines

This is the discussion thread:

https://lore.kernel.org/kvm/[email protected]/

"I guess I was assuming that enabling v2 migration in QEMU was dependent
on the existing type1 dirty tracking because it's the only means we have to tell QEMU that all memory is perpetually dirty when we have a DMA device. Is that not correct?"

Doesn't sound like me asking for this patch so much as trying to figure out how to support migration without DMA dirty tracking, and after the above comment was a concern whether we lock ourselves into a dirty tracking requirement in the iommufd type1 compatibility interface if we rely on this type1 feature. You had spit-balled that QEMU could skip pre-copy, but this all needs to be vetted with migration folks and management tools.

Quoted 3 lines

The only point was to prepare qemu for kernel's that don't support the legacy dirty tracking API but do have a v2 migration interface. IIRC something undesired happens if you do that right now.

Per this patch, the container requires dirty tracking or we add a blocker and can't migrate the device.

Quoted 7 lines

We could also just dirty all memory in qemu and keep it exactly the same so every SLA detail works. Or completely block pre-copy based flows.

It it not intended to be a useful configuration, this is just covering off backwards compat issues - so I'm not keen to do a bunch of management work to support it.

Are we then deemphasizing the vfio compatibility support in iommufd? If we really don't want to put effort towards backwards compatibility, should migration support only be enabled with native iommufd support? Thanks,

Alex

#21 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 4 lines · Alex Williamson

The current solution is obviously non-optimal, it was mainly meant for backwards compatibility, but this seems like a fail faster solution, with less useless work, but also providing less indication how to configure the migration to succeed.

I don't think this is a production configuration. We should not be expecting that the user is going to carefully fine tune some SLA parameter. It may be the "SLA check" we are missing is simply if a SLA exists or not.

Quoted 5 lines
Quoted 3 lines

It it not intended to be a useful configuration, this is just covering off backwards compat issues - so I'm not keen to do a bunch of management work to support it.

Are we then deemphasizing the vfio compatibility support in iommufd?

I'm viewing iommufd compatability with VFIO type 1 as only extending to implemented features.. We are deleting NESTED for instance. As there is no in-kernel implementation of the type 1 tracker I would expect to eventually delete it as well once we have consensus this is what we plan to do.

We discussed this in Joao's series and that was the consensus.

Quoted 3 lines

If we really don't want to put effort towards backwards compatibility, should migration support only be enabled with native iommufd support?

I'm expecting that the dirty tracking will require native iommufd only for the system iommu tracker, but the mlx5 on-device tracker will be fine with either iommu back end.

It is still useful currently for testing the VFIO device part as it will be some time until the other parts are ready, so I'd rather not block it completely in qemu.

The goal is for qemu to do something sensible so when we delete kernel support for type 1 dirty tracking so there is no back compat concern for existing non-experimental qemu.

Jason

#22 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

In reply to Jason Gunthorpe
Quoted 10 lines · Jason Gunthorpe
Quoted 8 lines · Alex Williamson
Quoted 7 lines

This is really intended to be a NOP from where things are now, as if you use mlx5 live migration without a patch like this then it causes a botched pre-copy since everything just ends up permanently dirty.

If it makes more sense we could abort the pre-copy too - in the end there will be dirty tracking so I don't know if I'd invest in a big adventure to fully define non-dirty tracking migration.

Quoted 8 lines
Quoted 4 lines

How is pre-copy currently "botched" without a patch like this? If it's simply that the pre-copy doesn't converge and the downtime constraints don't allow the VM to enter stop-and-copy, that's the expected behavior AIUI, and supports backwards compatibility with existing SLAs.

It means it always fails - that certainly isn't working live migration. There is no point in trying to converge something that we already know will never converge.

Fully agree with you here.

But not how this is being done. I think we need a way to convince the migration code that it shouldn't even try to migrate RAM. That would fix the current use case, and your use case.

Quoted 6 lines
Quoted 3 lines

I'm assuming that by setting this new skip_precopy flag that we're forcing the VM to move to stop-and-copy, regardless of any other SLA constraints placed on the migration.

That does seem like a defect in this patch, any SLA constraints should still all be checked under the assumption all ram is dirty.

And how are we going to:
- detect the network link speed
- to be sure that we are inside downtime limit

I think that it is not possible, so basically we are skiping the precopy stage and praying that the other bits are going to be ok.

Quoted 9 lines
Quoted 3 lines

It seems like a better solution would be to expose to management tools that the VM contains a device that does not support the pre-copy phase so that downtime expectations can be adjusted.

I don't expect this to be a real use case though..

Remember, you asked for this patch when you wanted qemu to have good behavior when kernel support for legacy dirty tracking is removed before we merge v2 support.

I am an ignorant on the subject. Can I ask how the dirty memory is tracked on this v2?

Thanks, Juan.

#23 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 9 lines · Juan Quintela
Quoted 2 lines

That does seem like a defect in this patch, any SLA constraints should still all be checked under the assumption all ram is dirty.

And how are we going to:
- detect the network link speed
- to be sure that we are inside downtime limit

I think that it is not possible, so basically we are skiping the precopy stage and praying that the other bits are going to be ok.

Like I keep saying, this is not a real use case, we expect dirty tracking to be available in any real configuration. This is just trying to make qemu work in some reasonable way if dirty tracking is not available but a VFIO migration device is plugged in.

Just pick something simple that makes sense. Like if any SLA is set then just refuse to even start. If no SLA then go directly to STOP_COPY.

Quoted 4 lines
Quoted 4 lines
Quoted 3 lines

It seems like a better solution would be to expose to management tools that the VM contains a device that does not support the pre-copy phase so that downtime expectations can be adjusted.

Quoted 8 lines
Quoted 5 lines

I don't expect this to be a real use case though..

Remember, you asked for this patch when you wanted qemu to have good behavior when kernel support for legacy dirty tracking is removed before we merge v2 support.

I am an ignorant on the subject. Can I ask how the dirty memory is tracked on this v2?

These two RFCs are the current proposal to enable it for the system iommu:

https://lore.kernel.org/kvm/[email protected]

And for device internal trackers:

https://lore.kernel.org/kvm/[email protected]/

Regards,
Jason

#24 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 10 lines · Jason Gunthorpe
Quoted 8 lines · Juan Quintela
Quoted 2 lines

That does seem like a defect in this patch, any SLA constraints should still all be checked under the assumption all ram is dirty.

And how are we going to:
- detect the network link speed
- to be sure that we are inside downtime limit

I think that it is not possible, so basically we are skiping the precopy stage and praying that the other bits are going to be ok.

Quoted 8 lines

Like I keep saying, this is not a real use case, we expect dirty tracking to be available in any real configuration. This is just trying to make qemu work in some reasonable way if dirty tracking is not available but a VFIO migration device is plugged in.

Just pick something simple that makes sense. Like if any SLA is set then just refuse to even start. If no SLA then go directly to STOP_COPY.

I tried to follow Jason's suggestion to check if there is any SLA and block migration, or no SLA at all and allow migration.

It doesn't seem like there is a way to say "no SLA at all".

Migration param downtime_limit takes values between 0 and 2000 seconds.

What does downtime_limit=0 mean?

If it's 0 then MigrationState->threshold_size = 0, so ram_save_pending() will never call migration_bitmap_sync_precopy(). Only upon entering stop-copy phase will migration_bitmap_sync_precopy() be called, which will collect all pages that were dirtied during pre-copy, which could be a lot and impact downtime.

In libvirt it seems that downtime_limit = 0 is not valid and can't be set.

Am I missing something here? Is there a way to allow unlimited downtime?

Thanks.

#25 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

In reply to Avihai Horon
Quoted 7 lines · Avihai Horon
hw/vfio/migration.c +0 -0
index 21e8f9d4d4..d4b6653026 100644
@@ -863,10 +863,17 @@ int vfio_migration_probe(VFIODevice *vbasedev, Error **errp)
     struct vfio_region_info *info = NULL;
     int ret = -ENOTSUP;

hw/vfio/migration.c int vfio_migration_probe(VFIODevice *vbasedev, Error **errp) · line 873

Quoted 10 lines
hw/vfio/migration.c +5 -1
 
-    if (!vbasedev->enable_migration || !container->dirty_pages_supported) {
+    if (!vbasedev->enable_migration) {
         goto add_blocker;
     }
 
+    if (!container->dirty_pages_supported) {
+        warn_report(
+            "%s: IOMMU of the device's VFIO container doesn't support dirty page tracking, migration pre-copy phase will be skipped",
+            vbasedev->name);

Maybe warn_report_once(...) given that the following N devices would observe the same thing in theory.

hw/vfio/migration.c int vfio_migration_probe(VFIODevice *vbasedev, Error **errp) · line 876

Quoted 3 lines
hw/vfio/migration.c +3 -0
+        migrate_get_current()->skip_precopy = true;
+    }
+

Perhaps it might be easier to reuse the existing knob to disable pre-copy per device that Kirti added some time ago, rather than changing migration core just yet (e.g. you might wanna bail of the migration preemptively because the CPU is dirtying too many pages for example?):

if (!container->dirty_pages_supported) {
    warn_report_once(...)
    pre_copy_dirty_page_tracking = ON_OFF_AUTO_OFF;
}

You might need to tackle the fact you will get when dirty_pages start/stop ioctls returns you error messages. The errors is just because log_start() and log_stop() simply fail because the ioctl doesn't exist, but everything else is fine -- at least that's what I observed at least. Should be noted that it's a problem with the existing -device vfio-pci host=XX:YY.ZZ,x-pre-copy-dirty-page-tracking=true regardless of this patch:

void vfio_listener_log_global_start()

{
	if (vfio_devices_all_dirty_tracking(container)) {
		vfio_set_dirty_page_tracking(container, true);
        }
}

... And same for vfio_listener_log_global_stop() -- maybe a worthwhile predecessor patch.

#26 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 17 lines · Joao Martins

External email: Use caution opening links or attachments

Quoted 13 lines · Avihai Horon
hw/vfio/migration.c +1 -1
index 21e8f9d4d4..d4b6653026 100644
@@ -863,10 +863,17 @@ int vfio_migration_probe(VFIODevice *vbasedev, Error **errp)
      struct vfio_region_info *info = NULL;
      int ret = -ENOTSUP;
 
-    if (!vbasedev->enable_migration || !container->dirty_pages_supported) {
+    if (!vbasedev->enable_migration) {
          goto add_blocker;
      }
 
Quoted 6 lines

hw/vfio/migration.c int vfio_migration_probe(VFIODevice *vbasedev, Error **errp) · line 873

Quoted 4 lines
hw/vfio/migration.c +4 -0
+    if (!container->dirty_pages_supported) {
+        warn_report(
+            "%s: IOMMU of the device's VFIO container doesn't support dirty page tracking, migration pre-copy phase will be skipped",
+            vbasedev->name);

Maybe warn_report_once(...) given that the following N devices would observe the same thing in theory.

Yes, you are right. Will change.

Quoted 8 lines

hw/vfio/migration.c int vfio_migration_probe(VFIODevice *vbasedev, Error **errp) · line 876

Quoted 3 lines
hw/vfio/migration.c +3 -0
+        migrate_get_current()->skip_precopy = true;
+    }
+

Perhaps it might be easier to reuse the existing knob to disable pre-copy per device that Kirti added some time ago, rather than changing migration core just yet (e.g. you might wanna bail of the migration preemptively because the CPU is dirtying too many pages for example?):

Quoted 4 lines
if (!container->dirty_pages_supported) {
     warn_report_once(...)
     pre_copy_dirty_page_tracking = ON_OFF_AUTO_OFF;
}

But this doesn't prevent the VFIO device from dirtying RAM pages during pre-copy phase.
The VFIO device can dirty RAM pages during pre-copy and it won't have a way to report the dirtied pages to QEMU and migration will be faulty.

Thanks.

Quoted 15 lines

You might need to tackle the fact you will get when dirty_pages start/stop ioctls returns you error messages. The errors is just because log_start() and log_stop() simply fail because the ioctl doesn't exist, but everything else is fine -- at least that's what I observed at least. Should be noted that it's a problem with the existing -device vfio-pci host=XX:YY.ZZ,x-pre-copy-dirty-page-tracking=true regardless of this patch:

void vfio_listener_log_global_start()

{
         if (vfio_devices_all_dirty_tracking(container)) {
                 vfio_set_dirty_page_tracking(container, true);
         }
}

... And same for vfio_listener_log_global_stop() -- maybe a worthwhile predecessor patch.

#27 lore raw

Re: [PATCH 4/9] vfio/migration: Skip pre-copy if dirty page tracking is not supported

Quoted 14 lines · Avihai Horon
Quoted 8 lines · Joao Martins

hw/vfio/migration.c int vfio_migration_probe(VFIODevice *vbasedev, Error **errp) · line 876

Quoted 3 lines
hw/vfio/migration.c +3 -0
+        migrate_get_current()->skip_precopy = true;
+    }
+

Perhaps it might be easier to reuse the existing knob to disable pre-copy per device that Kirti added some time ago, rather than changing migration core just yet (e.g. you might wanna bail of the migration preemptively because the CPU is dirtying too many pages for example?):

Quoted 4 lines
if (!container->dirty_pages_supported) {
     warn_report_once(...)
     pre_copy_dirty_page_tracking = ON_OFF_AUTO_OFF;
}
Quoted 5 lines

But this doesn't prevent the VFIO device from dirtying RAM pages during pre-copy phase.
The VFIO device can dirty RAM pages during pre-copy and it won't have a way to report the dirtied pages to QEMU and migration will be faulty.

You're quite right, sorry for the noise. I was a little too obsessed in reusing the existing field that forgot that letting the iterate stage go the PCI device could also be driven into dirtying RAM too.

#28 lore raw

PATCH 5/9 migration/qemu-file: Add qemu_file_get_to_fd()

In reply to Avihai Horon

Add new function qemu_file_get_to_fd() that allows reading data from QEMUFile and writing it straight into a given fd.

This will be used later in VFIO migration code.

---
 migration/qemu-file.c | 34 ++++++++++++++++++++++++++++++++++
 migration/qemu-file.h |  1 +
 2 files changed, 35 insertions(+)
migration/qemu-file.c +34 -0
index 1479cddad9..cad3d32eb3 100644
@@ -867,3 +867,37 @@ QIOChannel *qemu_file_get_ioc(QEMUFile *file)
 {
     return file->has_ioc ? QIO_CHANNEL(file->opaque) : NULL;
 }
+
+/*
+ * Read size bytes from QEMUFile f and write them to fd.
+ */
+int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size)
+{
+    while (size) {
+        size_t pending = f->buf_size - f->buf_index;
+        ssize_t rc;
+
+        if (!pending) {
+            rc = qemu_fill_buffer(f);
+            if (rc < 0) {
+                return rc;
+            }
+            if (rc == 0) {
+                return -1;
+            }
+            continue;
+        }
+
+        rc = write(fd, f->buf + f->buf_index, MIN(pending, size));
+        if (rc < 0) {
+            return rc;
+        }
+        if (rc == 0) {
+            return -1;
+        }
+        f->buf_index += rc;
+        size -= rc;
+    }
+
+    return 0;
+}
migration/qemu-file.h +1 -0
index 3f36d4dc8c..dd26037450 100644
@@ -162,6 +162,7 @@ int qemu_file_shutdown(QEMUFile *f);
 QEMUFile *qemu_file_get_return_path(QEMUFile *f);
 void qemu_fflush(QEMUFile *f);
 void qemu_file_set_blocking(QEMUFile *f, bool block);
+int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size);
 
 void ram_control_before_iterate(QEMUFile *f, uint64_t flags);
 void ram_control_after_iterate(QEMUFile *f, uint64_t flags);
Signature · 1 line
2.21.3
#29 lore raw

Re: [PATCH 5/9] migration/qemu-file: Add qemu_file_get_to_fd()

Quoted 43 lines · Avihai Horon

Add new function qemu_file_get_to_fd() that allows reading data from QEMUFile and writing it straight into a given fd.

This will be used later in VFIO migration code.

---
 migration/qemu-file.c | 34 ++++++++++++++++++++++++++++++++++
 migration/qemu-file.h |  1 +
 2 files changed, 35 insertions(+)
migration/qemu-file.c +24 -0
index 1479cddad9..cad3d32eb3 100644
@@ -867,3 +867,37 @@ QIOChannel *qemu_file_get_ioc(QEMUFile *file)
 {
     return file->has_ioc ? QIO_CHANNEL(file->opaque) : NULL;
 }
+
+/*
+ * Read size bytes from QEMUFile f and write them to fd.
+ */
+int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size)
+{
+    while (size) {
+        size_t pending = f->buf_size - f->buf_index;
+        ssize_t rc;
+
+        if (!pending) {
+            rc = qemu_fill_buffer(f);
+            if (rc < 0) {
+                return rc;
+            }
+            if (rc == 0) {
+                return -1;
+            }
+            continue;
+        }
+
+        rc = write(fd, f->buf + f->buf_index, MIN(pending, size));
+        if (rc < 0) {
+            return rc;

migration/qemu-file.c QIOChannel *qemu_file_get_ioc(QEMUFile *file) · line 903

Quoted 10 lines
migration/qemu-file.c +10 -0
+        }
+        if (rc == 0) {
+            return -1;
+        }
+        f->buf_index += rc;
+        size -= rc;
+    }
+
+    return 0;
+}

Is there a really performance difference to just use:

uint8_t buffer[size];

qemu_get_buffer(f, buffer, size);
write(fd, buffer, size);

Or telling it otherwise, what sizes are we talking here?

Thanks, Juan.

Quoted 12 lines
migration/qemu-file.h +1 -0
index 3f36d4dc8c..dd26037450 100644
@@ -162,6 +162,7 @@ int qemu_file_shutdown(QEMUFile *f);
 QEMUFile *qemu_file_get_return_path(QEMUFile *f);
 void qemu_fflush(QEMUFile *f);
 void qemu_file_set_blocking(QEMUFile *f, bool block);
+int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size);
 
 void ram_control_before_iterate(QEMUFile *f, uint64_t flags);
 void ram_control_after_iterate(QEMUFile *f, uint64_t flags);
#30 lore raw

Re: [PATCH 5/9] migration/qemu-file: Add qemu_file_get_to_fd()

Quoted 59 lines · Juan Quintela

External email: Use caution opening links or attachments

Quoted 43 lines · Avihai Horon

Add new function qemu_file_get_to_fd() that allows reading data from QEMUFile and writing it straight into a given fd.

This will be used later in VFIO migration code.

---
  migration/qemu-file.c | 34 ++++++++++++++++++++++++++++++++++
  migration/qemu-file.h |  1 +
  2 files changed, 35 insertions(+)
migration/qemu-file.c +24 -0
index 1479cddad9..cad3d32eb3 100644
@@ -867,3 +867,37 @@ QIOChannel *qemu_file_get_ioc(QEMUFile *file)
  {
      return file->has_ioc ? QIO_CHANNEL(file->opaque) : NULL;
  }
+
+/*
+ * Read size bytes from QEMUFile f and write them to fd.
+ */
+int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size)
+{
+    while (size) {
+        size_t pending = f->buf_size - f->buf_index;
+        ssize_t rc;
+
+        if (!pending) {
+            rc = qemu_fill_buffer(f);
+            if (rc < 0) {
+                return rc;
+            }
+            if (rc == 0) {
+                return -1;
+            }
+            continue;
+        }
+
+        rc = write(fd, f->buf + f->buf_index, MIN(pending, size));
+        if (rc < 0) {
+            return rc;

migration/qemu-file.c QIOChannel *qemu_file_get_ioc(QEMUFile *file) · line 903

Quoted 10 lines
migration/qemu-file.c +10 -0
+        }
+        if (rc == 0) {
+            return -1;
+        }
+        f->buf_index += rc;
+        size -= rc;
+    }
+
+    return 0;
+}

Is there a really performance difference to just use:

Quoted 6 lines

uint8_t buffer[size];

qemu_get_buffer(f, buffer, size);
write(fd, buffer, size);

Or telling it otherwise, what sizes are we talking here?

It depends on the device, but It can range from a few MBs to several GBs AFAIK.

Thanks.

Quoted 16 lines

Thanks, Juan.

Quoted 12 lines
migration/qemu-file.h +1 -0
index 3f36d4dc8c..dd26037450 100644
@@ -162,6 +162,7 @@ int qemu_file_shutdown(QEMUFile *f);
  QEMUFile *qemu_file_get_return_path(QEMUFile *f);
  void qemu_fflush(QEMUFile *f);
  void qemu_file_set_blocking(QEMUFile *f, bool block);
+int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size);
 
  void ram_control_before_iterate(QEMUFile *f, uint64_t flags);
  void ram_control_after_iterate(QEMUFile *f, uint64_t flags);
#31 lore raw

Re: [PATCH 5/9] migration/qemu-file: Add qemu_file_get_to_fd()

Quoted 62 lines · Avihai Horon
Quoted 61 lines · Juan Quintela

External email: Use caution opening links or attachments

Quoted 43 lines · Avihai Horon

Add new function qemu_file_get_to_fd() that allows reading data from QEMUFile and writing it straight into a given fd.

This will be used later in VFIO migration code.

---
  migration/qemu-file.c | 34 ++++++++++++++++++++++++++++++++++
  migration/qemu-file.h |  1 +
  2 files changed, 35 insertions(+)
migration/qemu-file.c +24 -0
index 1479cddad9..cad3d32eb3 100644
@@ -867,3 +867,37 @@ QIOChannel *qemu_file_get_ioc(QEMUFile *file)
  {
      return file->has_ioc ? QIO_CHANNEL(file->opaque) : NULL;
  }
+
+/*
+ * Read size bytes from QEMUFile f and write them to fd.
+ */
+int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size)
+{
+    while (size) {
+        size_t pending = f->buf_size - f->buf_index;
+        ssize_t rc;
+
+        if (!pending) {
+            rc = qemu_fill_buffer(f);
+            if (rc < 0) {
+                return rc;
+            }
+            if (rc == 0) {
+                return -1;
+            }
+            continue;
+        }
+
+        rc = write(fd, f->buf + f->buf_index, MIN(pending, size));
+        if (rc < 0) {
+            return rc;

migration/qemu-file.c QIOChannel *qemu_file_get_ioc(QEMUFile *file) · line 903

Quoted 10 lines
migration/qemu-file.c +10 -0
+        }
+        if (rc == 0) {
+            return -1;
+        }
+        f->buf_index += rc;
+        size -= rc;
+    }
+
+    return 0;
+}

Is there a really performance difference to just use:

uint8_t buffer[size];

Quoted 7 lines
Quoted 4 lines

qemu_get_buffer(f, buffer, size);
write(fd, buffer, size);

Or telling it otherwise, what sizes are we talking here?

It depends on the device, but It can range from a few MBs to several GBs AFAIK.

a few MB is ok.

Several GB on the main migration channel without a single header/whatever?

This sounds like a recipe for disaster IMHO.
Remember that on source side, we have a migration thread. This patch will just block that migration thread.

If we are using 10Gigabit networking, 1GB/second for friends and making math easy, each GB will take 1 second downtime.

During that downtime, migration control is basically handycapped. And you are sendinfg this data with qemu_put_buffer_async(). This function just adds its buffer to an iovec, only user uses 4KB (or whatever your page size is) to the iovec. You are talking about adding gigabytes here. I don't know how well this is going to work, but my guess is that migrate_cancel is not going to be happy.

On destination side, this is even worse, because we receive this multigigabyte chunk in a coroutine, and I am not sure that this will not completely block all qemu while this is happening (again, multisecond time).

I have to think more about this problem, but I can see how this is going to be able to go through the migration main channel.

Later, Juan.

#32 lore raw

Re: [PATCH 5/9] migration/qemu-file: Add qemu_file_get_to_fd()

Quoted 9 lines · Juan Quintela
Quoted 9 lines
Quoted 8 lines

Is there a really performance difference to just use:

uint8_t buffer[size];

qemu_get_buffer(f, buffer, size);
write(fd, buffer, size);

Or telling it otherwise, what sizes are we talking here?

Quoted 7 lines
Quoted 2 lines

It depends on the device, but It can range from a few MBs to several GBs AFAIK.

a few MB is ok.

Several GB on the main migration channel without a single header/whatever?

IIRC it iterates in multi-megabyte chunks each which gets a header.

The chunking size is set by the size of the buffer mmap

The overall point is that memcpying GB's is going to be taxing so we want to eliminate copies on this path, especially copies that result in more system calls.

We are expecting to look into further optimization down the road here because even this is still too slow.

Jason

#33 lore raw

Re: [PATCH 5/9] migration/qemu-file: Add qemu_file_get_to_fd()

Quoted 21 lines · Jason Gunthorpe
Quoted 9 lines · Juan Quintela
Quoted 9 lines
Quoted 8 lines

Is there a really performance difference to just use:

uint8_t buffer[size];

qemu_get_buffer(f, buffer, size);
write(fd, buffer, size);

Or telling it otherwise, what sizes are we talking here?

Quoted 7 lines
Quoted 2 lines

It depends on the device, but It can range from a few MBs to several GBs AFAIK.

a few MB is ok.

Several GB on the main migration channel without a single header/whatever?

IIRC it iterates in multi-megabyte chunks each which gets a header.

Quoted 8 lines

The chunking size is set by the size of the buffer mmap

The overall point is that memcpying GB's is going to be taxing so we want to eliminate copies on this path, especially copies that result in more system calls.

We are expecting to look into further optimization down the road here because even this is still too slow.

Considering the possibility of future optimization, IMHO adding this kind of API at the QEMUFile level is too high. We'd be better pushing the impl down into the QIOChannel API level.

int64_t qio_channel_copy_range(QIOCHannel *srcioc,

                                  QIOChannel *tgtioc,
				  size_t len);

The QIOChannel impl can do pretty much what you showed in the general case, but in special cases it could have the option to offload to the kernel copy_range() syscall to avoid the context sitches.

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#34 lore raw

Re: [PATCH 5/9] migration/qemu-file: Add qemu_file_get_to_fd()

Quoted 35 lines · Daniel P. Berrangé
Quoted 21 lines · Jason Gunthorpe
Quoted 9 lines · Juan Quintela
Quoted 9 lines
Quoted 8 lines

Is there a really performance difference to just use:

uint8_t buffer[size];

qemu_get_buffer(f, buffer, size);
write(fd, buffer, size);

Or telling it otherwise, what sizes are we talking here?

Quoted 7 lines
Quoted 2 lines

It depends on the device, but It can range from a few MBs to several GBs AFAIK.

a few MB is ok.

Several GB on the main migration channel without a single header/whatever?

IIRC it iterates in multi-megabyte chunks each which gets a header.

Quoted 8 lines

The chunking size is set by the size of the buffer mmap

The overall point is that memcpying GB's is going to be taxing so we want to eliminate copies on this path, especially copies that result in more system calls.

We are expecting to look into further optimization down the road here because even this is still too slow.

Considering the possibility of future optimization, IMHO adding this kind of API at the QEMUFile level is too high. We'd be better pushing the impl down into the QIOChannel API level.

Quoted 7 lines

int64_t qio_channel_copy_range(QIOCHannel *srcioc,

                                  QIOChannel *tgtioc,
				  size_t len);

The QIOChannel impl can do pretty much what you showed in the general case, but in special cases it could have the option to offload to the kernel copy_range() syscall to avoid the context sitches.

This is probably something to do down the road when we figure out exactly what is best.

Currently we don't have kernel support for optimized copy_file_range() (ie fops splice_read) inside the VFIO drivers so copy_file_range() will just fail.

I didn't look closely again but IIRC the challenge is that the QIOChannel doesn't have a ready large temporary buffer to use for a non-splice fallback path.

Jason

#35 lore raw

PATCH 6/9 vfio/migration: Implement VFIO migration protocol v2

In reply to Avihai Horon

Replace the current VFIO migration protocol v1 implementation with a new implementation corresponding to VFIO migration protocol v2.

The main changes are:
- VFIO device state is now represented as a finite state machine instead of a bitmap.

- Migration interface with kernel is now done using VFIO_DEVICE_FEATURE ioctl and normal read() and write() instead of the migration region.

- As VFIO migration protocol v2 currently doesn't support the pre-copy phase of migration, .save_live_pending and .save_live_iterate handlers plus pre-copy relevant code are removed.

Detailed information about VFIO migration protocol v2 and difference compared to v1 can be found here [1].

[1]
https://lore.kernel.org/all/[email protected]/

---
 hw/vfio/common.c              |  21 +-
 hw/vfio/migration.c           | 628 +++++++---------------------------
 hw/vfio/trace-events          |   9 +-
 include/hw/vfio/vfio-common.h |   8 +-
 4 files changed, 153 insertions(+), 513 deletions(-)
hw/vfio/common.c +13 -8
index 29982c7af8..4c6baa5a79 100644
@@ -40,6 +40,7 @@
 #include "trace.h"
 #include "qapi/error.h"
 #include "migration/migration.h"
+#include "migration/misc.h"
 #include "sysemu/tpm.h"
 
 VFIOGroupList vfio_group_list =
@@ -354,8 +355,9 @@ static bool vfio_devices_all_dirty_tracking(VFIOContainer *container)
                 return false;
             }
 
-            if ((vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF)
-                && (migration->device_state & VFIO_DEVICE_STATE_V1_RUNNING)) {
+            if ((vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF) &&
+                 (migration->device_state == VFIO_DEVICE_STATE_RUNNING ||
+                 migration->device_state == VFIO_DEVICE_STATE_RUNNING_P2P)) {
                 return false;
             }
         }
@@ -363,13 +365,16 @@ static bool vfio_devices_all_dirty_tracking(VFIOContainer *container)
     return true;
 }
 
-static bool vfio_devices_all_running_and_saving(VFIOContainer *container)
+/*
+ * Check if all VFIO devices are running and migration is active, which is
+ * essentially equivalent to the migration being in pre-copy phase.
+ */
+static bool vfio_devices_all_running_and_mig_active(VFIOContainer *container)
 {
     VFIOGroup *group;
     VFIODevice *vbasedev;
-    MigrationState *ms = migrate_get_current();
 
-    if (!migration_is_setup_or_active(ms->state)) {
+    if (!migration_is_active(migrate_get_current())) {
         return false;
     }
 
@@ -381,8 +386,8 @@ static bool vfio_devices_all_running_and_saving(VFIOContainer *container)
                 return false;
             }
 
-            if ((migration->device_state & VFIO_DEVICE_STATE_V1_SAVING) &&
-                (migration->device_state & VFIO_DEVICE_STATE_V1_RUNNING)) {
+            if (migration->device_state == VFIO_DEVICE_STATE_RUNNING ||
+                migration->device_state == VFIO_DEVICE_STATE_RUNNING_P2P) {
                 continue;
             } else {
                 return false;
@@ -461,7 +466,7 @@ static int vfio_dma_unmap(VFIOContainer *container,
     };
 
     if (iotlb && container->dirty_pages_supported &&
-        vfio_devices_all_running_and_saving(container)) {
+        vfio_devices_all_running_and_mig_active(container)) {
         return vfio_dma_unmap_bitmap(container, iova, size, iotlb);
     }
 
hw/vfio/migration.c +133 -495

833 lines not on this page · raw message

hw/vfio/trace-events +3 -6
index 582882db91..a24ea7d8b0 100644
@@ -148,21 +148,18 @@ vfio_display_edid_update(uint32_t prefx, uint32_t prefy) "%ux%u"
 vfio_display_edid_write_error(void) ""
 
 # migration.c
-vfio_migration_probe(const char *name, uint32_t index) " (%s) Region %d"
+vfio_migration_probe(const char *name) " (%s)"
 vfio_migration_set_state(const char *name, uint32_t state) " (%s) state %d"
 vfio_vmstate_change(const char *name, int running, const char *reason, uint32_t dev_state) " (%s) running %d reason %s device state %d"
 vfio_migration_state_notifier(const char *name, const char *state) " (%s) state %s"
 vfio_save_setup(const char *name) " (%s)"
 vfio_save_cleanup(const char *name) " (%s)"
-vfio_save_buffer(const char *name, uint64_t data_offset, uint64_t data_size, uint64_t pending) " (%s) Offset 0x%"PRIx64" size 0x%"PRIx64" pending 0x%"PRIx64
-vfio_update_pending(const char *name, uint64_t pending) " (%s) pending 0x%"PRIx64
 vfio_save_device_config_state(const char *name) " (%s)"
-vfio_save_pending(const char *name, uint64_t precopy, uint64_t postcopy, uint64_t compatible) " (%s) precopy 0x%"PRIx64" postcopy 0x%"PRIx64" compatible 0x%"PRIx64
-vfio_save_iterate(const char *name, int data_size) " (%s) data_size %d"
 vfio_save_complete_precopy(const char *name) " (%s)"
 vfio_load_device_config_state(const char *name) " (%s)"
 vfio_load_state(const char *name, uint64_t data) " (%s) data 0x%"PRIx64
-vfio_load_state_device_data(const char *name, uint64_t data_offset, uint64_t data_size) " (%s) Offset 0x%"PRIx64" size 0x%"PRIx64
+vfio_load_state_device_data(const char *name, uint64_t data_size) " (%s) size 0x%"PRIx64
 vfio_load_cleanup(const char *name) " (%s)"
 vfio_get_dirty_bitmap(int fd, uint64_t iova, uint64_t size, uint64_t bitmap_size, uint64_t start) "container fd=%d, iova=0x%"PRIx64" size= 0x%"PRIx64" bitmap_size=0x%"PRIx64" start=0x%"PRIx64
 vfio_iommu_map_dirty_notify(uint64_t iova_start, uint64_t iova_end) "iommu dirty @ 0x%"PRIx64" - 0x%"PRIx64
+vfio_save_block(const char *name, int data_size) " (%s) data_size %d"
include/hw/vfio/vfio-common.h +4 -4
index e573f5a9f1..09446a9082 100644
@@ -61,11 +61,11 @@ typedef struct VFIORegion {
 typedef struct VFIOMigration {
     struct VFIODevice *vbasedev;
     VMChangeStateEntry *vm_state;
-    VFIORegion region;
-    uint32_t device_state;
-    int vm_running;
+    enum vfio_device_mig_state device_state;
+    int data_fd;
     Notifier migration_state;
-    uint64_t pending_bytes;
+    void *data_buffer;
+    size_t data_buffer_size;
 } VFIOMigration;
 
 typedef struct VFIOAddressSpace {
Signature · 1 line
2.21.3
#36 lore raw
Quoted 20 lines · Avihai Horon

Replace the current VFIO migration protocol v1 implementation with a new implementation corresponding to VFIO migration protocol v2.

The main changes are:
- VFIO device state is now represented as a finite state machine instead of a bitmap.

- Migration interface with kernel is now done using VFIO_DEVICE_FEATURE ioctl and normal read() and write() instead of the migration region.

- As VFIO migration protocol v2 currently doesn't support the pre-copy phase of migration, .save_live_pending and .save_live_iterate handlers plus pre-copy relevant code are removed.

Detailed information about VFIO migration protocol v2 and difference compared to v1 can be found here [1].

[1]
https://lore.kernel.org/all/[email protected]/

Quoted 8 lines
---
 hw/vfio/common.c              |  21 +-
 hw/vfio/migration.c           | 628 +++++++---------------------------
 hw/vfio/trace-events          |   9 +-
 include/hw/vfio/vfio-common.h |   8 +-
 4 files changed, 153 insertions(+), 513 deletions(-)

This looks like a fairly big patch, though more than 70% of it is removing code. Perhaps you could split it into adding v2 and removing v1 afterwards, rather than a single replacement patch? It's just a suggestion anyhow, to hopefully ease analysis of the new additions. The removal looks to muddle a tiny bit.

I don't wanna throw you into potentially unnecessary work should maintainers disagree, so here's an attempt:

https://github.com/jpemartins/qemu/commits/for-avihai

If you apply your series on top of the same base commit (78ac2eebbab9) you should be able to compare both branches.

I haven't found yet any particular flaws in your new logic (but will reply back if I find any).

#37 lore raw
Quoted 37 lines · Joao Martins

External email: Use caution opening links or attachments

Quoted 20 lines · Avihai Horon

Replace the current VFIO migration protocol v1 implementation with a new implementation corresponding to VFIO migration protocol v2.

The main changes are:
- VFIO device state is now represented as a finite state machine instead of a bitmap.

- Migration interface with kernel is now done using VFIO_DEVICE_FEATURE ioctl and normal read() and write() instead of the migration region.

- As VFIO migration protocol v2 currently doesn't support the pre-copy phase of migration, .save_live_pending and .save_live_iterate handlers plus pre-copy relevant code are removed.

Detailed information about VFIO migration protocol v2 and difference compared to v1 can be found here [1].

[1]
https://lore.kernel.org/all/[email protected]/

Quoted 8 lines
---
  hw/vfio/common.c              |  21 +-
  hw/vfio/migration.c           | 628 +++++++---------------------------
  hw/vfio/trace-events          |   9 +-
  include/hw/vfio/vfio-common.h |   8 +-
  4 files changed, 153 insertions(+), 513 deletions(-)

This looks like a fairly big patch, though more than 70% of it is removing code. Perhaps you could split it into adding v2 and removing v1 afterwards, rather than a single replacement patch? It's just a suggestion anyhow, to hopefully ease analysis of the new additions. The removal looks to muddle a tiny bit.

Quoted 5 lines

I don't wanna throw you into potentially unnecessary work should maintainers disagree, so here's an attempt:

https://github.com/jpemartins/qemu/commits/for-avihai

Ah, nice idea, thanks! I was afraid this patch would be too cluttered.

Alex, do you want me to split this patch in a similar manner as Joao suggested? and maybe add v1 prefixes to existing functions instead of v2 to new functions?

Quoted 5 lines

If you apply your series on top of the same base commit (78ac2eebbab9) you should be able to compare both branches.

I haven't found yet any particular flaws in your new logic (but will reply back if I find any).

Sure, thanks!

#38 lore raw

PATCH 7/9 vfio/migration: Reset device if setting recover state fails

In reply to Avihai Horon

If vfio_migration_set_state() fails to set the device in the requested state it tries to put it in a recover state. If setting the device in the recover state fails as well, hw_error is triggered and the VM is aborted.

To improve user experience and avoid VM data loss, reset the device with VFIO_RESET_DEVICE instead of aborting the VM.

---
 hw/vfio/migration.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
hw/vfio/migration.c +10 -2
index 8943ccbace..aec8afcd6c 100644
@@ -89,8 +89,16 @@ static int vfio_migration_set_state(VFIODevice *vbasedev,
         /* Try to put the device in some good state */
         mig_state->device_state = recover_state;
         if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) {
-            hw_error("%s: Device in error state, can't recover",
-                     vbasedev->name);
+            if (ioctl(vbasedev->fd, VFIO_DEVICE_RESET)) {
+                hw_error("%s: Device in error state, can't recover",
+                         vbasedev->name);
+            }
+
+            error_report(
+                "%s: Device was reset due to failure in changing device state to recover state %s",
+                vbasedev->name, mig_state_to_str(recover_state));
+
+            return -1;
         }
 
         error_report("%s: Failed changing device state to %s", vbasedev->name,
Signature · 1 line
2.21.3
#39 lore raw

PATCH 8/9 vfio: Alphabetize migration section of VFIO trace-events file

In reply to Avihai Horon

Sort the migration section of VFIO trace events file alphabetically and move two misplaced traces to common.c section.

---
 hw/vfio/trace-events | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)
hw/vfio/trace-events +10 -10
index a24ea7d8b0..d3cba59bfd 100644
@@ -119,6 +119,8 @@ vfio_region_sparse_mmap_header(const char *name, int index, int nr_areas) "Devic
 vfio_region_sparse_mmap_entry(int i, unsigned long start, unsigned long end) "sparse entry %d [0x%lx - 0x%lx]"
 vfio_get_dev_region(const char *name, int index, uint32_t type, uint32_t subtype) "%s index %d, %08x/%0x8"
 vfio_dma_unmap_overflow_workaround(void) ""
+vfio_get_dirty_bitmap(int fd, uint64_t iova, uint64_t size, uint64_t bitmap_size, uint64_t start) "container fd=%d, iova=0x%"PRIx64" size= 0x%"PRIx64" bitmap_size=0x%"PRIx64" start=0x%"PRIx64
+vfio_iommu_map_dirty_notify(uint64_t iova_start, uint64_t iova_end) "iommu dirty @ 0x%"PRIx64" - 0x%"PRIx64
 
 # platform.c
 vfio_platform_base_device_init(char *name, int groupid) "%s belongs to group #%d"
@@ -148,18 +150,16 @@ vfio_display_edid_update(uint32_t prefx, uint32_t prefy) "%ux%u"
 vfio_display_edid_write_error(void) ""
 
 # migration.c
+vfio_load_cleanup(const char *name) " (%s)"
+vfio_load_device_config_state(const char *name) " (%s)"
+vfio_load_state(const char *name, uint64_t data) " (%s) data 0x%"PRIx64
+vfio_load_state_device_data(const char *name, uint64_t data_size) " (%s) size 0x%"PRIx64
 vfio_migration_probe(const char *name) " (%s)"
 vfio_migration_set_state(const char *name, uint32_t state) " (%s) state %d"
-vfio_vmstate_change(const char *name, int running, const char *reason, uint32_t dev_state) " (%s) running %d reason %s device state %d"
 vfio_migration_state_notifier(const char *name, const char *state) " (%s) state %s"
-vfio_save_setup(const char *name) " (%s)"
+vfio_save_block(const char *name, int data_size) " (%s) data_size %d"
 vfio_save_cleanup(const char *name) " (%s)"
-vfio_save_device_config_state(const char *name) " (%s)"
 vfio_save_complete_precopy(const char *name) " (%s)"
-vfio_load_device_config_state(const char *name) " (%s)"
-vfio_load_state(const char *name, uint64_t data) " (%s) data 0x%"PRIx64
-vfio_load_state_device_data(const char *name, uint64_t data_size) " (%s) size 0x%"PRIx64
-vfio_load_cleanup(const char *name) " (%s)"
-vfio_get_dirty_bitmap(int fd, uint64_t iova, uint64_t size, uint64_t bitmap_size, uint64_t start) "container fd=%d, iova=0x%"PRIx64" size= 0x%"PRIx64" bitmap_size=0x%"PRIx64" start=0x%"PRIx64
-vfio_iommu_map_dirty_notify(uint64_t iova_start, uint64_t iova_end) "iommu dirty @ 0x%"PRIx64" - 0x%"PRIx64
-vfio_save_block(const char *name, int data_size) " (%s) data_size %d"
+vfio_save_device_config_state(const char *name) " (%s)"
+vfio_save_setup(const char *name) " (%s)"
+vfio_vmstate_change(const char *name, int running, const char *reason, uint32_t dev_state) " (%s) running %d reason %s device state %d"
Signature · 1 line
2.21.3
#40 lore raw

PATCH 9/9 docs/devel: Align vfio-migration docs to VFIO migration v2

In reply to Avihai Horon

Align the vfio-migration documentation to VFIO migration protocol v2.

---
 docs/devel/vfio-migration.rst | 77 +++++++++++++++--------------------
 1 file changed, 33 insertions(+), 44 deletions(-)
docs/devel/vfio-migration.rst +33 -44
index 9ff6163c88..09744af5a6 100644
@@ -7,46 +7,35 @@ the guest is running on source host and restoring this saved state on the
 destination host. This document details how saving and restoring of VFIO
 devices is done in QEMU.
 
-Migration of VFIO devices consists of two phases: the optional pre-copy phase,
-and the stop-and-copy phase. The pre-copy phase is iterative and allows to
-accommodate VFIO devices that have a large amount of data that needs to be
-transferred. The iterative pre-copy phase of migration allows for the guest to
-continue whilst the VFIO device state is transferred to the destination, this
-helps to reduce the total downtime of the VM. VFIO devices can choose to skip
-the pre-copy phase of migration by returning pending_bytes as zero during the
-pre-copy phase.
+Migration of VFIO devices currently consists of a single stop-and-copy phase.
+During the stop-and-copy phase the guest is stopped and the entire VFIO device
+data is transferred to the destination.
+
+The pre-copy phase of migration is currently not supported for VFIO devices,
+so VFIO device data is not transferred during pre-copy phase.
 
 A detailed description of the UAPI for VFIO device migration can be found in
-the comment for the ``vfio_device_migration_info`` structure in the header
-file linux-headers/linux/vfio.h.
+the comment for the ``vfio_device_mig_state`` structure in the header file
+linux-headers/linux/vfio.h.
 
 VFIO implements the device hooks for the iterative approach as follows:
 
-* A ``save_setup`` function that sets up the migration region and sets _SAVING
-  flag in the VFIO device state.
-
-* A ``load_setup`` function that sets up the migration region on the
-  destination and sets _RESUMING flag in the VFIO device state.
-
-* A ``save_live_pending`` function that reads pending_bytes from the vendor
-  driver, which indicates the amount of data that the vendor driver has yet to
-  save for the VFIO device.
+* A ``save_setup`` function that sets up migration on the source.
 
-* A ``save_live_iterate`` function that reads the VFIO device's data from the
-  vendor driver through the migration region during iterative phase.
+* A ``load_setup`` function that sets the VFIO device on the destination in
+  _RESUMING state.
 
 * A ``save_state`` function to save the device config space if it is present.
 
-* A ``save_live_complete_precopy`` function that resets _RUNNING flag from the
-  VFIO device state and iteratively copies the remaining data for the VFIO
-  device until the vendor driver indicates that no data remains (pending bytes
-  is zero).
+* A ``save_live_complete_precopy`` function that sets the VFIO device in
+  _STOP_COPY state and iteratively copies the data for the VFIO device until
+  the vendor driver indicates that no data remains.
 
 * A ``load_state`` function that loads the config section and the data
-  sections that are generated by the save functions above
+  sections that are generated by the save functions above.
 
 * ``cleanup`` functions for both save and load that perform any migration
-  related cleanup, including unmapping the migration region
+  related cleanup.
 
 
 The VFIO migration code uses a VM state change handler to change the VFIO
@@ -71,13 +60,13 @@ tracking can identify dirtied pages, but any page pinned by the vendor driver
 can also be written by the device. There is currently no device or IOMMU
 support for dirty page tracking in hardware.
 
-By default, dirty pages are tracked when the device is in pre-copy as well as
-stop-and-copy phase. So, a page pinned by the vendor driver will be copied to
-the destination in both phases. Copying dirty pages in pre-copy phase helps
-QEMU to predict if it can achieve its downtime tolerances. If QEMU during
-pre-copy phase keeps finding dirty pages continuously, then it understands
-that even in stop-and-copy phase, it is likely to find dirty pages and can
-predict the downtime accordingly.
+By default, dirty pages are tracked during pre-copy as well as stop-and-copy
+phase. So, a page pinned by the vendor driver will be copied to the destination
+in both phases. Copying dirty pages in pre-copy phase helps QEMU to predict if
+it can achieve its downtime tolerances. If QEMU during pre-copy phase keeps
+finding dirty pages continuously, then it understands that even in stop-and-copy
+phase, it is likely to find dirty pages and can predict the downtime
+accordingly.
 
 QEMU also provides a per device opt-out option ``pre-copy-dirty-page-tracking``
 which disables querying the dirty bitmap during pre-copy phase. If it is set to
@@ -111,23 +100,23 @@ Live migration save path
                                   |
                      migrate_init spawns migration_thread
                 Migration thread then calls each device's .save_setup()
-                    (RUNNING, _SETUP, _RUNNING|_SAVING)
+                       (RUNNING, _SETUP, _RUNNING)
                                   |
-                    (RUNNING, _ACTIVE, _RUNNING|_SAVING)
-             If device is active, get pending_bytes by .save_live_pending()
-          If total pending_bytes >= threshold_size, call .save_live_iterate()
-                  Data of VFIO device for pre-copy phase is copied
+                      (RUNNING, _ACTIVE, _RUNNING)
+         Migration thread calls each .save_live_pending() handler
+  If total pending_bytes >= threshold_size, call each .save_live_iterate() handler
+          Data of this iteration for pre-copy phase is copied
         Iterate till total pending bytes converge and are less than threshold
                                   |
   On migration completion, vCPU stops and calls .save_live_complete_precopy for
-   each active device. The VFIO device is then transitioned into _SAVING state
-                   (FINISH_MIGRATE, _DEVICE, _SAVING)
+  each active device. The VFIO device is then transitioned into _STOP_COPY state
+                  (FINISH_MIGRATE, _DEVICE, _STOP_COPY)
                                   |
      For the VFIO device, iterate in .save_live_complete_precopy until
                          pending data is 0
-                   (FINISH_MIGRATE, _DEVICE, _STOPPED)
+                   (FINISH_MIGRATE, _DEVICE, _STOP)
                                   |
-                 (FINISH_MIGRATE, _COMPLETED, _STOPPED)
+                 (FINISH_MIGRATE, _COMPLETED, _STOP)
              Migraton thread schedules cleanup bottom half and exits
 
 Live migration resume path
@@ -136,7 +125,7 @@ Live migration resume path
 ::
 
               Incoming migration calls .load_setup for each device
-                       (RESTORE_VM, _ACTIVE, _STOPPED)
+                       (RESTORE_VM, _ACTIVE, _STOP)
                                  |
        For each device, .load_state is called for that device section data
                        (RESTORE_VM, _ACTIVE, _RESUMING)
Signature · 1 line
2.21.3
#41 lore raw
In reply to Avihai Horon
Quoted 5 lines · On Thu, 12 May 2022 18:43:11 +0300 Avihai Horon <[email protected]> wrote:

Hello,

Following VFIO migration protocol v2 acceptance in kernel, this series implements VFIO migration according to the new v2 protocol and replaces the now deprecated v1 implementation.

Let's not bottleneck others waiting on a linux header file update on also incorporating v2 support. In the short term we just need the first two patches here.

Are there any objections to folding those patches together for the sake of bisection? Thanks,

Alex

#42 lore raw
Quoted 9 lines · Alex Williamson
Quoted 5 lines · On Thu, 12 May 2022 18:43:11 +0300 Avihai Horon <[email protected]> wrote:

Hello,

Following VFIO migration protocol v2 acceptance in kernel, this series implements VFIO migration according to the new v2 protocol and replaces the now deprecated v1 implementation.

Quoted 8 lines

Let's not bottleneck others waiting on a linux header file update on also incorporating v2 support. In the short term we just need the first two patches here.

Are there any objections to folding those patches together for the sake of bisection? Thanks,

Alex

I think folding the headers update and the fixup together makes a lot of sense. And yes, I'd like to see it in QEMU quickly in order to unblock other series.