Skip to contentSkip to conversation

UFFD write-tracking migration/snapshots

PATCH Superseded andrey.gruzdev--- via 6 participants 50 messages Jan 21, 2021 – Feb 24, 2021 Arm/Amlogic Meson SoC support

v13 of 14 Superseded Latest is v14 →

lore
Share & tools
lore
#0 lore raw

v13 cover UFFD write-tracking migration/snapshots

This patch series is a kind of 'rethinking' of Denis Plotnikov's ideas he's implemented in his series '[PATCH v0 0/4] migration: add background snapshot'.

Currently the only way to make (external) live VM snapshot is using existing dirty page logging migration mechanism. The main problem is that it tends to produce a lot of page duplicates while running VM goes on updating already saved pages. That leads to the fact that vmstate image size is commonly several times bigger then non-zero part of virtual machine's RSS. Time required to converge RAM migration and the size of snapshot image severely depend on the guest memory write rate, sometimes resulting in unacceptably long snapshot creation time and huge image size.

This series propose a way to solve the aforementioned problems. This is done by using different RAM migration mechanism based on UFFD write protection management introduced in v5.7 kernel. The migration strategy is to 'freeze' guest RAM content using write-protection and iteratively release protection for memory ranges that have already been saved to the migration stream. At the same time we read in pending UFFD write fault events and save those pages out-of-order with higher priority.

How to use:
1. Enable write-tracking migration capability
virsh qemu-monitor-command <domain> --hmp migrate_set_capability background-snapshot on

2. Start the external migration to a file
virsh qemu-monitor-command <domain> --hmp migrate exec:'cat > ./vm_state'

3. Wait for the migration finish and check that the migration has completed. state.

Changes v12->v13:

* 1. Fixed codestyle problem for checkpatch.

Changes v11->v12:

* 1. Consolidated UFFD-related code under single #if defined(__linux__).
* 2. Abandoned use of pre/post hooks in ram_find_and_save_block() in favour
* of more compact code fragment in ram_save_host_page().
* 3. Refactored/simplified eBPF code in userfaultfd-wrlat.py script.

Changes v10->v11:

* 1. Updated commit messages.

Changes v9->v10:

* 1. Fixed commit message for [PATCH v9 1/5].

Changes v8->v9:

* 1. Fixed wrong cover letter subject.

Changes v7->v8:

* 1. Fixed coding style problems to pass checkpatch.

Changes v6->v7:

* 1. Fixed background snapshot on suspended guest: call qemu_system_wakeup_request()
* before stopping VM to make runstate transition valid.
* 2. Disabled dirty page logging and log syn when 'background-snapshot' is enabled.
* 3. Introduced 'userfaultfd-wrlat.py' script to analyze UFFD write fault latencies.

Changes v5->v6:

* 1. Consider possible hot pluggin/unpluggin of memory device - don't use static
* for write-tracking support level in migrate_query_write_tracking(), check
* each time when one tries to enable 'background-snapshot' capability.

Changes v4->v5:

* 1. Refactored util/userfaultfd.c code to support features required by postcopy.
* 2. Introduced checks for host kernel and guest memory backend compatibility
* to 'background-snapshot' branch in migrate_caps_check().
* 3. Switched to using trace_xxx instead of info_report()/error_report() for

*    cases when error message must be hidden (probing UFFD-IO) or info may be
*    really littering output if goes to stderr.
* 4  Added RCU_READ_LOCK_GUARDs to the code dealing with RAM block list.

* 5. Added memory_region_ref() for each RAM block being wr-protected.
* 6. Reused qemu_ram_block_from_host() instead of custom RAM block lookup routine.
* 7. Refused from using specific hwaddr/ram_addr_t in favour of void */uint64_t.
* 8. Currently dropped 'linear-scan-rate-limiting' patch. The reason is that

*    that choosen criteria for high-latency fault detection (i.e. timestamp of
*    UFFD event fetch) is not representative enough for this task.
*    At the moment it looks somehow like premature optimization effort.

* 8. Dropped some unnecessary/unused code.

Andrey Gruzdev (5):
migration: introduce 'background-snapshot' migration capability
migration: introduce UFFD-WP low-level interface helpers
migration: support UFFD write fault processing in ram_save_iterate()
migration: implementation of background snapshot thread
migration: introduce 'userfaultfd-wrlat.py' script

 include/exec/memory.h        |   8 +
 include/qemu/userfaultfd.h   |  35 ++++
 migration/migration.c        | 357 ++++++++++++++++++++++++++++++++++-
 migration/migration.h        |   4 +
 migration/ram.c              | 303 ++++++++++++++++++++++++++++-
 migration/ram.h              |   6 +
 migration/savevm.c           |   1 -
 migration/savevm.h           |   2 +
 migration/trace-events       |   2 +
 qapi/migration.json          |   7 +-
 scripts/userfaultfd-wrlat.py | 122 ++++++++++++
 util/meson.build             |   1 +
 util/trace-events            |   9 +
 util/userfaultfd.c           | 345 +++++++++++++++++++++++++++++++++
 14 files changed, 1190 insertions(+), 12 deletions(-)
 create mode 100644 include/qemu/userfaultfd.h
 create mode 100755 scripts/userfaultfd-wrlat.py
 create mode 100644 util/userfaultfd.c
Signature · 1 line
2.25.1
#1 lore raw

PATCH v13 1/5 migration: introduce 'background-snapshot' migration capability

Add new capability to 'qapi/migration.json' schema. Update migrate_caps_check() to validate enabled capability set against introduced one. Perform checks for required kernel features and compatibility with guest memory backends.

---
 migration/migration.c | 110 ++++++++++++++++++++++++++++++++++++++++++
 migration/migration.h |   1 +
 migration/ram.c       |  21 ++++++++
 migration/ram.h       |   4 ++
 qapi/migration.json   |   7 ++-
 5 files changed, 142 insertions(+), 1 deletion(-)
migration/migration.c +110 -0
index d5136419bf..f018337fbc 100644
@@ -58,6 +58,7 @@
 #include "qemu/queue.h"
 #include "multifd.h"
 #include "qemu/yank.h"
+#include "sysemu/cpus.h"
 
 #ifdef CONFIG_VFIO
 #include "hw/vfio/vfio-common.h"
@@ -134,6 +135,38 @@ enum mig_rp_message_type {
     MIG_RP_MSG_MAX
 };
 
+/* Migration capabilities set */
+struct MigrateCapsSet {
+    int size;                       /* Capability set size */
+    MigrationCapability caps[];     /* Variadic array of capabilities */
+};
+typedef struct MigrateCapsSet MigrateCapsSet;
+
+/* Define and initialize MigrateCapsSet */
+#define INITIALIZE_MIGRATE_CAPS_SET(_name, ...)   \
+    MigrateCapsSet _name = {    \
+        .size = sizeof((int []) { __VA_ARGS__ }) / sizeof(int), \
+        .caps = { __VA_ARGS__ } \
+    }
+
+/* Background-snapshot compatibility check list */
+static const
+INITIALIZE_MIGRATE_CAPS_SET(check_caps_background_snapshot,
+    MIGRATION_CAPABILITY_POSTCOPY_RAM,
+    MIGRATION_CAPABILITY_DIRTY_BITMAPS,
+    MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME,
+    MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE,
+    MIGRATION_CAPABILITY_RETURN_PATH,
+    MIGRATION_CAPABILITY_MULTIFD,
+    MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER,
+    MIGRATION_CAPABILITY_AUTO_CONVERGE,
+    MIGRATION_CAPABILITY_RELEASE_RAM,
+    MIGRATION_CAPABILITY_RDMA_PIN_ALL,
+    MIGRATION_CAPABILITY_COMPRESS,
+    MIGRATION_CAPABILITY_XBZRLE,
+    MIGRATION_CAPABILITY_X_COLO,
+    MIGRATION_CAPABILITY_VALIDATE_UUID);
+
 /* When we add fault tolerance, we could have several
    migrations at once.  For now we don't need to add
    dynamic creation of migration */
@@ -1097,6 +1130,33 @@ static void fill_source_migration_info(MigrationInfo *info)
     info->status = s->state;
 }
 
+#ifdef CONFIG_LINUX
+typedef enum WriteTrackingSupport {
+    WT_SUPPORT_UNKNOWN = 0,
+    WT_SUPPORT_ABSENT,
+    WT_SUPPORT_AVAILABLE,
+    WT_SUPPORT_COMPATIBLE
+} WriteTrackingSupport;
+
+static
+WriteTrackingSupport migrate_query_write_tracking(void)
+{
+    /* Check if kernel supports required UFFD features */
+    if (!ram_write_tracking_available()) {
+        return WT_SUPPORT_ABSENT;
+    }
+    /*
+     * Check if current memory configuration is
+     * compatible with required UFFD features.
+     */
+    if (!ram_write_tracking_compatible()) {
+        return WT_SUPPORT_AVAILABLE;
+    }
+
+    return WT_SUPPORT_COMPATIBLE;
+}
+#endif /* CONFIG_LINUX */
+
 /**
  * @migration_caps_check - check capability validity
  *
@@ -1158,6 +1218,45 @@ static bool migrate_caps_check(bool *cap_list,
         }
     }
 
+    if (cap_list[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT]) {
+#ifdef CONFIG_LINUX
+        WriteTrackingSupport wt_support;
+        int idx;
+        /*
+         * Check if 'background-snapshot' capability is supported by
+         * host kernel and compatible with guest memory configuration.
+         */
+        wt_support = migrate_query_write_tracking();
+        if (wt_support < WT_SUPPORT_AVAILABLE) {
+            error_setg(errp, "Background-snapshot is not supported by host kernel");
+            return false;
+        }
+        if (wt_support < WT_SUPPORT_COMPATIBLE) {
+            error_setg(errp, "Background-snapshot is not compatible "
+                    "with guest memory configuration");
+            return false;
+        }
+
+        /*
+         * Check if there are any migration capabilities
+         * incompatible with 'background-snapshot'.
+         */
+        for (idx = 0; idx < check_caps_background_snapshot.size; idx++) {
+            int incomp_cap = check_caps_background_snapshot.caps[idx];
+            if (cap_list[incomp_cap]) {
+                error_setg(errp,
+                        "Background-snapshot is not compatible with %s",
+                        MigrationCapability_str(incomp_cap));
+                return false;
+            }
+        }
+#else
+        error_setg(errp,
+                "Background-snapshot is not supported on non-Linux hosts");
+        return false;
+#endif
+    }
+
     return true;
 }
 
@@ -2499,6 +2598,15 @@ bool migrate_use_block_incremental(void)
     return s->parameters.block_incremental;
 }
 
+bool migrate_background_snapshot(void)
+{
+    MigrationState *s;
+
+    s = migrate_get_current();
+
+    return s->enabled_capabilities[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT];
+}
+
 /* migration thread support */
 /*
  * Something bad happened to the RP stream, mark an error
@@ -3792,6 +3900,8 @@ static Property migration_properties[] = {
     DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
     DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
     DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
+    DEFINE_PROP_MIG_CAP("x-background-snapshot",
+            MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT),
 
     DEFINE_PROP_END_OF_LIST(),
 };
migration/migration.h +1 -0
index d096b77f74..f40338cfbf 100644
@@ -341,6 +341,7 @@ int migrate_compress_wait_thread(void);
 int migrate_decompress_threads(void);
 bool migrate_use_events(void);
 bool migrate_postcopy_blocktime(void);
+bool migrate_background_snapshot(void);
 
 /* Sending on the return path - generic and then for each message type */
 void migrate_send_rp_shut(MigrationIncomingState *mis,
migration/ram.c +21 -0
index 7811cde643..ae8de17153 100644
@@ -3788,6 +3788,27 @@ static int ram_resume_prepare(MigrationState *s, void *opaque)
     return 0;
 }
 
+/* ram_write_tracking_available: check if kernel supports required UFFD features
+ *
+ * Returns true if supports, false otherwise
+ */
+bool ram_write_tracking_available(void)
+{
+    /* TODO: implement */
+    return false;
+}
+
+/* ram_write_tracking_compatible: check if guest configuration is
+ *   compatible with 'write-tracking'
+ *
+ * Returns true if compatible, false otherwise
+ */
+bool ram_write_tracking_compatible(void)
+{
+    /* TODO: implement */
+    return false;
+}
+
 static SaveVMHandlers savevm_ram_handlers = {
     .save_setup = ram_save_setup,
     .save_live_iterate = ram_save_iterate,
migration/ram.h +4 -0
index 011e85414e..1a9ff90304 100644
@@ -79,4 +79,8 @@ void colo_flush_ram_cache(void);
 void colo_release_ram_cache(void);
 void colo_incoming_start_dirty_log(void);
 
+/* Background snapshot */
+bool ram_write_tracking_available(void);
+bool ram_write_tracking_compatible(void);
+
 #endif
qapi/migration.json +6 -1
index d1d9632c2a..6c12b368aa 100644
@@ -442,6 +442,11 @@
 # @validate-uuid: Send the UUID of the source to allow the destination
 #                 to ensure it is the same. (since 4.2)
 #
+# @background-snapshot: If enabled, the migration stream will be a snapshot
+#                       of the VM exactly at the point when the migration
+#                       procedure starts. The VM RAM is saved with running VM.
+#                       (since 6.0)
+#
 # Since: 1.2
 ##
 { 'enum': 'MigrationCapability',
@@ -449,7 +454,7 @@
            'compress', 'events', 'postcopy-ram', 'x-colo', 'release-ram',
            'block', 'return-path', 'pause-before-switchover', 'multifd',
            'dirty-bitmaps', 'postcopy-blocktime', 'late-block-activate',
-           'x-ignore-shared', 'validate-uuid' ] }
+           'x-ignore-shared', 'validate-uuid', 'background-snapshot'] }
 
 ##
 # @MigrationCapabilityStatus:
Signature · 1 line
2.25.1
#2 lore raw

PATCH v13 2/5 migration: introduce UFFD-WP low-level interface helpers

In reply to andrey.gruzdev--- via

Glue code to the userfaultfd kernel implementation. Querying feature support, createing file descriptor, feature control, memory region registration, IOCTLs on registered registered regions.

---
 include/exec/memory.h      |   1 +
 include/qemu/userfaultfd.h |  35 ++++
 util/meson.build           |   1 +
 util/trace-events          |   9 +
 util/userfaultfd.c         | 345 +++++++++++++++++++++++++++++++++++++
 5 files changed, 391 insertions(+)
 create mode 100644 include/qemu/userfaultfd.h
 create mode 100644 util/userfaultfd.c
include/exec/memory.h +1 -0
index 521d9901d7..b76b1256bf 100644
@@ -149,6 +149,7 @@ typedef struct IOMMUTLBEvent {
 /* RAM is a persistent kind memory */
 #define RAM_PMEM (1 << 5)
 
+
 static inline void iommu_notifier_init(IOMMUNotifier *n, IOMMUNotify fn,
                                        IOMMUNotifierFlag flags,
                                        hwaddr start, hwaddr end,
include/qemu/userfaultfd.h new file +35 -0
new file mode 100644
index 0000000000..6b74f92792
@@ -0,0 +1,35 @@
+/*
+ * Linux UFFD-WP support
+ *
+ * Copyright Virtuozzo GmbH, 2020
+ *
+ * Authors:
+ *  Andrey Gruzdev   <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef USERFAULTFD_H
+#define USERFAULTFD_H
+
+#include "qemu/osdep.h"
+#include "exec/hwaddr.h"
+#include <linux/userfaultfd.h>
+
+int uffd_query_features(uint64_t *features);
+int uffd_create_fd(uint64_t features, bool non_blocking);
+void uffd_close_fd(int uffd_fd);
+int uffd_register_memory(int uffd_fd, void *addr, uint64_t length,
+        uint64_t mode, uint64_t *ioctls);
+int uffd_unregister_memory(int uffd_fd, void *addr, uint64_t length);
+int uffd_change_protection(int uffd_fd, void *addr, uint64_t length,
+        bool wp, bool dont_wake);
+int uffd_copy_page(int uffd_fd, void *dst_addr, void *src_addr,
+        uint64_t length, bool dont_wake);
+int uffd_zero_page(int uffd_fd, void *addr, uint64_t length, bool dont_wake);
+int uffd_wakeup(int uffd_fd, void *addr, uint64_t length);
+int uffd_read_events(int uffd_fd, struct uffd_msg *msgs, int count);
+bool uffd_poll_events(int uffd_fd, int tmo);
+
+#endif /* USERFAULTFD_H */
util/meson.build +1 -0
index 540a605b78..d45a3a2caf 100644
@@ -51,6 +51,7 @@ endif
 if have_system
   util_ss.add(when: 'CONFIG_GIO', if_true: [files('dbus.c'), gio])
   util_ss.add(files('yank.c'))
+  util_ss.add(when: 'CONFIG_LINUX', if_true: files('userfaultfd.c'))
 endif
 
 if have_block
util/trace-events +9 -0
index 61e0d4bcdf..bac0924899 100644
@@ -91,3 +91,12 @@ qemu_vfio_pci_read_config(void *buf, int ofs, int size, uint64_t region_ofs, uin
 qemu_vfio_pci_write_config(void *buf, int ofs, int size, uint64_t region_ofs, uint64_t region_size) "write cfg ptr %p ofs 0x%x size 0x%x (region addr 0x%"PRIx64" size 0x%"PRIx64")"
 qemu_vfio_region_info(const char *desc, uint64_t region_ofs, uint64_t region_size, uint32_t cap_offset) "region '%s' addr 0x%"PRIx64" size 0x%"PRIx64" cap_ofs 0x%"PRIx32
 qemu_vfio_pci_map_bar(int index, uint64_t region_ofs, uint64_t region_size, int ofs, void *host) "map region bar#%d addr 0x%"PRIx64" size 0x%"PRIx64" ofs 0x%x host %p"
+
+#userfaultfd.c
+uffd_query_features_nosys(int err) "errno: %i"
+uffd_query_features_api_failed(int err) "errno: %i"
+uffd_create_fd_nosys(int err) "errno: %i"
+uffd_create_fd_api_failed(int err) "errno: %i"
+uffd_create_fd_api_noioctl(uint64_t ioctl_req, uint64_t ioctl_supp) "ioctl_req: 0x%" PRIx64 "ioctl_supp: 0x%" PRIx64
+uffd_register_memory_failed(void *addr, uint64_t length, uint64_t mode, int err) "addr: %p length: %" PRIu64 " mode: 0x%" PRIx64 " errno: %i"
+uffd_unregister_memory_failed(void *addr, uint64_t length, int err) "addr: %p length: %" PRIu64 " errno: %i"
util/userfaultfd.c new file +345 -0

345 lines not on this page · raw message

Signature · 1 line
2.25.1
#3 lore raw

PATCH v13 3/5 migration: support UFFD write fault processing in ram_save_iterate()

In reply to andrey.gruzdev--- via

In this particular implementation the same single migration thread is responsible for both normal linear dirty page migration and procesing UFFD page fault events.

Processing write faults includes reading UFFD file descriptor, finding respective RAM block and saving faulting page to the migration stream. After page has been saved, write protection can be removed. Since asynchronous version of qemu_put_buffer() is expected to be used to save pages, we also have to flush migraion stream prior to un-protecting saved memory range.

Write protection is being removed for any previously protected memory chunk that has hit the migration stream. That's valid for pages from linear page scan along with write fault pages.

---
 include/exec/memory.h  |   7 +
 migration/ram.c        | 324 +++++++++++++++++++++++++++++++++++++----
 migration/ram.h        |   2 +
 migration/trace-events |   2 +
 4 files changed, 306 insertions(+), 29 deletions(-)
include/exec/memory.h +7 -0
index b76b1256bf..1aa1c6a3f4 100644
@@ -150,6 +150,13 @@ typedef struct IOMMUTLBEvent {
 #define RAM_PMEM (1 << 5)
 
 
+/*
+ * UFFDIO_WRITEPROTECT is used on this RAMBlock to
+ * support 'write-tracking' migration type.
+ * Implies ram_state->ram_wt_enabled.
+ */
+#define RAM_UF_WRITEPROTECT (1 << 6)
+
 static inline void iommu_notifier_init(IOMMUNotifier *n, IOMMUNotify fn,
                                        IOMMUNotifierFlag flags,
                                        hwaddr start, hwaddr end,
migration/ram.c +295 -29

380 lines not on this page · raw message

migration/ram.h +2 -0
index 1a9ff90304..c25540cb93 100644
@@ -82,5 +82,7 @@ void colo_incoming_start_dirty_log(void);
 /* Background snapshot */
 bool ram_write_tracking_available(void);
 bool ram_write_tracking_compatible(void);
+int ram_write_tracking_start(void);
+void ram_write_tracking_stop(void);
 
 #endif
migration/trace-events +2 -0
index 75de5004ac..668c562fed 100644
@@ -111,6 +111,8 @@ save_xbzrle_page_skipping(void) ""
 save_xbzrle_page_overflow(void) ""
 ram_save_iterate_big_wait(uint64_t milliconds, int iterations) "big wait: %" PRIu64 " milliseconds, %d iterations"
 ram_load_complete(int ret, uint64_t seq_iter) "exit_code %d seq iteration %" PRIu64
+ram_write_tracking_ramblock_start(const char *block_id, size_t page_size, void *addr, size_t length) "%s: page_size: %zu addr: %p length: %zu"
+ram_write_tracking_ramblock_stop(const char *block_id, size_t page_size, void *addr, size_t length) "%s: page_size: %zu addr: %p length: %zu"
 
 # multifd.c
 multifd_new_send_channel_async(uint8_t id) "channel %d"
Signature · 1 line
2.25.1
#4 lore raw

PATCH v13 4/5 migration: implementation of background snapshot thread

In reply to andrey.gruzdev--- via

Introducing implementation of 'background' snapshot thread which in overall follows the logic of precopy migration while internally utilizes completely different mechanism to 'freeze' vmstate at the start of snapshot creation.

This mechanism is based on userfault_fd with wr-protection support and is Linux-specific.

---
 migration/migration.c | 263 ++++++++++++++++++++++++++++++++++++++++--
 migration/migration.h |   3 +
 migration/savevm.c    |   1 -
 migration/savevm.h    |   2 +
 4 files changed, 258 insertions(+), 11 deletions(-)
migration/migration.c +253 -10
index f018337fbc..869afa7a86 100644
@@ -1130,7 +1130,6 @@ static void fill_source_migration_info(MigrationInfo *info)
     info->status = s->state;
 }
 
-#ifdef CONFIG_LINUX
 typedef enum WriteTrackingSupport {
     WT_SUPPORT_UNKNOWN = 0,
     WT_SUPPORT_ABSENT,
@@ -1155,7 +1154,6 @@ WriteTrackingSupport migrate_query_write_tracking(void)
 
     return WT_SUPPORT_COMPATIBLE;
 }
-#endif /* CONFIG_LINUX */
 
 /**
  * @migration_caps_check - check capability validity
@@ -1219,7 +1217,6 @@ static bool migrate_caps_check(bool *cap_list,
     }
 
     if (cap_list[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT]) {
-#ifdef CONFIG_LINUX
         WriteTrackingSupport wt_support;
         int idx;
         /*
@@ -1250,11 +1247,6 @@ static bool migrate_caps_check(bool *cap_list,
                 return false;
             }
         }
-#else
-        error_setg(errp,
-                "Background-snapshot is not supported on non-Linux hosts");
-        return false;
-#endif
     }
 
     return true;
@@ -2016,6 +2008,7 @@ void migrate_init(MigrationState *s)
      * locks.
      */
     s->cleanup_bh = 0;
+    s->vm_start_bh = 0;
     s->to_dst_file = NULL;
     s->state = MIGRATION_STATUS_NONE;
     s->rp_state.from_dst_file = NULL;
@@ -3233,6 +3226,50 @@ fail:
                       MIGRATION_STATUS_FAILED);
 }
 
+/**
+ * bg_migration_completion: Used by bg_migration_thread when after all the
+ *   RAM has been saved. The caller 'breaks' the loop when this returns.
+ *
+ * @s: Current migration state
+ */
+static void bg_migration_completion(MigrationState *s)
+{
+    int current_active_state = s->state;
+
+    /*
+     * Stop tracking RAM writes - un-protect memory, un-register UFFD
+     * memory ranges, flush kernel wait queues and wake up threads
+     * waiting for write fault to be resolved.
+     */
+    ram_write_tracking_stop();
+
+    if (s->state == MIGRATION_STATUS_ACTIVE) {
+        /*
+         * By this moment we have RAM content saved into the migration stream.
+         * The next step is to flush the non-RAM content (device state)
+         * right after the ram content. The device state has been stored into
+         * the temporary buffer before RAM saving started.
+         */
+        qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
+        qemu_fflush(s->to_dst_file);
+    } else if (s->state == MIGRATION_STATUS_CANCELLING) {
+        goto fail;
+    }
+
+    if (qemu_file_get_error(s->to_dst_file)) {
+        trace_migration_completion_file_err();
+        goto fail;
+    }
+
+    migrate_set_state(&s->state, current_active_state,
+                      MIGRATION_STATUS_COMPLETED);
+    return;
+
+fail:
+    migrate_set_state(&s->state, current_active_state,
+                      MIGRATION_STATUS_FAILED);
+}
+
 bool migrate_colo_enabled(void)
 {
     MigrationState *s = migrate_get_current();
@@ -3573,6 +3610,47 @@ static void migration_iteration_finish(MigrationState *s)
     qemu_mutex_unlock_iothread();
 }
 
+static void bg_migration_iteration_finish(MigrationState *s)
+{
+    qemu_mutex_lock_iothread();
+    switch (s->state) {
+    case MIGRATION_STATUS_COMPLETED:
+        migration_calculate_complete(s);
+        break;
+
+    case MIGRATION_STATUS_ACTIVE:
+    case MIGRATION_STATUS_FAILED:
+    case MIGRATION_STATUS_CANCELLED:
+    case MIGRATION_STATUS_CANCELLING:
+        break;
+
+    default:
+        /* Should not reach here, but if so, forgive the VM. */
+        error_report("%s: Unknown ending state %d", __func__, s->state);
+        break;
+    }
+
+    migrate_fd_cleanup_schedule(s);
+    qemu_mutex_unlock_iothread();
+}
+
+/*
+ * Return true if continue to the next iteration directly, false
+ * otherwise.
+ */
+static MigIterateState bg_migration_iteration_run(MigrationState *s)
+{
+    int res;
+
+    res = qemu_savevm_state_iterate(s->to_dst_file, false);
+    if (res > 0) {
+        bg_migration_completion(s);
+        return MIG_ITERATE_BREAK;
+    }
+
+    return MIG_ITERATE_RESUME;
+}
+
 void migration_make_urgent_request(void)
 {
     qemu_sem_post(&migrate_get_current()->rate_limit_sem);
@@ -3720,6 +3798,165 @@ static void *migration_thread(void *opaque)
     return NULL;
 }
 
+static void bg_migration_vm_start_bh(void *opaque)
+{
+    MigrationState *s = opaque;
+
+    qemu_bh_delete(s->vm_start_bh);
+    s->vm_start_bh = NULL;
+
+    vm_start();
+    s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
+}
+
+/**
+ * Background snapshot thread, based on live migration code.
+ * This is an alternative implementation of live migration mechanism
+ * introduced specifically to support background snapshots.
+ *
+ * It takes advantage of userfault_fd write protection mechanism introduced
+ * in v5.7 kernel. Compared to existing dirty page logging migration much
+ * lesser stream traffic is produced resulting in smaller snapshot images,
+ * simply cause of no page duplicates can get into the stream.
+ *
+ * Another key point is that generated vmstate stream reflects machine state
+ * 'frozen' at the beginning of snapshot creation compared to dirty page logging
+ * mechanism, which effectively results in that saved snapshot is the state of VM
+ * at the end of the process.
+ */
+static void *bg_migration_thread(void *opaque)
+{
+    MigrationState *s = opaque;
+    int64_t setup_start;
+    MigThrError thr_error;
+    QEMUFile *fb;
+    bool early_fail = true;
+
+    rcu_register_thread();
+    object_ref(OBJECT(s));
+
+    qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
+
+    setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
+    /*
+     * We want to save vmstate for the moment when migration has been
+     * initiated but also we want to save RAM content while VM is running.
+     * The RAM content should appear first in the vmstate. So, we first
+     * stash the non-RAM part of the vmstate to the temporary buffer,
+     * then write RAM part of the vmstate to the migration stream
+     * with vCPUs running and, finally, write stashed non-RAM part of
+     * the vmstate from the buffer to the migration stream.
+     */
+    s->bioc = qio_channel_buffer_new(128 * 1024);
+    qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
+    fb = qemu_fopen_channel_output(QIO_CHANNEL(s->bioc));
+    object_unref(OBJECT(s->bioc));
+
+    update_iteration_initial_status(s);
+
+    qemu_savevm_state_header(s->to_dst_file);
+    qemu_savevm_state_setup(s->to_dst_file);
+
+    if (qemu_savevm_state_guest_unplug_pending()) {
+        migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
+                          MIGRATION_STATUS_WAIT_UNPLUG);
+
+        while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
+               qemu_savevm_state_guest_unplug_pending()) {
+            qemu_sem_timedwait(&s->wait_unplug_sem, 250);
+        }
+
+        migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG,
+                          MIGRATION_STATUS_ACTIVE);
+    } else {
+        migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
+                MIGRATION_STATUS_ACTIVE);
+    }
+    s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
+
+    trace_migration_thread_setup_complete();
+    s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
+
+    qemu_mutex_lock_iothread();
+
+    /*
+     * If VM is currently in suspended state, then, to make a valid runstate
+     * transition in vm_stop_force_state() we need to wakeup it up.
+     */
+    qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
+    s->vm_was_running = runstate_is_running();
+
+    if (global_state_store()) {
+        goto fail;
+    }
+    /* Forcibly stop VM before saving state of vCPUs and devices */
+    if (vm_stop_force_state(RUN_STATE_PAUSED)) {
+        goto fail;
+    }
+    /*
+     * Put vCPUs in sync with shadow context structures, then
+     * save their state to channel-buffer along with devices.
+     */
+    cpu_synchronize_all_states();
+    if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
+        goto fail;
+    }
+    /* Now initialize UFFD context and start tracking RAM writes */
+    if (ram_write_tracking_start()) {
+        goto fail;
+    }
+    early_fail = false;
+
+    /*
+     * Start VM from BH handler to avoid write-fault lock here.
+     * UFFD-WP protection for the whole RAM is already enabled so
+     * calling VM state change notifiers from vm_start() would initiate
+     * writes to virtio VQs memory which is in write-protected region.
+     */
+    s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
+    qemu_bh_schedule(s->vm_start_bh);
+
+    qemu_mutex_unlock_iothread();
+
+    while (migration_is_active(s)) {
+        MigIterateState iter_state = bg_migration_iteration_run(s);
+        if (iter_state == MIG_ITERATE_SKIP) {
+            continue;
+        } else if (iter_state == MIG_ITERATE_BREAK) {
+            break;
+        }
+
+        /*
+         * Try to detect any kind of failures, and see whether we
+         * should stop the migration now.
+         */
+        thr_error = migration_detect_error(s);
+        if (thr_error == MIG_THR_ERR_FATAL) {
+            /* Stop migration */
+            break;
+        }
+
+        migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
+    }
+
+    trace_migration_thread_after_loop();
+
+fail:
+    if (early_fail) {
+        migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
+                MIGRATION_STATUS_FAILED);
+        qemu_mutex_unlock_iothread();
+    }
+
+    bg_migration_iteration_finish(s);
+
+    qemu_fclose(fb);
+    object_unref(OBJECT(s));
+    rcu_unregister_thread();
+
+    return NULL;
+}
+
 void migrate_fd_connect(MigrationState *s, Error *error_in)
 {
     Error *local_err = NULL;
@@ -3783,8 +4020,14 @@ void migrate_fd_connect(MigrationState *s, Error *error_in)
         migrate_fd_cleanup(s);
         return;
     }
-    qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
-                       QEMU_THREAD_JOINABLE);
+
+    if (migrate_background_snapshot()) {
+        qemu_thread_create(&s->thread, "bg_snapshot",
+                bg_migration_thread, s, QEMU_THREAD_JOINABLE);
+    } else {
+        qemu_thread_create(&s->thread, "live_migration",
+                migration_thread, s, QEMU_THREAD_JOINABLE);
+    }
     s->migration_thread_running = true;
 }
 
migration/migration.h +3 -0
index f40338cfbf..0723955cd7 100644
@@ -20,6 +20,7 @@
 #include "qemu/thread.h"
 #include "qemu/coroutine_int.h"
 #include "io/channel.h"
+#include "io/channel-buffer.h"
 #include "net/announce.h"
 #include "qom/object.h"
 
@@ -147,8 +148,10 @@ struct MigrationState {
 
     /*< public >*/
     QemuThread thread;
+    QEMUBH *vm_start_bh;
     QEMUBH *cleanup_bh;
     QEMUFile *to_dst_file;
+    QIOChannelBuffer *bioc;
     /*
      * Protects to_dst_file pointer.  We need to make sure we won't
      * yield or hang during the critical section, since this lock will
migration/savevm.c +0 -1
index 4f3b69ecfc..9f8ad5e0f5 100644
@@ -1355,7 +1355,6 @@ int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
     return 0;
 }
 
-static
 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
                                                     bool in_postcopy,
                                                     bool inactivate_disks)
migration/savevm.h +2 -0
index ba64a7e271..aaee2528ed 100644
@@ -64,5 +64,7 @@ int qemu_loadvm_state(QEMUFile *f);
 void qemu_loadvm_state_cleanup(void);
 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis);
 int qemu_load_device_state(QEMUFile *f);
+int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
+        bool in_postcopy, bool inactivate_disks);
 
 #endif
Signature · 1 line
2.25.1
#5 lore raw

Re: [PATCH v13 4/5] migration: implementation of background snapshot thread

Quoted 11 lines · * Andrey Gruzdev ([email protected]) wrote:

Introducing implementation of 'background' snapshot thread which in overall follows the logic of precopy migration while internally utilizes completely different mechanism to 'freeze' vmstate at the start of snapshot creation.

This mechanism is based on userfault_fd with wr-protection support and is Linux-specific.

Thanks for fixing the thread name; I've just noticed something though:

Quoted 20 lines
---
 migration/migration.c | 263 ++++++++++++++++++++++++++++++++++++++++--
 migration/migration.h |   3 +
 migration/savevm.c    |   1 -
 migration/savevm.h    |   2 +
 4 files changed, 258 insertions(+), 11 deletions(-)
migration/migration.c +0 -1
index f018337fbc..869afa7a86 100644
@@ -1130,7 +1130,6 @@ static void fill_source_migration_info(MigrationInfo *info)
     info->status = s->state;
 }
 
-#ifdef CONFIG_LINUX
 typedef enum WriteTrackingSupport {
     WT_SUPPORT_UNKNOWN = 0,
     WT_SUPPORT_ABSENT,

migration/migration.c WriteTrackingSupport migrate_query_write_tracking(void) · line 1158

Quoted 4 lines
migration/migration.c +0 -1
@@ -1155,7 +1154,6 @@ WriteTrackingSupport migrate_query_write_tracking(void)
 
     return WT_SUPPORT_COMPATIBLE;
 }
-#endif /* CONFIG_LINUX */

Why is this 4/5 patch removing these ifdef's (including the one below); since it's the ram_write_tracking_available that lets you know if you can do it, and htat's got ifdef's, why do these lines go in at all?

Dave

Quoted 362 lines
migration/migration.c +253 -8
 /**
  * @migration_caps_check - check capability validity
@@ -1219,7 +1217,6 @@ static bool migrate_caps_check(bool *cap_list,
     }
 
     if (cap_list[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT]) {
-#ifdef CONFIG_LINUX
         WriteTrackingSupport wt_support;
         int idx;
         /*
@@ -1250,11 +1247,6 @@ static bool migrate_caps_check(bool *cap_list,
                 return false;
             }
         }
-#else
-        error_setg(errp,
-                "Background-snapshot is not supported on non-Linux hosts");
-        return false;
-#endif
     }
 
     return true;
@@ -2016,6 +2008,7 @@ void migrate_init(MigrationState *s)
      * locks.
      */
     s->cleanup_bh = 0;
+    s->vm_start_bh = 0;
     s->to_dst_file = NULL;
     s->state = MIGRATION_STATUS_NONE;
     s->rp_state.from_dst_file = NULL;
@@ -3233,6 +3226,50 @@ fail:
                       MIGRATION_STATUS_FAILED);
 }
 
+/**
+ * bg_migration_completion: Used by bg_migration_thread when after all the
+ *   RAM has been saved. The caller 'breaks' the loop when this returns.
+ *
+ * @s: Current migration state
+ */
+static void bg_migration_completion(MigrationState *s)
+{
+    int current_active_state = s->state;
+
+    /*
+     * Stop tracking RAM writes - un-protect memory, un-register UFFD
+     * memory ranges, flush kernel wait queues and wake up threads
+     * waiting for write fault to be resolved.
+     */
+    ram_write_tracking_stop();
+
+    if (s->state == MIGRATION_STATUS_ACTIVE) {
+        /*
+         * By this moment we have RAM content saved into the migration stream.
+         * The next step is to flush the non-RAM content (device state)
+         * right after the ram content. The device state has been stored into
+         * the temporary buffer before RAM saving started.
+         */
+        qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
+        qemu_fflush(s->to_dst_file);
+    } else if (s->state == MIGRATION_STATUS_CANCELLING) {
+        goto fail;
+    }
+
+    if (qemu_file_get_error(s->to_dst_file)) {
+        trace_migration_completion_file_err();
+        goto fail;
+    }
+
+    migrate_set_state(&s->state, current_active_state,
+                      MIGRATION_STATUS_COMPLETED);
+    return;
+
+fail:
+    migrate_set_state(&s->state, current_active_state,
+                      MIGRATION_STATUS_FAILED);
+}
+
 bool migrate_colo_enabled(void)
 {
     MigrationState *s = migrate_get_current();
@@ -3573,6 +3610,47 @@ static void migration_iteration_finish(MigrationState *s)
     qemu_mutex_unlock_iothread();
 }
 
+static void bg_migration_iteration_finish(MigrationState *s)
+{
+    qemu_mutex_lock_iothread();
+    switch (s->state) {
+    case MIGRATION_STATUS_COMPLETED:
+        migration_calculate_complete(s);
+        break;
+
+    case MIGRATION_STATUS_ACTIVE:
+    case MIGRATION_STATUS_FAILED:
+    case MIGRATION_STATUS_CANCELLED:
+    case MIGRATION_STATUS_CANCELLING:
+        break;
+
+    default:
+        /* Should not reach here, but if so, forgive the VM. */
+        error_report("%s: Unknown ending state %d", __func__, s->state);
+        break;
+    }
+
+    migrate_fd_cleanup_schedule(s);
+    qemu_mutex_unlock_iothread();
+}
+
+/*
+ * Return true if continue to the next iteration directly, false
+ * otherwise.
+ */
+static MigIterateState bg_migration_iteration_run(MigrationState *s)
+{
+    int res;
+
+    res = qemu_savevm_state_iterate(s->to_dst_file, false);
+    if (res > 0) {
+        bg_migration_completion(s);
+        return MIG_ITERATE_BREAK;
+    }
+
+    return MIG_ITERATE_RESUME;
+}
+
 void migration_make_urgent_request(void)
 {
     qemu_sem_post(&migrate_get_current()->rate_limit_sem);
@@ -3720,6 +3798,165 @@ static void *migration_thread(void *opaque)
     return NULL;
 }
 
+static void bg_migration_vm_start_bh(void *opaque)
+{
+    MigrationState *s = opaque;
+
+    qemu_bh_delete(s->vm_start_bh);
+    s->vm_start_bh = NULL;
+
+    vm_start();
+    s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
+}
+
+/**
+ * Background snapshot thread, based on live migration code.
+ * This is an alternative implementation of live migration mechanism
+ * introduced specifically to support background snapshots.
+ *
+ * It takes advantage of userfault_fd write protection mechanism introduced
+ * in v5.7 kernel. Compared to existing dirty page logging migration much
+ * lesser stream traffic is produced resulting in smaller snapshot images,
+ * simply cause of no page duplicates can get into the stream.
+ *
+ * Another key point is that generated vmstate stream reflects machine state
+ * 'frozen' at the beginning of snapshot creation compared to dirty page logging
+ * mechanism, which effectively results in that saved snapshot is the state of VM
+ * at the end of the process.
+ */
+static void *bg_migration_thread(void *opaque)
+{
+    MigrationState *s = opaque;
+    int64_t setup_start;
+    MigThrError thr_error;
+    QEMUFile *fb;
+    bool early_fail = true;
+
+    rcu_register_thread();
+    object_ref(OBJECT(s));
+
+    qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
+
+    setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
+    /*
+     * We want to save vmstate for the moment when migration has been
+     * initiated but also we want to save RAM content while VM is running.
+     * The RAM content should appear first in the vmstate. So, we first
+     * stash the non-RAM part of the vmstate to the temporary buffer,
+     * then write RAM part of the vmstate to the migration stream
+     * with vCPUs running and, finally, write stashed non-RAM part of
+     * the vmstate from the buffer to the migration stream.
+     */
+    s->bioc = qio_channel_buffer_new(128 * 1024);
+    qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
+    fb = qemu_fopen_channel_output(QIO_CHANNEL(s->bioc));
+    object_unref(OBJECT(s->bioc));
+
+    update_iteration_initial_status(s);
+
+    qemu_savevm_state_header(s->to_dst_file);
+    qemu_savevm_state_setup(s->to_dst_file);
+
+    if (qemu_savevm_state_guest_unplug_pending()) {
+        migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
+                          MIGRATION_STATUS_WAIT_UNPLUG);
+
+        while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
+               qemu_savevm_state_guest_unplug_pending()) {
+            qemu_sem_timedwait(&s->wait_unplug_sem, 250);
+        }
+
+        migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG,
+                          MIGRATION_STATUS_ACTIVE);
+    } else {
+        migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
+                MIGRATION_STATUS_ACTIVE);
+    }
+    s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
+
+    trace_migration_thread_setup_complete();
+    s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
+
+    qemu_mutex_lock_iothread();
+
+    /*
+     * If VM is currently in suspended state, then, to make a valid runstate
+     * transition in vm_stop_force_state() we need to wakeup it up.
+     */
+    qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
+    s->vm_was_running = runstate_is_running();
+
+    if (global_state_store()) {
+        goto fail;
+    }
+    /* Forcibly stop VM before saving state of vCPUs and devices */
+    if (vm_stop_force_state(RUN_STATE_PAUSED)) {
+        goto fail;
+    }
+    /*
+     * Put vCPUs in sync with shadow context structures, then
+     * save their state to channel-buffer along with devices.
+     */
+    cpu_synchronize_all_states();
+    if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
+        goto fail;
+    }
+    /* Now initialize UFFD context and start tracking RAM writes */
+    if (ram_write_tracking_start()) {
+        goto fail;
+    }
+    early_fail = false;
+
+    /*
+     * Start VM from BH handler to avoid write-fault lock here.
+     * UFFD-WP protection for the whole RAM is already enabled so
+     * calling VM state change notifiers from vm_start() would initiate
+     * writes to virtio VQs memory which is in write-protected region.
+     */
+    s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
+    qemu_bh_schedule(s->vm_start_bh);
+
+    qemu_mutex_unlock_iothread();
+
+    while (migration_is_active(s)) {
+        MigIterateState iter_state = bg_migration_iteration_run(s);
+        if (iter_state == MIG_ITERATE_SKIP) {
+            continue;
+        } else if (iter_state == MIG_ITERATE_BREAK) {
+            break;
+        }
+
+        /*
+         * Try to detect any kind of failures, and see whether we
+         * should stop the migration now.
+         */
+        thr_error = migration_detect_error(s);
+        if (thr_error == MIG_THR_ERR_FATAL) {
+            /* Stop migration */
+            break;
+        }
+
+        migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
+    }
+
+    trace_migration_thread_after_loop();
+
+fail:
+    if (early_fail) {
+        migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
+                MIGRATION_STATUS_FAILED);
+        qemu_mutex_unlock_iothread();
+    }
+
+    bg_migration_iteration_finish(s);
+
+    qemu_fclose(fb);
+    object_unref(OBJECT(s));
+    rcu_unregister_thread();
+
+    return NULL;
+}
+
 void migrate_fd_connect(MigrationState *s, Error *error_in)
 {
     Error *local_err = NULL;
@@ -3783,8 +4020,14 @@ void migrate_fd_connect(MigrationState *s, Error *error_in)
         migrate_fd_cleanup(s);
         return;
     }
-    qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
-                       QEMU_THREAD_JOINABLE);
+
+    if (migrate_background_snapshot()) {
+        qemu_thread_create(&s->thread, "bg_snapshot",
+                bg_migration_thread, s, QEMU_THREAD_JOINABLE);
+    } else {
+        qemu_thread_create(&s->thread, "live_migration",
+                migration_thread, s, QEMU_THREAD_JOINABLE);
+    }
     s->migration_thread_running = true;
 }
 
migration/migration.h +3 -0
index f40338cfbf..0723955cd7 100644
@@ -20,6 +20,7 @@
 #include "qemu/thread.h"
 #include "qemu/coroutine_int.h"
 #include "io/channel.h"
+#include "io/channel-buffer.h"
 #include "net/announce.h"
 #include "qom/object.h"
 
@@ -147,8 +148,10 @@ struct MigrationState {
 
     /*< public >*/
     QemuThread thread;
+    QEMUBH *vm_start_bh;
     QEMUBH *cleanup_bh;
     QEMUFile *to_dst_file;
+    QIOChannelBuffer *bioc;
     /*
      * Protects to_dst_file pointer.  We need to make sure we won't
      * yield or hang during the critical section, since this lock will
migration/savevm.c +0 -1
index 4f3b69ecfc..9f8ad5e0f5 100644
@@ -1355,7 +1355,6 @@ int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
     return 0;
 }
 
-static
 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
                                                     bool in_postcopy,
                                                     bool inactivate_disks)
migration/savevm.h +2 -0
index ba64a7e271..aaee2528ed 100644
@@ -64,5 +64,7 @@ int qemu_loadvm_state(QEMUFile *f);
 void qemu_loadvm_state_cleanup(void);
 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis);
 int qemu_load_device_state(QEMUFile *f);
+int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
+        bool in_postcopy, bool inactivate_disks);
 
 #endif
Signature · 1 line
2.25.1
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
#6 lore raw

Re: [PATCH v13 4/5] migration: implementation of background snapshot thread

Quoted 35 lines · Dr. David Alan Gilbert
Quoted 11 lines · * Andrey Gruzdev ([email protected]) wrote:

Introducing implementation of 'background' snapshot thread which in overall follows the logic of precopy migration while internally utilizes completely different mechanism to 'freeze' vmstate at the start of snapshot creation.

This mechanism is based on userfault_fd with wr-protection support and is Linux-specific.

Thanks for fixing the thread name; I've just noticed something though:

Quoted 21 lines
---
  migration/migration.c | 263 ++++++++++++++++++++++++++++++++++++++++--
  migration/migration.h |   3 +
  migration/savevm.c    |   1 -
  migration/savevm.h    |   2 +
  4 files changed, 258 insertions(+), 11 deletions(-)
migration/migration.c +0 -1
index f018337fbc..869afa7a86 100644
@@ -1130,7 +1130,6 @@ static void fill_source_migration_info(MigrationInfo *info)
      info->status = s->state;
  }
 
-#ifdef CONFIG_LINUX
  typedef enum WriteTrackingSupport {
      WT_SUPPORT_UNKNOWN = 0,
      WT_SUPPORT_ABSENT,
@@ -1155,7 +1154,6 @@ WriteTrackingSupport migrate_query_write_tracking(void)
 
Quoted 9 lines

migration/migration.c WriteTrackingSupport migrate_query_write_tracking(void) · line 1158

Quoted 3 lines
migration/migration.c +0 -1
      return WT_SUPPORT_COMPATIBLE;
  }
-#endif /* CONFIG_LINUX */

Why is this 4/5 patch removing these ifdef's (including the one below); since it's the ram_write_tracking_available that lets you know if you can do it, and htat's got ifdef's, why do these lines go in at all?

Dave

I think I just missed to remove #ifdef's from the first patch, that's the reason. I'll fix it.

Andrey

Quoted 362 lines
Quoted 362 lines
migration/migration.c +253 -8
  /**
   * @migration_caps_check - check capability validity
@@ -1219,7 +1217,6 @@ static bool migrate_caps_check(bool *cap_list,
      }
 
      if (cap_list[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT]) {
-#ifdef CONFIG_LINUX
          WriteTrackingSupport wt_support;
          int idx;
          /*
@@ -1250,11 +1247,6 @@ static bool migrate_caps_check(bool *cap_list,
                  return false;
              }
          }
-#else
-        error_setg(errp,
-                "Background-snapshot is not supported on non-Linux hosts");
-        return false;
-#endif
      }
 
      return true;
@@ -2016,6 +2008,7 @@ void migrate_init(MigrationState *s)
       * locks.
       */
      s->cleanup_bh = 0;
+    s->vm_start_bh = 0;
      s->to_dst_file = NULL;
      s->state = MIGRATION_STATUS_NONE;
      s->rp_state.from_dst_file = NULL;
@@ -3233,6 +3226,50 @@ fail:
                        MIGRATION_STATUS_FAILED);
  }
 
+/**
+ * bg_migration_completion: Used by bg_migration_thread when after all the
+ *   RAM has been saved. The caller 'breaks' the loop when this returns.
+ *
+ * @s: Current migration state
+ */
+static void bg_migration_completion(MigrationState *s)
+{
+    int current_active_state = s->state;
+
+    /*
+     * Stop tracking RAM writes - un-protect memory, un-register UFFD
+     * memory ranges, flush kernel wait queues and wake up threads
+     * waiting for write fault to be resolved.
+     */
+    ram_write_tracking_stop();
+
+    if (s->state == MIGRATION_STATUS_ACTIVE) {
+        /*
+         * By this moment we have RAM content saved into the migration stream.
+         * The next step is to flush the non-RAM content (device state)
+         * right after the ram content. The device state has been stored into
+         * the temporary buffer before RAM saving started.
+         */
+        qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
+        qemu_fflush(s->to_dst_file);
+    } else if (s->state == MIGRATION_STATUS_CANCELLING) {
+        goto fail;
+    }
+
+    if (qemu_file_get_error(s->to_dst_file)) {
+        trace_migration_completion_file_err();
+        goto fail;
+    }
+
+    migrate_set_state(&s->state, current_active_state,
+                      MIGRATION_STATUS_COMPLETED);
+    return;
+
+fail:
+    migrate_set_state(&s->state, current_active_state,
+                      MIGRATION_STATUS_FAILED);
+}
+
  bool migrate_colo_enabled(void)
  {
      MigrationState *s = migrate_get_current();
@@ -3573,6 +3610,47 @@ static void migration_iteration_finish(MigrationState *s)
      qemu_mutex_unlock_iothread();
  }
 
+static void bg_migration_iteration_finish(MigrationState *s)
+{
+    qemu_mutex_lock_iothread();
+    switch (s->state) {
+    case MIGRATION_STATUS_COMPLETED:
+        migration_calculate_complete(s);
+        break;
+
+    case MIGRATION_STATUS_ACTIVE:
+    case MIGRATION_STATUS_FAILED:
+    case MIGRATION_STATUS_CANCELLED:
+    case MIGRATION_STATUS_CANCELLING:
+        break;
+
+    default:
+        /* Should not reach here, but if so, forgive the VM. */
+        error_report("%s: Unknown ending state %d", __func__, s->state);
+        break;
+    }
+
+    migrate_fd_cleanup_schedule(s);
+    qemu_mutex_unlock_iothread();
+}
+
+/*
+ * Return true if continue to the next iteration directly, false
+ * otherwise.
+ */
+static MigIterateState bg_migration_iteration_run(MigrationState *s)
+{
+    int res;
+
+    res = qemu_savevm_state_iterate(s->to_dst_file, false);
+    if (res > 0) {
+        bg_migration_completion(s);
+        return MIG_ITERATE_BREAK;
+    }
+
+    return MIG_ITERATE_RESUME;
+}
+
  void migration_make_urgent_request(void)
  {
      qemu_sem_post(&migrate_get_current()->rate_limit_sem);
@@ -3720,6 +3798,165 @@ static void *migration_thread(void *opaque)
      return NULL;
  }
 
+static void bg_migration_vm_start_bh(void *opaque)
+{
+    MigrationState *s = opaque;
+
+    qemu_bh_delete(s->vm_start_bh);
+    s->vm_start_bh = NULL;
+
+    vm_start();
+    s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
+}
+
+/**
+ * Background snapshot thread, based on live migration code.
+ * This is an alternative implementation of live migration mechanism
+ * introduced specifically to support background snapshots.
+ *
+ * It takes advantage of userfault_fd write protection mechanism introduced
+ * in v5.7 kernel. Compared to existing dirty page logging migration much
+ * lesser stream traffic is produced resulting in smaller snapshot images,
+ * simply cause of no page duplicates can get into the stream.
+ *
+ * Another key point is that generated vmstate stream reflects machine state
+ * 'frozen' at the beginning of snapshot creation compared to dirty page logging
+ * mechanism, which effectively results in that saved snapshot is the state of VM
+ * at the end of the process.
+ */
+static void *bg_migration_thread(void *opaque)
+{
+    MigrationState *s = opaque;
+    int64_t setup_start;
+    MigThrError thr_error;
+    QEMUFile *fb;
+    bool early_fail = true;
+
+    rcu_register_thread();
+    object_ref(OBJECT(s));
+
+    qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
+
+    setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
+    /*
+     * We want to save vmstate for the moment when migration has been
+     * initiated but also we want to save RAM content while VM is running.
+     * The RAM content should appear first in the vmstate. So, we first
+     * stash the non-RAM part of the vmstate to the temporary buffer,
+     * then write RAM part of the vmstate to the migration stream
+     * with vCPUs running and, finally, write stashed non-RAM part of
+     * the vmstate from the buffer to the migration stream.
+     */
+    s->bioc = qio_channel_buffer_new(128 * 1024);
+    qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
+    fb = qemu_fopen_channel_output(QIO_CHANNEL(s->bioc));
+    object_unref(OBJECT(s->bioc));
+
+    update_iteration_initial_status(s);
+
+    qemu_savevm_state_header(s->to_dst_file);
+    qemu_savevm_state_setup(s->to_dst_file);
+
+    if (qemu_savevm_state_guest_unplug_pending()) {
+        migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
+                          MIGRATION_STATUS_WAIT_UNPLUG);
+
+        while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
+               qemu_savevm_state_guest_unplug_pending()) {
+            qemu_sem_timedwait(&s->wait_unplug_sem, 250);
+        }
+
+        migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG,
+                          MIGRATION_STATUS_ACTIVE);
+    } else {
+        migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
+                MIGRATION_STATUS_ACTIVE);
+    }
+    s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
+
+    trace_migration_thread_setup_complete();
+    s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
+
+    qemu_mutex_lock_iothread();
+
+    /*
+     * If VM is currently in suspended state, then, to make a valid runstate
+     * transition in vm_stop_force_state() we need to wakeup it up.
+     */
+    qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
+    s->vm_was_running = runstate_is_running();
+
+    if (global_state_store()) {
+        goto fail;
+    }
+    /* Forcibly stop VM before saving state of vCPUs and devices */
+    if (vm_stop_force_state(RUN_STATE_PAUSED)) {
+        goto fail;
+    }
+    /*
+     * Put vCPUs in sync with shadow context structures, then
+     * save their state to channel-buffer along with devices.
+     */
+    cpu_synchronize_all_states();
+    if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
+        goto fail;
+    }
+    /* Now initialize UFFD context and start tracking RAM writes */
+    if (ram_write_tracking_start()) {
+        goto fail;
+    }
+    early_fail = false;
+
+    /*
+     * Start VM from BH handler to avoid write-fault lock here.
+     * UFFD-WP protection for the whole RAM is already enabled so
+     * calling VM state change notifiers from vm_start() would initiate
+     * writes to virtio VQs memory which is in write-protected region.
+     */
+    s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
+    qemu_bh_schedule(s->vm_start_bh);
+
+    qemu_mutex_unlock_iothread();
+
+    while (migration_is_active(s)) {
+        MigIterateState iter_state = bg_migration_iteration_run(s);
+        if (iter_state == MIG_ITERATE_SKIP) {
+            continue;
+        } else if (iter_state == MIG_ITERATE_BREAK) {
+            break;
+        }
+
+        /*
+         * Try to detect any kind of failures, and see whether we
+         * should stop the migration now.
+         */
+        thr_error = migration_detect_error(s);
+        if (thr_error == MIG_THR_ERR_FATAL) {
+            /* Stop migration */
+            break;
+        }
+
+        migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
+    }
+
+    trace_migration_thread_after_loop();
+
+fail:
+    if (early_fail) {
+        migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
+                MIGRATION_STATUS_FAILED);
+        qemu_mutex_unlock_iothread();
+    }
+
+    bg_migration_iteration_finish(s);
+
+    qemu_fclose(fb);
+    object_unref(OBJECT(s));
+    rcu_unregister_thread();
+
+    return NULL;
+}
+
  void migrate_fd_connect(MigrationState *s, Error *error_in)
  {
      Error *local_err = NULL;
@@ -3783,8 +4020,14 @@ void migrate_fd_connect(MigrationState *s, Error *error_in)
          migrate_fd_cleanup(s);
          return;
      }
-    qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
-                       QEMU_THREAD_JOINABLE);
+
+    if (migrate_background_snapshot()) {
+        qemu_thread_create(&s->thread, "bg_snapshot",
+                bg_migration_thread, s, QEMU_THREAD_JOINABLE);
+    } else {
+        qemu_thread_create(&s->thread, "live_migration",
+                migration_thread, s, QEMU_THREAD_JOINABLE);
+    }
      s->migration_thread_running = true;
  }
 
migration/migration.h +3 -0
index f40338cfbf..0723955cd7 100644
@@ -20,6 +20,7 @@
  #include "qemu/thread.h"
  #include "qemu/coroutine_int.h"
  #include "io/channel.h"
+#include "io/channel-buffer.h"
  #include "net/announce.h"
  #include "qom/object.h"
 
@@ -147,8 +148,10 @@ struct MigrationState {
 
      /*< public >*/
      QemuThread thread;
+    QEMUBH *vm_start_bh;
      QEMUBH *cleanup_bh;
      QEMUFile *to_dst_file;
+    QIOChannelBuffer *bioc;
      /*
       * Protects to_dst_file pointer.  We need to make sure we won't
       * yield or hang during the critical section, since this lock will
migration/savevm.c +0 -1
index 4f3b69ecfc..9f8ad5e0f5 100644
@@ -1355,7 +1355,6 @@ int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
      return 0;
  }
 
-static
  int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
                                                      bool in_postcopy,
                                                      bool inactivate_disks)
migration/savevm.h +2 -0
index ba64a7e271..aaee2528ed 100644
@@ -64,5 +64,7 @@ int qemu_loadvm_state(QEMUFile *f);
  void qemu_loadvm_state_cleanup(void);
  int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis);
  int qemu_load_device_state(QEMUFile *f);
+int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
+        bool in_postcopy, bool inactivate_disks);
 
  #endif
Signature · 1 line
2.25.1
Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#7 lore raw

PATCH v13 5/5 migration: introduce 'userfaultfd-wrlat.py' script

In reply to andrey.gruzdev--- via

Add BCC/eBPF script to analyze userfaultfd write fault latency distribution.

---
 scripts/userfaultfd-wrlat.py | 122 +++++++++++++++++++++++++++++++++++
 1 file changed, 122 insertions(+)
 create mode 100755 scripts/userfaultfd-wrlat.py
scripts/userfaultfd-wrlat.py new file +122 -0
new file mode 100755
index 0000000000..0684be4e04
@@ -0,0 +1,122 @@
+#!/usr/bin/python3
+#
+# userfaultfd-wrlat Summarize userfaultfd write fault latencies.
+#                   Events are continuously accumulated for the
+#                   run, while latency distribution histogram is
+#                   dumped each 'interval' seconds.
+#
+#                   For Linux, uses BCC, eBPF.
+#
+# USAGE: userfaultfd-lat [interval [count]]
+#
+# Copyright Virtuozzo GmbH, 2020
+#
+# Authors:
+#   Andrey Gruzdev   <[email protected]>
+#
+# This work is licensed under the terms of the GNU GPL, version 2 or
+# later.  See the COPYING file in the top-level directory.
+
+from __future__ import print_function
+from bcc import BPF
+from ctypes import c_ushort, c_int, c_ulonglong
+from time import sleep
+from sys import argv
+
+def usage():
+    print("USAGE: %s [interval [count]]" % argv[0])
+    exit()
+
+# define BPF program
+bpf_text = """
+#include <uapi/linux/ptrace.h>
+#include <linux/mm.h>
+
+BPF_HASH(ev_start, u32, u64);
+BPF_HISTOGRAM(ev_delta_hist, u64);
+
+/* Trace UFFD page fault start event. */
+static void do_event_start()
+{
+    /* Using "(u32)" to drop group ID which is upper 32 bits */
+    u32 tid = (u32) bpf_get_current_pid_tgid();
+    u64 ts = bpf_ktime_get_ns();
+
+    ev_start.update(&tid, &ts);
+}
+
+/* Trace UFFD page fault end event. */
+static void do_event_end()
+{
+    /* Using "(u32)" to drop group ID which is upper 32 bits */
+    u32 tid = (u32) bpf_get_current_pid_tgid();
+    u64 ts = bpf_ktime_get_ns();
+    u64 *tsp;
+
+    tsp = ev_start.lookup(&tid);
+    if (tsp) {
+        u64 delta = ts - (*tsp);
+        /* Transform time delta to milliseconds */
+        ev_delta_hist.increment(bpf_log2l(delta / 1000000));
+        ev_start.delete(&tid);
+    }
+}
+
+/* KPROBE for handle_userfault(). */
+int probe_handle_userfault(struct pt_regs *ctx, struct vm_fault *vmf,
+        unsigned long reason)
+{
+    /* Trace only UFFD write faults. */
+    if (reason & VM_UFFD_WP) {
+        do_event_start();
+    }
+    return 0;
+}
+
+/* KRETPROBE for handle_userfault(). */
+int retprobe_handle_userfault(struct pt_regs *ctx)
+{
+    do_event_end();
+    return 0;
+}
+"""
+
+# arguments
+interval = 10
+count = -1
+if len(argv) > 1:
+    try:
+        interval = int(argv[1])
+        if interval == 0:
+            raise
+        if len(argv) > 2:
+            count = int(argv[2])
+    except:    # also catches -h, --help
+        usage()
+
+# load BPF program
+b = BPF(text=bpf_text)
+# attach KRPOBEs
+b.attach_kprobe(event="handle_userfault", fn_name="probe_handle_userfault")
+b.attach_kretprobe(event="handle_userfault", fn_name="retprobe_handle_userfault")
+
+# header
+print("Tracing UFFD-WP write fault latency... Hit Ctrl-C to end.")
+
+# output
+loop = 0
+do_exit = 0
+while (1):
+    if count > 0:
+        loop += 1
+        if loop > count:
+            exit()
+    try:
+        sleep(interval)
+    except KeyboardInterrupt:
+        pass; do_exit = 1
+
+    print()
+    b["ev_delta_hist"].print_log2_hist("msecs")
+    if do_exit:
+        exit()
Signature · 1 line
2.25.1
#8 lore raw
In reply to andrey.gruzdev--- via
Quoted 12 lines · andrey.gruzdev--- via

This patch series is a kind of 'rethinking' of Denis Plotnikov's ideas he's implemented in his series '[PATCH v0 0/4] migration: add background snapshot'.

Currently the only way to make (external) live VM snapshot is using existing dirty page logging migration mechanism. The main problem is that it tends to produce a lot of page duplicates while running VM goes on updating already saved pages. That leads to the fact that vmstate image size is commonly several times bigger then non-zero part of virtual machine's RSS. Time required to converge RAM migration and the size of snapshot image severely depend on the guest memory write rate, sometimes resulting in unacceptably long snapshot creation time and huge image size.

Quoted 8 lines

This series propose a way to solve the aforementioned problems. This is done by using different RAM migration mechanism based on UFFD write protection management introduced in v5.7 kernel. The migration strategy is to 'freeze' guest RAM content using write-protection and iteratively release protection for memory ranges that have already been saved to the migration stream. At the same time we read in pending UFFD write fault events and save those pages out-of-order with higher priority.

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW: !pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

How are you handling that scenario, or why don't you have to handle that scenario?

Signature · 3 lines
Thanks,

David / dhildenb
#9 lore raw
Quoted 28 lines · David Hildenbrand
Quoted 12 lines · andrey.gruzdev--- via

This patch series is a kind of 'rethinking' of Denis Plotnikov's ideas he's implemented in his series '[PATCH v0 0/4] migration: add background snapshot'.

Currently the only way to make (external) live VM snapshot is using existing dirty page logging migration mechanism. The main problem is that it tends to produce a lot of page duplicates while running VM goes on updating already saved pages. That leads to the fact that vmstate image size is commonly several times bigger then non-zero part of virtual machine's RSS. Time required to converge RAM migration and the size of snapshot image severely depend on the guest memory write rate, sometimes resulting in unacceptably long snapshot creation time and huge image size.

Quoted 8 lines

This series propose a way to solve the aforementioned problems. This is done by using different RAM migration mechanism based on UFFD write protection management introduced in v5.7 kernel. The migration strategy is to 'freeze' guest RAM content using write-protection and iteratively release protection for memory ranges that have already been saved to the migration stream. At the same time we read in pending UFFD write fault events and save those pages out-of-order with higher priority.

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW: !pte_none() in the kernel).

Quoted 8 lines

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

How are you handling that scenario, or why don't you have to handle that scenario?

Hi David,

I really wonder if such a problem exists.. If we are talking about a write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma. For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#10 lore raw
Quoted 18 lines
Quoted 18 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

Quoted 6 lines
Quoted 3 lines

How are you handling that scenario, or why don't you have to handle that scenario?

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 4 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma. For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

See the attached test program. Triggers for me on 5.11.0-rc6+ and 5.9.13-200.fc33

gcc -lpthread uffdio_wp.c -o uffdio_wp
./uffdio_wp
WP did not fire

Uncomment the placement of the zeropage just before registering to make the WP actually trigger. If there is no PTE, there is nothing to protect.

And it makes sense: How should the fault handler know which ranges you wp-ed, if there is no place to store that information (the PTEs!). The VMA cannot tell that story, it only knows that someone registered UFFD_WP to selectively wp some parts.

You might have to register also for MISSING faults and place zero pages.

Signature · 3 lines
Thanks,

David / dhildenb

#include <string.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <poll.h>
#include <linux/userfaultfd.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/ioctl.h>

static int page_size;
volatile bool wp_fired;

static void *fault_handler_thread(void *arg)

{
    const long uffd = (long) arg;
    struct pollfd pollfd = {
        .fd = uffd,
        .events = POLLIN,
    };
    int ret;

    while (true) {
        struct uffdio_writeprotect wp;
        struct uffd_msg msg;
        ssize_t nread;

        if (poll(&pollfd, 1, -1) == -1) {
            fprintf(stderr, "POLL failed: %s\n", strerror(errno));
            exit(-1);
        }
        if (read(uffd, &msg, sizeof(msg)) != sizeof(msg)) {
            fprintf(stderr, "READ failed\n");
            exit(-1);
        }
        if (msg.event == UFFD_EVENT_REMOVE) {
            continue;
        }
        if (msg.event != UFFD_EVENT_PAGEFAULT) {
            fprintf(stderr, "Not UFFD_EVENT_PAGEFAULT\n");
            exit(-1);
        }

        wp_fired = true;

        /* Simply unprotect and wake */
        wp.range.start = msg.arg.pagefault.address;
        wp.range.len = page_size;
        wp.mode = 0;
        if (ioctl(uffd, UFFDIO_WRITEPROTECT, &wp) == -1) {
            fprintf(stderr, "UFFDIO_WRITEPROTECT failed: %s\n", strerror(errno));
            exit(-1);
        }
    }
}

int main(void)

{
    struct uffdio_writeprotect wp;
    struct uffdio_zeropage zeropage;
    struct uffdio_register reg;
    struct uffdio_api api = {
        .api = UFFD_API,
        .features = UFFD_FEATURE_EVENT_REMOVE,
    };
    pthread_t fault, discard;
    long uffd;
    char *area;

    page_size = sysconf(_SC_PAGE_SIZE);

    uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
    if (uffd == -1) {
        fprintf(stderr, "Could not create uffd: %s\n", strerror(errno));
        exit(-1);
    }
    if (ioctl(uffd, UFFDIO_API, &api) == -1) {
        fprintf(stderr, "UFFDIO_API failed: %s\n", strerror(errno));
        exit(-1);
    }

    area = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
                MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (area == MAP_FAILED) {
        fprintf(stderr, "Could not allocate memory");
        exit(-1);
    }

    /* make sure the area is empty */
    if (madvise(area, page_size, MADV_DONTNEED)) {
        fprintf(stderr, "MADV_DONTNEED failed:%s\n", strerror(errno));
        exit(-1);
    }

    /* register a WP handler */
    reg.range.start = (uint64_t) area;
    reg.range.len = page_size,
    reg.mode = UFFDIO_REGISTER_MODE_WP;
    if (ioctl(uffd, UFFDIO_REGISTER, &reg) == -1) {
        fprintf(stderr, "UFFDIO_REGISTER failed: %s\n", strerror(errno));
        exit(-1);
    }

    /*
     * comment this out to make the wp actually fire
    zeropage.range = reg.range;
    zeropage.mode = UFFDIO_ZEROPAGE_MODE_DONTWAKE;
    if (ioctl(uffd, UFFDIO_ZEROPAGE, &zeropage) == -1) {
        fprintf(stderr, "UFFDIO_ZEROPAGE failed: %s\n", strerror(errno));
        exit(-1);
    }
    */

    /* protect the page */
    wp.range = reg.range;
    wp.mode = UFFDIO_WRITEPROTECT_MODE_WP;
    if (ioctl(uffd, UFFDIO_WRITEPROTECT, &wp) == -1) {
        fprintf(stderr, "UFFDIO_WRITEPROTECT failed: %s\n", strerror(errno));
        exit(-1);
    }

    if (pthread_create(&fault, NULL, fault_handler_thread,
                       (void *) uffd)) {
        fprintf(stderr, "Could not create fault handing thread");
        exit(-1);
    }

    *area = 0;
    if (wp_fired) {
        printf("WP fired\n");
        return 0;
    }
    printf("WP did not fire\n");
    return -1;
}
#11 lore raw

Hi, David, Andrey,

Quoted 12 lines · David Hildenbrand
Quoted 12 lines
Quoted 12 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

How are you handling that scenario, or why don't you have to handle that scenario?

Good catch.. Indeed I overlooked that as well when reviewing the code.

Quoted 11 lines
Quoted 4 lines
Quoted 1 line

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 4 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma. For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

The problem is even if the page is read-only, it does not yet have the uffd-wp bit set, so it won't really trigger the handle_userfault() path.

Quoted 1 line

You might have to register also for MISSING faults and place zero pages.

So I think what's missing for live snapshot is indeed to register with both missing & wp mode.

Then we'll receive two messages: For wp, we do like before. For missing, we do UFFDIO_ZEROCOPY and at the same time dump this page as a zero page.

I bet live snapshot didn't encounter this issue simply because normal live snapshots would still work, especially when there's the guest OS. Say, the worst case is we could have migrated some zero pages with some random data filled in along with the snapshot, however all these pages were zero pages and not used by the guest OS after all, then when we load a snapshot we won't easily notice either..

Thanks,

Signature · 1 line
Peter Xu
#12 lore raw
Quoted 49 lines · Peter Xu

Hi, David, Andrey,

Quoted 12 lines · David Hildenbrand
Quoted 12 lines
Quoted 12 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

How are you handling that scenario, or why don't you have to handle that scenario?

Good catch.. Indeed I overlooked that as well when reviewing the code.

Quoted 11 lines
Quoted 4 lines
Quoted 1 line

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 4 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma. For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

The problem is even if the page is read-only, it does not yet have the uffd-wp bit set, so it won't really trigger the handle_userfault() path.

Quoted 1 line

You might have to register also for MISSING faults and place zero pages.

So I think what's missing for live snapshot is indeed to register with both missing & wp mode.

Then we'll receive two messages: For wp, we do like before. For missing, we do UFFDIO_ZEROCOPY and at the same time dump this page as a zero page.

Quoted 6 lines

I bet live snapshot didn't encounter this issue simply because normal live snapshots would still work, especially when there's the guest OS. Say, the worst case is we could have migrated some zero pages with some random data filled in along with the snapshot, however all these pages were zero pages and not used by the guest OS after all, then when we load a snapshot we won't easily notice either..

I'm thinking some way to verify this from live snapshot pov, and I've got an idea so I just share it out... Maybe we need a guest application that does something like below:

- mmap() a huge lot of memory

- call mlockall(), so that pages will be provisioned in the guest but without data written. IIUC on the host these pages should be backed by missing pages as long as guest app doesn't write. Then...

- the app starts to read input from user:

- If user inputs "dirty" and enter: it'll start to dirty the whole range. Write non-zero to the 1st byte of each page would suffice.

- If user inputs "check" and enter: it'll read the whole memory chunk to see whether all the pages are zero pages. If it reads any non-zero page, it should bail out and print error.

With the help of above program, we can do below to verify the live snapshot worked as expected on zero pages:

- Guest: start above program, don't input yet (so waiting to read either "dirty" or "check" command)

- Host: start live snapshot

- Guest: input "dirty" command, so start quickly dirtying the ram

- Host: live snapshot completes

Then to verify the snapshot image, we do:

- Host: load the snapshot we've got

- Guest: (should still be in the state of waiting for cmd) this time we enter

    "check"

Thanks,

Signature · 1 line
Peter Xu
#13 lore raw
Quoted 82 lines · Peter Xu
Quoted 44 lines · Peter Xu

Hi, David, Andrey,

Quoted 12 lines · David Hildenbrand
Quoted 12 lines
Quoted 12 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

How are you handling that scenario, or why don't you have to handle that scenario?

Good catch.. Indeed I overlooked that as well when reviewing the code.

Quoted 9 lines
Quoted 3 lines

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 4 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma. For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

The problem is even if the page is read-only, it does not yet have the uffd-wp bit set, so it won't really trigger the handle_userfault() path.

Quoted 1 line

You might have to register also for MISSING faults and place zero pages.

So I think what's missing for live snapshot is indeed to register with both missing & wp mode.

Then we'll receive two messages: For wp, we do like before. For missing, we do UFFDIO_ZEROCOPY and at the same time dump this page as a zero page.

Quoted 6 lines

I bet live snapshot didn't encounter this issue simply because normal live snapshots would still work, especially when there's the guest OS. Say, the worst case is we could have migrated some zero pages with some random data filled in along with the snapshot, however all these pages were zero pages and not used by the guest OS after all, then when we load a snapshot we won't easily notice either..

I'm thinking some way to verify this from live snapshot pov, and I've got an idea so I just share it out... Maybe we need a guest application that does something like below:

- mmap() a huge lot of memory

- call mlockall(), so that pages will be provisioned in the guest but without data written. IIUC on the host these pages should be backed by missing pages as long as guest app doesn't write. Then...

- the app starts to read input from user:

- If user inputs "dirty" and enter: it'll start to dirty the whole range. Write non-zero to the 1st byte of each page would suffice.

- If user inputs "check" and enter: it'll read the whole memory chunk to see whether all the pages are zero pages. If it reads any non-zero page, it should bail out and print error.

With the help of above program, we can do below to verify the live snapshot worked as expected on zero pages:

- Guest: start above program, don't input yet (so waiting to read either "dirty" or "check" command)

- Host: start live snapshot

- Guest: input "dirty" command, so start quickly dirtying the ram

- Host: live snapshot completes

Quoted 9 lines

Then to verify the snapshot image, we do:

- Host: load the snapshot we've got

- Guest: (should still be in the state of waiting for cmd) this time we enter

     "check"

Thanks,

Hi David, Peter,

A little unexpected behavior, from my point of view, for UFFD write-protection. So, that means that UFFD_WP protection/events works only for locked memory? I'm now looking at kernel implementation, to understand..

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#14 lore raw
Quoted 90 lines · Andrey Gruzdev
Quoted 89 lines · Peter Xu
Quoted 44 lines · Peter Xu

Hi, David, Andrey,

Quoted 12 lines · David Hildenbrand
Quoted 12 lines
Quoted 12 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

How are you handling that scenario, or why don't you have to handle that scenario?

Good catch.. Indeed I overlooked that as well when reviewing the code.

Quoted 9 lines
Quoted 3 lines

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 4 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma. For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

The problem is even if the page is read-only, it does not yet have the uffd-wp bit set, so it won't really trigger the handle_userfault() path.

Quoted 1 line

You might have to register also for MISSING faults and place zero pages.

So I think what's missing for live snapshot is indeed to register with both missing & wp mode.

Then we'll receive two messages: For wp, we do like before. For missing, we do UFFDIO_ZEROCOPY and at the same time dump this page as a zero page.

Quoted 6 lines

I bet live snapshot didn't encounter this issue simply because normal live snapshots would still work, especially when there's the guest OS. Say, the worst case is we could have migrated some zero pages with some random data filled in along with the snapshot, however all these pages were zero pages and not used by the guest OS after all, then when we load a snapshot we won't easily notice either..

I'm thinking some way to verify this from live snapshot pov, and I've got an idea so I just share it out... Maybe we need a guest application that does something like below:

- mmap() a huge lot of memory

- call mlockall(), so that pages will be provisioned in the guest but without data written. IIUC on the host these pages should be backed by missing pages as long as guest app doesn't write. Then...

- the app starts to read input from user:

- If user inputs "dirty" and enter: it'll start to dirty the whole range. Write non-zero to the 1st byte of each page would suffice.

- If user inputs "check" and enter: it'll read the whole memory chunk to see whether all the pages are zero pages. If it reads any non-zero page, it should bail out and print error.

With the help of above program, we can do below to verify the live snapshot worked as expected on zero pages:

- Guest: start above program, don't input yet (so waiting to read either "dirty" or "check" command)

- Host: start live snapshot

- Guest: input "dirty" command, so start quickly dirtying the ram

- Host: live snapshot completes

Then to verify the snapshot image, we do:

- Host: load the snapshot we've got

- Guest: (should still be in the state of waiting for cmd) this time we enter

     "check"
Quoted 7 lines
Quoted 2 lines

Thanks,

Hi David, Peter,

A little unexpected behavior, from my point of view, for UFFD write-protection. So, that means that UFFD_WP protection/events works only for locked memory? I'm now looking at kernel implementation, to understand..

Not really; it definitely works for all memories that we've touched. My previous exmaple wanted to let the guest app use a not-yet-allocated page. I figured mlockall() might achieve that, hence I proposed such an example assuming that may verify the zero page issue on live snapshot. So if my understanding is correct, if we run above scenario, current live snapshot might fail that app when we do the "check" command at last, by finding non-zero pages.

Thanks,

Signature · 1 line
Peter Xu
#15 lore raw
Quoted 98 lines · Peter Xu
Quoted 90 lines · Andrey Gruzdev
Quoted 89 lines · Peter Xu
Quoted 44 lines · Peter Xu

Hi, David, Andrey,

Quoted 12 lines · David Hildenbrand
Quoted 12 lines
Quoted 12 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

How are you handling that scenario, or why don't you have to handle that scenario?

Good catch.. Indeed I overlooked that as well when reviewing the code.

Quoted 9 lines
Quoted 3 lines

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 4 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma. For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

The problem is even if the page is read-only, it does not yet have the uffd-wp bit set, so it won't really trigger the handle_userfault() path.

Quoted 1 line

You might have to register also for MISSING faults and place zero pages.

So I think what's missing for live snapshot is indeed to register with both missing & wp mode.

Then we'll receive two messages: For wp, we do like before. For missing, we do UFFDIO_ZEROCOPY and at the same time dump this page as a zero page.

Quoted 6 lines

I bet live snapshot didn't encounter this issue simply because normal live snapshots would still work, especially when there's the guest OS. Say, the worst case is we could have migrated some zero pages with some random data filled in along with the snapshot, however all these pages were zero pages and not used by the guest OS after all, then when we load a snapshot we won't easily notice either..

I'm thinking some way to verify this from live snapshot pov, and I've got an idea so I just share it out... Maybe we need a guest application that does something like below:

- mmap() a huge lot of memory

- call mlockall(), so that pages will be provisioned in the guest but without data written. IIUC on the host these pages should be backed by missing pages as long as guest app doesn't write. Then...

- the app starts to read input from user:

- If user inputs "dirty" and enter: it'll start to dirty the whole range. Write non-zero to the 1st byte of each page would suffice.

- If user inputs "check" and enter: it'll read the whole memory chunk to see whether all the pages are zero pages. If it reads any non-zero page, it should bail out and print error.

With the help of above program, we can do below to verify the live snapshot worked as expected on zero pages:

- Guest: start above program, don't input yet (so waiting to read either "dirty" or "check" command)

- Host: start live snapshot

- Guest: input "dirty" command, so start quickly dirtying the ram

- Host: live snapshot completes

Then to verify the snapshot image, we do:

- Host: load the snapshot we've got

- Guest: (should still be in the state of waiting for cmd) this time we enter "check"

Quoted 7 lines
Quoted 2 lines

Thanks,

Hi David, Peter,

A little unexpected behavior, from my point of view, for UFFD write-protection. So, that means that UFFD_WP protection/events works only for locked memory? I'm now looking at kernel implementation, to understand..

Quoted 9 lines

Not really; it definitely works for all memories that we've touched. My previous exmaple wanted to let the guest app use a not-yet-allocated page. I figured mlockall() might achieve that, hence I proposed such an example assuming that may verify the zero page issue on live snapshot. So if my understanding is correct, if we run above scenario, current live snapshot might fail that app when we do the "check" command at last, by finding non-zero pages.

Thanks,

Yes, I understand the limitations with vma's which lead to the fact we can write-protect with PTE softbits only. I think mlockall() is not required, just need mmap() with MAP_POPULATE. Since the problem is related only to pte_none() entries.

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#16 lore raw
In reply to David Hildenbrand
Quoted 38 lines · David Hildenbrand
Quoted 18 lines
Quoted 18 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

Quoted 6 lines
Quoted 3 lines

How are you handling that scenario, or why don't you have to handle that scenario?

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 4 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma. For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

See the attached test program. Triggers for me on 5.11.0-rc6+ and 5.9.13-200.fc33

gcc -lpthread uffdio_wp.c -o uffdio_wp
./uffdio_wp
WP did not fire

Quoted 7 lines

Uncomment the placement of the zeropage just before registering to make the WP actually trigger. If there is no PTE, there is nothing to protect.

And it makes sense: How should the fault handler know which ranges you wp-ed, if there is no place to store that information (the PTEs!). The VMA cannot tell that story, it only knows that someone registered UFFD_WP to selectively wp some parts.

You might have to register also for MISSING faults and place zero pages.

Looked at the kernel code, agree that we miss WP events for unpopulated pages, UFFD_WP softbit won't be set in this case. But it doesn't make saved snapshot inconsistent or introduce security issues. The only side effect is that we may save updated page instead of zeroed, just increasing snapshot size. However this guest-physical page has never been touched from the point of view of saved vCPU/device state and is not a concern.

Often (at least on desktop Windows guests) only a small part of RAM has ever been allocated by guest. Migration code needs to read each guest-physical page, so we'll have a lot of additional UFFD events, much more MISSING events then WP-faults.

And the main problem is that adding MISSING handler is impossible in current single-threaded snapshot code. We'll get an immediate deadlock on iterative page read.

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#17 lore raw
Quoted 52 lines · Andrey Gruzdev
Quoted 51 lines · David Hildenbrand
Quoted 18 lines
Quoted 18 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

Quoted 6 lines
Quoted 3 lines

How are you handling that scenario, or why don't you have to handle that scenario?

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 6 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma.
For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

See the attached test program. Triggers for me on 5.11.0-rc6+ and 5.9.13-200.fc33

gcc -lpthread uffdio_wp.c -o uffdio_wp
./uffdio_wp
WP did not fire

Uncomment the placement of the zeropage just before registering to make the WP actually trigger. If there is no PTE, there is nothing to protect.

And it makes sense: How should the fault handler know which ranges you wp-ed, if there is no place to store that information (the PTEs!). The VMA cannot tell that story, it only knows that someone registered UFFD_WP to selectively wp some parts.

Quoted 8 lines
Quoted 2 lines

You might have to register also for MISSING faults and place zero pages.

Looked at the kernel code, agree that we miss WP events for unpopulated pages, UFFD_WP softbit won't be set in this case. But it doesn't make saved snapshot inconsistent or introduce security issues. The only side effect is that we may save updated page instead of zeroed, just increasing snapshot size. However this guest-physical page has never been touched from the point of view of saved vCPU/device state and is not a concern.

Oh I just remembered one thing, that Linux should be zeroing pages when allocating, so even if the page has legacy content it'll be cleared with __GFP_ZERO allocations. So yeah it would be harder to have issue at least with a sensible OS. I'm not sure about Windows or others, but it could be a common case. Then the only overhead is the extra pages we kept in the live snapshot, which takes some more disk space.

Or there could be firmware running without OS at all, but it should really not read unallocated pages assuming there must be zero. It's not a sane behavior even for a firmware.

Quoted 9 lines

Often (at least on desktop Windows guests) only a small part of RAM has ever been allocated by guest. Migration code needs to read each guest-physical page, so we'll have a lot of additional UFFD events, much more MISSING events then WP-faults.

And the main problem is that adding MISSING handler is impossible in current single-threaded snapshot code. We'll get an immediate deadlock on iterative page read.

Right. We'll need to rework the design but just for saving a bunch of snapshot image disk size. So now I agree with you, let's keep this in mind, but maybe it isn't worth a fix for now, at least until we figure something really broken.

Andrey, do you think we should still mention this issue into the todo list of the wiki page of live snapshot?

Thanks,

Signature · 1 line
Peter Xu
#18 lore raw
Quoted 78 lines · Peter Xu
Quoted 50 lines · Andrey Gruzdev
Quoted 49 lines · David Hildenbrand
Quoted 18 lines
Quoted 18 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

Quoted 6 lines
Quoted 3 lines

How are you handling that scenario, or why don't you have to handle that scenario?

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 6 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma.
For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

See the attached test program. Triggers for me on 5.11.0-rc6+ and 5.9.13-200.fc33

gcc -lpthread uffdio_wp.c -o uffdio_wp
./uffdio_wp
WP did not fire

Uncomment the placement of the zeropage just before registering to make the WP actually trigger. If there is no PTE, there is nothing to protect.

And it makes sense: How should the fault handler know which ranges you wp-ed, if there is no place to store that information (the PTEs!). The VMA cannot tell that story, it only knows that someone registered UFFD_WP to selectively wp some parts.

Quoted 8 lines
Quoted 2 lines

You might have to register also for MISSING faults and place zero pages.

Looked at the kernel code, agree that we miss WP events for unpopulated pages, UFFD_WP softbit won't be set in this case. But it doesn't make saved snapshot inconsistent or introduce security issues. The only side effect is that we may save updated page instead of zeroed, just increasing snapshot size. However this guest-physical page has never been touched from the point of view of saved vCPU/device state and is not a concern.

Oh I just remembered one thing, that Linux should be zeroing pages when allocating, so even if the page has legacy content it'll be cleared with __GFP_ZERO allocations. So yeah it would be harder to have issue at least with a sensible OS. I'm not sure about Windows or others, but it could be a common case. Then the only overhead is the extra pages we kept in the live snapshot, which takes some more disk space.

Or there could be firmware running without OS at all, but it should really not read unallocated pages assuming there must be zero. It's not a sane behavior even for a firmware.

Quoted 8 lines

Often (at least on desktop Windows guests) only a small part of RAM has ever been allocated by guest. Migration code needs to read each guest-physical page, so we'll have a lot of additional UFFD events, much more MISSING events then WP-faults.

And the main problem is that adding MISSING handler is impossible in current single-threaded snapshot code. We'll get an immediate deadlock on iterative page read.

Quoted 9 lines

Right. We'll need to rework the design but just for saving a bunch of snapshot image disk size. So now I agree with you, let's keep this in mind, but maybe it isn't worth a fix for now, at least until we figure something really broken.

Andrey, do you think we should still mention this issue into the todo list of the wiki page of live snapshot?

Thanks,

Yes, even if the page happens to be overwritten, it's overwritten by the same VM so no security boundaries are crossed. And no machine code can assume that RAM content is zeroed on power-on or reset so our snapshot state stays quite consistent.

Agree we should keep it in mind, but IMHO adding MISSING handler and running separate thread would make performance worse.. So I doubt it's worth adding this to TODO list..

Thanks,

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#19 lore raw
Quoted 86 lines · Andrey Gruzdev
Quoted 85 lines · Peter Xu
Quoted 50 lines · Andrey Gruzdev
Quoted 49 lines · David Hildenbrand
Quoted 18 lines
Quoted 18 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

Quoted 6 lines
Quoted 3 lines

How are you handling that scenario, or why don't you have to handle that scenario?

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 6 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma.
For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

See the attached test program. Triggers for me on 5.11.0-rc6+ and 5.9.13-200.fc33

gcc -lpthread uffdio_wp.c -o uffdio_wp
./uffdio_wp
WP did not fire

Uncomment the placement of the zeropage just before registering to make the WP actually trigger. If there is no PTE, there is nothing to protect.

And it makes sense: How should the fault handler know which ranges you wp-ed, if there is no place to store that information (the PTEs!). The VMA cannot tell that story, it only knows that someone registered UFFD_WP to selectively wp some parts.

Quoted 8 lines
Quoted 2 lines

You might have to register also for MISSING faults and place zero pages.

Looked at the kernel code, agree that we miss WP events for unpopulated pages, UFFD_WP softbit won't be set in this case. But it doesn't make saved snapshot inconsistent or introduce security issues. The only side effect is that we may save updated page instead of zeroed, just increasing snapshot size. However this guest-physical page has never been touched from the point of view of saved vCPU/device state and is not a concern.

Oh I just remembered one thing, that Linux should be zeroing pages when allocating, so even if the page has legacy content it'll be cleared with __GFP_ZERO allocations. So yeah it would be harder to have issue at least with a sensible OS. I'm not sure about Windows or others, but it could be a common case. Then the only overhead is the extra pages we kept in the live snapshot, which takes some more disk space.

Or there could be firmware running without OS at all, but it should really not read unallocated pages assuming there must be zero. It's not a sane behavior even for a firmware.

Quoted 8 lines

Often (at least on desktop Windows guests) only a small part of RAM has ever been allocated by guest. Migration code needs to read each guest-physical page, so we'll have a lot of additional UFFD events, much more MISSING events then WP-faults.

And the main problem is that adding MISSING handler is impossible in current single-threaded snapshot code. We'll get an immediate deadlock on iterative page read.

Right. We'll need to rework the design but just for saving a bunch of snapshot image disk size. So now I agree with you, let's keep this in mind, but maybe it isn't worth a fix for now, at least until we figure something really broken.

Andrey, do you think we should still mention this issue into the todo list of the wiki page of live snapshot?

Quoted 9 lines
Quoted 2 lines

Thanks,

Yes, even if the page happens to be overwritten, it's overwritten by the same VM so no security boundaries are crossed. And no machine code can assume that RAM content is zeroed on power-on or reset so our snapshot state stays quite consistent.

Agree we should keep it in mind, but IMHO adding MISSING handler and running separate thread would make performance worse.. So I doubt it's worth adding this to TODO list..

So, here is what happens: your snapshot will contain garbage at places where it should contain zero.

This happens when your guest starts using an unpopulated page after snapshotting started and the page has not been copied to the snapshot yet. You won't get a WP event, therefore you cannot copy "zero" to the snapshot before content gets overridden.

If you load your snapshot, it contains garbage at places that are supposed to contain zero.

There is a feature in virtio-balloon that *depends* on previously discarded pages from staying unmodified in some cases: free page reporting.

The guest will report pages (that might have been initialized to zero) to the hypervisor). The hypervisor will discard page content if the content was initialized to zero. After that, the guest is free to reuse the pages anytime with the guarantee that content has not been modified (-> still is zero).

See QEMU hw/virtio/virtio-balloon.c: virtio_balloon_handle_report()

"When we discard the page it has the effect of removing the page from the hypervisor itself and causing it to be zeroed when it is returned to us. So we must not discard the page [...] if the guest is expecting it to retain a non-zero value."

And Linux drivers/virtio/virtio_balloon.c: virtballoon_validate()

"Inform the hypervisor that our pages are poisoned or initialized. If we cannot do that then we should disable page reporting as it could potentially change the contents of our free pages."

It's as simple as having a Linux guest with init_on_free and free-page-reporting active via virtio-balloon.

Long story short, your feature might break guests (when continuing the snapshot) when free page reporting is active. I agree that MISSING events might be too heavy, so you should disable snapshots if free page reporting is active.

Signature · 3 lines
Thanks,

David / dhildenb
#20 lore raw
Quoted 133 lines · David Hildenbrand
Quoted 86 lines · Andrey Gruzdev
Quoted 85 lines · Peter Xu
Quoted 50 lines · Andrey Gruzdev
Quoted 49 lines · David Hildenbrand
Quoted 18 lines
Quoted 18 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

Quoted 6 lines
Quoted 3 lines

How are you handling that scenario, or why don't you have to handle that scenario?

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 6 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma.
For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

See the attached test program. Triggers for me on 5.11.0-rc6+ and 5.9.13-200.fc33

gcc -lpthread uffdio_wp.c -o uffdio_wp
./uffdio_wp
WP did not fire

Uncomment the placement of the zeropage just before registering to make the WP actually trigger. If there is no PTE, there is nothing to protect.

And it makes sense: How should the fault handler know which ranges you wp-ed, if there is no place to store that information (the PTEs!). The VMA cannot tell that story, it only knows that someone registered UFFD_WP to selectively wp some parts.

Quoted 8 lines
Quoted 2 lines

You might have to register also for MISSING faults and place zero pages.

Looked at the kernel code, agree that we miss WP events for unpopulated pages, UFFD_WP softbit won't be set in this case. But it doesn't make saved snapshot inconsistent or introduce security issues. The only side effect is that we may save updated page instead of zeroed, just increasing snapshot size. However this guest-physical page has never been touched from the point of view of saved vCPU/device state and is not a concern.

Oh I just remembered one thing, that Linux should be zeroing pages when allocating, so even if the page has legacy content it'll be cleared with __GFP_ZERO allocations. So yeah it would be harder to have issue at least with a sensible OS. I'm not sure about Windows or others, but it could be a common case. Then the only overhead is the extra pages we kept in the live snapshot, which takes some more disk space.

Or there could be firmware running without OS at all, but it should really not read unallocated pages assuming there must be zero. It's not a sane behavior even for a firmware.

Quoted 8 lines

Often (at least on desktop Windows guests) only a small part of RAM has ever been allocated by guest. Migration code needs to read each guest-physical page, so we'll have a lot of additional UFFD events, much more MISSING events then WP-faults.

And the main problem is that adding MISSING handler is impossible in current single-threaded snapshot code. We'll get an immediate deadlock on iterative page read.

Right. We'll need to rework the design but just for saving a bunch of snapshot image disk size. So now I agree with you, let's keep this in mind, but maybe it isn't worth a fix for now, at least until we figure something really broken.

Andrey, do you think we should still mention this issue into the todo list of the wiki page of live snapshot?

Quoted 9 lines
Quoted 2 lines

Thanks,

Yes, even if the page happens to be overwritten, it's overwritten by the same VM so no security boundaries are crossed. And no machine code can assume that RAM content is zeroed on power-on or reset so our snapshot state stays quite consistent.

Agree we should keep it in mind, but IMHO adding MISSING handler and running separate thread would make performance worse.. So I doubt it's worth adding this to TODO list..

So, here is what happens: your snapshot will contain garbage at places where it should contain zero.

This happens when your guest starts using an unpopulated page after snapshotting started and the page has not been copied to the snapshot yet. You won't get a WP event, therefore you cannot copy "zero" to the snapshot before content gets overridden.

If you load your snapshot, it contains garbage at places that are supposed to contain zero.

There is a feature in virtio-balloon that *depends* on previously discarded pages from staying unmodified in some cases: free page reporting.

The guest will report pages (that might have been initialized to zero) to the hypervisor). The hypervisor will discard page content if the content was initialized to zero. After that, the guest is free to reuse the pages anytime with the guarantee that content has not been modified (-> still is zero).

See QEMU hw/virtio/virtio-balloon.c: virtio_balloon_handle_report()

"When we discard the page it has the effect of removing the page from the hypervisor itself and causing it to be zeroed when it is returned to us. So we must not discard the page [...] if the guest is expecting it to retain a non-zero value."

And Linux drivers/virtio/virtio_balloon.c: virtballoon_validate()

"Inform the hypervisor that our pages are poisoned or initialized. If we cannot do that then we should disable page reporting as it could potentially change the contents of our free pages."

Quoted 7 lines

It's as simple as having a Linux guest with init_on_free and free-page-reporting active via virtio-balloon.

Long story short, your feature might break guests (when continuing the snapshot) when free page reporting is active. I agree that MISSING events might be too heavy, so you should disable snapshots if free page reporting is active.

When the page is reported with poison_val set, it is written already by the guest, right (either all zeros, or some special marks)? If so, why it won't be wr-protected by uffd? Thanks,

Signature · 1 line
Peter Xu
#21 lore raw
Quoted 140 lines

Am 11.02.2021 um 21:31 schrieb Peter Xu <[email protected]>:

Quoted 136 lines · David Hildenbrand
Quoted 87 lines · Andrey Gruzdev
Quoted 85 lines · Peter Xu
Quoted 50 lines · Andrey Gruzdev
Quoted 49 lines · David Hildenbrand
Quoted 18 lines
Quoted 18 lines

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

Quoted 6 lines
Quoted 3 lines

How are you handling that scenario, or why don't you have to handle that scenario?

Hi David,

I really wonder if such a problem exists.. If we are talking about a

I immediately ran into this issue with my simplest test cases. :)

Quoted 6 lines

write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma.
For UFFD_WP vma's page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

See the attached test program. Triggers for me on 5.11.0-rc6+ and 5.9.13-200.fc33

gcc -lpthread uffdio_wp.c -o uffdio_wp
./uffdio_wp
WP did not fire

Uncomment the placement of the zeropage just before registering to make the WP actually trigger. If there is no PTE, there is nothing to protect.

And it makes sense: How should the fault handler know which ranges you wp-ed, if there is no place to store that information (the PTEs!). The VMA cannot tell that story, it only knows that someone registered UFFD_WP to selectively wp some parts.

Quoted 8 lines
Quoted 2 lines

You might have to register also for MISSING faults and place zero pages.

Looked at the kernel code, agree that we miss WP events for unpopulated pages, UFFD_WP softbit won't be set in this case. But it doesn't make saved snapshot inconsistent or introduce security issues. The only side effect is that we may save updated page instead of zeroed, just increasing snapshot size. However this guest-physical page has never been touched from the point of view of saved vCPU/device state and is not a concern.

Oh I just remembered one thing, that Linux should be zeroing pages when allocating, so even if the page has legacy content it'll be cleared with __GFP_ZERO allocations. So yeah it would be harder to have issue at least with a sensible OS. I'm not sure about Windows or others, but it could be a common case. Then the only overhead is the extra pages we kept in the live snapshot, which takes some more disk space.

Or there could be firmware running without OS at all, but it should really not read unallocated pages assuming there must be zero. It's not a sane behavior even for a firmware.

Quoted 8 lines

Often (at least on desktop Windows guests) only a small part of RAM has ever been allocated by guest. Migration code needs to read each guest-physical page, so we'll have a lot of additional UFFD events, much more MISSING events then WP-faults.

And the main problem is that adding MISSING handler is impossible in current single-threaded snapshot code. We'll get an immediate deadlock on iterative page read.

Right. We'll need to rework the design but just for saving a bunch of snapshot image disk size. So now I agree with you, let's keep this in mind, but maybe it isn't worth a fix for now, at least until we figure something really broken.

Andrey, do you think we should still mention this issue into the todo list of the wiki page of live snapshot?

Quoted 9 lines
Quoted 2 lines

Thanks,

Yes, even if the page happens to be overwritten, it's overwritten by the same VM so no security boundaries are crossed. And no machine code can assume that RAM content is zeroed on power-on or reset so our snapshot state stays quite consistent.

Agree we should keep it in mind, but IMHO adding MISSING handler and running separate thread would make performance worse.. So I doubt it's worth adding this to TODO list..

So, here is what happens: your snapshot will contain garbage at places where it should contain zero.

This happens when your guest starts using an unpopulated page after snapshotting started and the page has not been copied to the snapshot yet. You won't get a WP event, therefore you cannot copy "zero" to the snapshot before content gets overridden.

If you load your snapshot, it contains garbage at places that are supposed to contain zero.

There is a feature in virtio-balloon that *depends* on previously discarded pages from staying unmodified in some cases: free page reporting.

The guest will report pages (that might have been initialized to zero) to the hypervisor). The hypervisor will discard page content if the content was initialized to zero. After that, the guest is free to reuse the pages anytime with the guarantee that content has not been modified (-> still is zero).

See QEMU hw/virtio/virtio-balloon.c: virtio_balloon_handle_report()

"When we discard the page it has the effect of removing the page from the hypervisor itself and causing it to be zeroed when it is returned to us. So we must not discard the page [...] if the guest is expecting it to retain a non-zero value."

And Linux drivers/virtio/virtio_balloon.c: virtballoon_validate()

"Inform the hypervisor that our pages are poisoned or initialized. If we cannot do that then we should disable page reporting as it could potentially change the contents of our free pages."

It's as simple as having a Linux guest with init_on_free and free-page-reporting active via virtio-balloon.

Quoted 8 lines
Quoted 4 lines

Long story short, your feature might break guests (when continuing the snapshot) when free page reporting is active. I agree that MISSING events might be too heavy, so you should disable snapshots if free page reporting is active.

When the page is reported with poison_val set, it is written already by the guest, right (either all zeros, or some special marks)? If so, why it won't be wr-protected by uffd?

Let‘s take a look at init-on-free.

The guest zeroes a page and puts it onto a buddy freelist. Free page reporting code takes it off that list and reports it to the hypervisor. The hypervisor discards the physical page and tells the guest he‘s done processing the page. The guest re-places the page onto the free page list.

From that point on, the page can be re-allocated inside the guest and is assumed to be zero. On access, a fresh (zeroed) page is populated by the hypervisor. The guest won‘t re-zero the page, as it has the guarantee (from free page reporting) that the page remained zero.

Write-protecting the unpopulated page won‘t work as discussed.

Quoted 4 lines
Signature · 2 lines
-- 
Peter Xu
#22 lore raw
Quoted 7 lines · David Hildenbrand

Let‘s take a look at init-on-free.

The guest zeroes a page and puts it onto a buddy freelist. Free page reporting code takes it off that list and reports it to the hypervisor. The hypervisor discards the physical page and tells the guest he‘s done processing the page. The guest re-places the page onto the free page list.

From that point on, the page can be re-allocated inside the guest and is assumed to be zero. On access, a fresh (zeroed) page is populated by the hypervisor. The guest won‘t re-zero the page, as it has the guarantee (from free page reporting) that the page remained zero.

Write-protecting the unpopulated page won‘t work as discussed.

IMHO no matter if it's init_on_alloc or init_on_free or both, as long as it's inited in some way then it means the guest OS wrote to it. Then wr-protect will work..

MADV_DONTNEED during live snapshot seems to be a separate topic as you mentioned in the other thread. For that, I agree we'd better simply let virtio_balloon_inhibited() to return true for live snapshot too just like postcopy.

Thanks,

Signature · 1 line
Peter Xu
#23 lore raw
Quoted 8 lines

Am 11.02.2021 um 22:05 schrieb Peter Xu <[email protected]>:

Quoted 4 lines · David Hildenbrand

Let‘s take a look at init-on-free.

The guest zeroes a page and puts it onto a buddy freelist. Free page reporting code takes it off that list and reports it to the hypervisor. The hypervisor discards the physical page and tells the guest he‘s done processing the page. The guest re-places the page onto the free page list.

Quoted 7 lines
Quoted 3 lines

From that point on, the page can be re-allocated inside the guest and is assumed to be zero. On access, a fresh (zeroed) page is populated by the hypervisor. The guest won‘t re-zero the page, as it has the guarantee (from free page reporting) that the page remained zero.

Write-protecting the unpopulated page won‘t work as discussed.

IMHO no matter if it's init_on_alloc or init_on_free or both, as long as it's inited in some way then it means the guest OS wrote to it. Then wr-protect will work..

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

Quoted 5 lines

MADV_DONTNEED during live snapshot seems to be a separate topic as you mentioned in the other thread. For that, I agree we'd better simply let virtio_balloon_inhibited() to return true for live snapshot too just like postcopy.

Yes, but other issue.

Quoted 6 lines

Thanks,

Signature · 1 line
Peter Xu
#24 lore raw
Quoted 1 line · David Hildenbrand

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

I see what you mean now, and iiuc it will only be a problem if init_on_free=1. I think CONFIG_INIT_ON_FREE_DEFAULT_ON should be off for most distros, so the impact should be small, I think. I thought about it, but indeed I didn't see a good way to fix this if without fixing the zero page copy for live snapshot.

Signature · 1 line
Peter Xu
#25 lore raw
Quoted 5 lines · Peter Xu
Quoted 1 line · David Hildenbrand

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

I see what you mean now, and iiuc it will only be a problem if init_on_free=1. I think CONFIG_INIT_ON_FREE_DEFAULT_ON should be off for most distros, so the

Yes, some distros seem to enable init_on_alloc instead. Looking at the introducing commit 6471384af2a6 ("mm: security: introduce init_on_alloc=1 and init_on_free=1 boot options") there are security use cases and it might become important with memory tagging.

Note that in Linux, there was also the option to poison pages with 0, removed via f289041ed4cf ("mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO"), available in some kernels that supported free page reporting.

It got removed and use cases got told to use init_on_free.

Quoted 2 lines

impact should be small, I think. I thought about it, but indeed I didn't see a good way to fix this if without fixing the zero page copy for live snapshot.

We should really document this (unexpected) behavior of snapshotting. Otherwise, the next feature comes around that relies on pages that were discarded to remain zeroed (I even have one in mind ;) ) and forgets to disable snapshots.

Signature · 3 lines
Thanks,

David / dhildenb
#26 lore raw
Quoted 19 lines · David Hildenbrand
Quoted 5 lines · Peter Xu
Quoted 1 line · David Hildenbrand

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

I see what you mean now, and iiuc it will only be a problem if init_on_free=1. I think CONFIG_INIT_ON_FREE_DEFAULT_ON should be off for most distros, so the

Yes, some distros seem to enable init_on_alloc instead. Looking at the introducing commit 6471384af2a6 ("mm: security: introduce init_on_alloc=1 and init_on_free=1 boot options") there are security use cases and it might become important with memory tagging.

Note that in Linux, there was also the option to poison pages with 0, removed via f289041ed4cf ("mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO"), available in some kernels that supported free page reporting.

It got removed and use cases got told to use init_on_free.

Quoted 7 lines
Quoted 2 lines

impact should be small, I think. I thought about it, but indeed I didn't see a good way to fix this if without fixing the zero page copy for live snapshot.

We should really document this (unexpected) behavior of snapshotting. Otherwise, the next feature comes around that relies on pages that were discarded to remain zeroed (I even have one in mind ;) ) and forgets to disable snapshots.

Agreed. I'll see whether Andrey would have any idea to workaround this, or further comment. Or I can draft a patch to document this next week (or unless Andrey would beat me to it :).

Signature · 1 line
Peter Xu
#27 lore raw
Quoted 11 lines · Peter Xu
Quoted 10 lines · David Hildenbrand
Quoted 4 lines · Peter Xu
Quoted 1 line · David Hildenbrand

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

I see what you mean now, and iiuc it will only be a problem if init_on_free=1. I think CONFIG_INIT_ON_FREE_DEFAULT_ON should be off for most distros, so the

Yes, some distros seem to enable init_on_alloc instead. Looking at the introducing commit 6471384af2a6 ("mm: security: introduce init_on_alloc=1 and init_on_free=1 boot options") there are security use cases and it might become important with memory tagging.

Quoted 6 lines
Quoted 6 lines

Note that in Linux, there was also the option to poison pages with 0, removed via f289041ed4cf ("mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO"), available in some kernels that supported free page reporting.

It got removed and use cases got told to use init_on_free.

I think we talk about init_on_free()/init_on_alloc() on guest side, right? Still can't get how it relates to host's unpopulated pages..

Try to look from hardware side. Untouched SDRAM in hardware is required to contain zeroes somehow? No. These 'trash' pages in migration stream are like never written physical memory pages, they are really not needed in snapshot but they don't do any harm as well as there's no harm in that never-written physical page is full of garbage.

Do these 'trash' pages in snapshot contain sensitive information not allowed to be accessed by the same VM? I think no. Or we need a good example how it can be potentially exploited.

The only issue that I see is madvise(MADV_DONTNEED) for RAM blocks during snapshotting. And free page reporting or memory balloon is secondary - the point is that UFFD_WP snapshot is incompatible with madvise(MADV_DONTNEED) on hypervisor side. No matter which guest functionality can induce it.

Quoted 10 lines
Quoted 6 lines
Quoted 2 lines

impact should be small, I think. I thought about it, but indeed I didn't see a good way to fix this if without fixing the zero page copy for live snapshot.

We should really document this (unexpected) behavior of snapshotting. Otherwise, the next feature comes around that relies on pages that were discarded to remain zeroed (I even have one in mind ;) ) and forgets to disable snapshots.

Agreed. I'll see whether Andrey would have any idea to workaround this, or further comment. Or I can draft a patch to document this next week (or unless Andrey would beat me to it :).

Really better to document this specific behaviour but also clarify that the saved state remains consistent and secure, off course if you agree with my arguments.

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#28 lore raw
Quoted 32 lines

Am 13.02.2021 um 10:34 schrieb Andrey Gruzdev <[email protected]>:



Quoted 28 lines · Peter Xu
Quoted 11 lines
Quoted 11 lines · David Hildenbrand
Quoted 5 lines · Peter Xu
Quoted 2 lines · David Hildenbrand

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

I see what you mean now, and iiuc it will only be a problem if init_on_free=1. I think CONFIG_INIT_ON_FREE_DEFAULT_ON should be off for most distros, so the

Yes, some distros seem to enable init_on_alloc instead. Looking at the introducing commit 6471384af2a6 ("mm: security: introduce init_on_alloc=1 and init_on_free=1 boot options") there are security use cases and it might become important with memory tagging.

Quoted 6 lines
Quoted 6 lines

Note that in Linux, there was also the option to poison pages with 0, removed via f289041ed4cf ("mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO"), available in some kernels that supported free page reporting.

It got removed and use cases got told to use init_on_free.

I think we talk about init_on_free()/init_on_alloc() on guest side, right? Still can't get how it relates to host's unpopulated pages..

Try to look from hardware side. Untouched SDRAM in hardware is required to contain zeroes somehow? No. These 'trash' pages in migration stream are like never written physical memory pages, they are really not needed in snapshot but they don't do any harm as well as there's no harm in that never-written physical page is full of garbage.

Do these 'trash' pages in snapshot contain sensitive information not allowed to be accessed by the same VM? I think no. Or we need a good example how it can be potentially exploited.

I tried to explain how your implementation breaks *the guest inside the snapshot* (I have no idea why you talk about sensitive information). If you run the snapshot, the guest will run into trouble, because the snapshot contains different data than the guest expects:

1. with discards before snapshotting started and free page reporting is running
2. with discards after snapshotting started

Maybe Peter can enlighten you, or the links I shared.

#29 lore raw
In reply to Andrey Gruzdev

Hi, Andrey,

Quoted 12 lines · Andrey Gruzdev
Quoted 11 lines · Peter Xu
Quoted 10 lines · David Hildenbrand
Quoted 4 lines · Peter Xu
Quoted 1 line · David Hildenbrand

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

I see what you mean now, and iiuc it will only be a problem if init_on_free=1. I think CONFIG_INIT_ON_FREE_DEFAULT_ON should be off for most distros, so the

Yes, some distros seem to enable init_on_alloc instead. Looking at the introducing commit 6471384af2a6 ("mm: security: introduce init_on_alloc=1 and init_on_free=1 boot options") there are security use cases and it might become important with memory tagging.

Quoted 8 lines
Quoted 6 lines
Quoted 6 lines

Note that in Linux, there was also the option to poison pages with 0, removed via f289041ed4cf ("mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO"), available in some kernels that supported free page reporting.

It got removed and use cases got told to use init_on_free.

I think we talk about init_on_free()/init_on_alloc() on guest side, right?

Right. IIUC it's the init_on_free() that matters.

We'll have no issue if init_on_alloc=1 && init_on_free=0, since in that case all pages will be zeroed after all before the new page returned to the caller to allocate the page. Then we're safe, I think.

Quoted 6 lines

Still can't get how it relates to host's unpopulated pages..
Try to look from hardware side. Untouched SDRAM in hardware is required to contain zeroes somehow? No. These 'trash' pages in migration stream are like never written physical memory pages, they are really not needed in snapshot but they don't do any harm as well as there's no harm in that never-written physical page is full of garbage.

Quoted 6 lines

Do these 'trash' pages in snapshot contain sensitive information not allowed to be accessed by the same VM? I think no. Or we need a good example how it can be potentially exploited.

The only issue that I see is madvise(MADV_DONTNEED) for RAM blocks during snapshotting. And free page reporting or memory balloon is secondary - the point is that UFFD_WP snapshot is incompatible with madvise(MADV_DONTNEED) on hypervisor side. No matter which guest functionality can induce it.

I think the problem is if with init_on_free=1, the kernel will assume that all the pages that got freed has been zeroed before-hand so it thinks that it's a waste of time to zero it again when the page is reused/reallocated. As a reference see kernel prep_new_page() where there's:

	if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags))
		kernel_init_free_pages(page, 1 << order);

In this case I believe free_pages_prezeroed() will return true, then we don't even need to check want_init_on_alloc() at all. Note that it'll cover all the cases where kernel allocates with __GFP_ZERO: it means it could happen that even the guest kernel tries to alloc_page(__GFP_ZERO) it may got a page with random data after the live snapshot is loaded. So it's not about any hardware, it's the optimization of guest kernel instead. It is actually reasonable and efficient since if we *know* that page is zero page then we shouldn't bother zeroing it again. However it brought us a bit of trouble on live snapshot that the current solution might not work for all guest OS configurations.

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

impact should be small, I think. I thought about it, but indeed I didn't see a good way to fix this if without fixing the zero page copy for live snapshot.

We should really document this (unexpected) behavior of snapshotting. Otherwise, the next feature comes around that relies on pages that were discarded to remain zeroed (I even have one in mind ;) ) and forgets to disable snapshots.

Quoted 6 lines
Quoted 4 lines

Agreed. I'll see whether Andrey would have any idea to workaround this, or further comment. Or I can draft a patch to document this next week (or unless Andrey would beat me to it :).

Really better to document this specific behaviour but also clarify that the saved state remains consistent and secure, off course if you agree with my arguments.

Yes, no rush on anything yet, let's reach a consensus on understanding the problem before trying to even document anything. If you agree with above, feel free to draft a documentation update patch if you'd like, that could also contain the code to prohibit virtio-balloon page reporting when live snapshot.

IMHO if above issue exists, it'll be indeed better to implement the MISSING tracking as well with UFFDIO_ZEROCOPY - it's still not optimized to keep trash pages in the live snapshot, since for a high dirty rate guest the number of trash pages could still be huge. It would definitely be more challenging than only do wr-protect so we may need multi-threading at least, but it'll be a pity that live snapshot randomly fails some guests, even if it's rare. The thing is host cannot easily detect that guest config, so we can't simply block some users taking snapshots even if at last the snapshot could be silently broken.

Thanks,

Signature · 1 line
Peter Xu
#30 lore raw
Quoted 51 lines · Peter Xu

Hi, Andrey,

Quoted 12 lines · Andrey Gruzdev
Quoted 11 lines · Peter Xu
Quoted 10 lines · David Hildenbrand
Quoted 4 lines · Peter Xu
Quoted 1 line · David Hildenbrand

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

I see what you mean now, and iiuc it will only be a problem if init_on_free=1. I think CONFIG_INIT_ON_FREE_DEFAULT_ON should be off for most distros, so the

Yes, some distros seem to enable init_on_alloc instead. Looking at the introducing commit 6471384af2a6 ("mm: security: introduce init_on_alloc=1 and init_on_free=1 boot options") there are security use cases and it might become important with memory tagging.

Quoted 8 lines
Quoted 6 lines
Quoted 6 lines

Note that in Linux, there was also the option to poison pages with 0, removed via f289041ed4cf ("mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO"), available in some kernels that supported free page reporting.

It got removed and use cases got told to use init_on_free.

I think we talk about init_on_free()/init_on_alloc() on guest side, right?

Right. IIUC it's the init_on_free() that matters.

We'll have no issue if init_on_alloc=1 && init_on_free=0, since in that case all pages will be zeroed after all before the new page returned to the caller to allocate the page. Then we're safe, I think.

Quoted 6 lines

Still can't get how it relates to host's unpopulated pages..
Try to look from hardware side. Untouched SDRAM in hardware is required to contain zeroes somehow? No. These 'trash' pages in migration stream are like never written physical memory pages, they are really not needed in snapshot but they don't do any harm as well as there's no harm in that never-written physical page is full of garbage.

Quoted 6 lines

Do these 'trash' pages in snapshot contain sensitive information not allowed to be accessed by the same VM? I think no. Or we need a good example how it can be potentially exploited.

The only issue that I see is madvise(MADV_DONTNEED) for RAM blocks during snapshotting. And free page reporting or memory balloon is secondary - the point is that UFFD_WP snapshot is incompatible with madvise(MADV_DONTNEED) on hypervisor side. No matter which guest functionality can induce it.

I think the problem is if with init_on_free=1, the kernel will assume that all the pages that got freed has been zeroed before-hand so it thinks that it's a waste of time to zero it again when the page is reused/reallocated. As a reference see kernel prep_new_page() where there's:

	if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags))
		kernel_init_free_pages(page, 1 << order);
Quoted 9 lines

In this case I believe free_pages_prezeroed() will return true, then we don't even need to check want_init_on_alloc() at all. Note that it'll cover all the cases where kernel allocates with __GFP_ZERO: it means it could happen that even the guest kernel tries to alloc_page(__GFP_ZERO) it may got a page with random data after the live snapshot is loaded. So it's not about any hardware, it's the optimization of guest kernel instead. It is actually reasonable and efficient since if we *know* that page is zero page then we shouldn't bother zeroing it again. However it brought us a bit of trouble on live snapshot that the current solution might not work for all guest OS configurations.

Adding to that, we are so far talking about how Linux *currently* implements it, but that is just an instance of the problem where it could happen in practice.

Free page reporting documents in the spec that with the right configuration, previously reported free pages are guaranteed to retain a certain value (e.g., 0) when re-accessed. So any future guest changes that rely on the virtio spec (e.g., Windows support) would be problematic - as these pages in the snapshot don't actually keep the value.

Signature · 3 lines
Thanks,

David / dhildenb
#31 lore raw
In reply to Peter Xu
Quoted 48 lines · Peter Xu

Hi, Andrey,

Quoted 12 lines · Andrey Gruzdev
Quoted 11 lines · Peter Xu
Quoted 10 lines · David Hildenbrand
Quoted 4 lines · Peter Xu
Quoted 1 line · David Hildenbrand

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

I see what you mean now, and iiuc it will only be a problem if init_on_free=1. I think CONFIG_INIT_ON_FREE_DEFAULT_ON should be off for most distros, so the

Yes, some distros seem to enable init_on_alloc instead. Looking at the introducing commit 6471384af2a6 ("mm: security: introduce init_on_alloc=1 and init_on_free=1 boot options") there are security use cases and it might become important with memory tagging.

Quoted 7 lines
Quoted 6 lines
Quoted 6 lines

Note that in Linux, there was also the option to poison pages with 0, removed via f289041ed4cf ("mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO"), available in some kernels that supported free page reporting.

It got removed and use cases got told to use init_on_free.

I think we talk about init_on_free()/init_on_alloc() on guest side, right?

Right. IIUC it's the init_on_free() that matters.

We'll have no issue if init_on_alloc=1 && init_on_free=0, since in that case all pages will be zeroed after all before the new page returned to the caller to allocate the page. Then we're safe, I think.

Quoted 6 lines

Still can't get how it relates to host's unpopulated pages..
Try to look from hardware side. Untouched SDRAM in hardware is required to contain zeroes somehow? No. These 'trash' pages in migration stream are like never written physical memory pages, they are really not needed in snapshot but they don't do any harm as well as there's no harm in that never-written physical page is full of garbage.

Quoted 6 lines

Do these 'trash' pages in snapshot contain sensitive information not allowed to be accessed by the same VM? I think no. Or we need a good example how it can be potentially exploited.

The only issue that I see is madvise(MADV_DONTNEED) for RAM blocks during snapshotting. And free page reporting or memory balloon is secondary - the point is that UFFD_WP snapshot is incompatible with madvise(MADV_DONTNEED) on hypervisor side. No matter which guest functionality can induce it.

I think the problem is if with init_on_free=1, the kernel will assume that all the pages that got freed has been zeroed before-hand so it thinks that it's a waste of time to zero it again when the page is reused/reallocated. As a reference see kernel prep_new_page() where there's:

	if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags))
		kernel_init_free_pages(page, 1 << order);
Quoted 9 lines

In this case I believe free_pages_prezeroed() will return true, then we don't even need to check want_init_on_alloc() at all. Note that it'll cover all the cases where kernel allocates with __GFP_ZERO: it means it could happen that even the guest kernel tries to alloc_page(__GFP_ZERO) it may got a page with random data after the live snapshot is loaded. So it's not about any hardware, it's the optimization of guest kernel instead. It is actually reasonable and efficient since if we *know* that page is zero page then we shouldn't bother zeroing it again. However it brought us a bit of trouble on live snapshot that the current solution might not work for all guest OS configurations.

So I'd like to clarify that guest's init_on_alloc/init_on_free cannot bring any problems if we don't consider virtio-baloon here.. If these pages have been zeroed inside the guest they certainly have got populated on the host. And UFFD_WP should work as expected.

Quoted 26 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 2 lines

impact should be small, I think. I thought about it, but indeed I didn't see a good way to fix this if without fixing the zero page copy for live snapshot.

We should really document this (unexpected) behavior of snapshotting. Otherwise, the next feature comes around that relies on pages that were discarded to remain zeroed (I even have one in mind ;) ) and forgets to disable snapshots.

Quoted 6 lines
Quoted 4 lines

Agreed. I'll see whether Andrey would have any idea to workaround this, or further comment. Or I can draft a patch to document this next week (or unless Andrey would beat me to it :).

Really better to document this specific behaviour but also clarify that the saved state remains consistent and secure, off course if you agree with my arguments.

Yes, no rush on anything yet, let's reach a consensus on understanding the problem before trying to even document anything. If you agree with above, feel free to draft a documentation update patch if you'd like, that could also contain the code to prohibit virtio-balloon page reporting when live snapshot.

IMHO if above issue exists, it'll be indeed better to implement the MISSING tracking as well with UFFDIO_ZEROCOPY - it's still not optimized to keep trash pages in the live snapshot, since for a high dirty rate guest the number of trash pages could still be huge. It would definitely be more challenging than only do wr-protect so we may need multi-threading at least, but it'll be a pity that live snapshot randomly fails some guests, even if it's rare. The thing is host cannot easily detect that guest config, so we can't simply block some users taking snapshots even if at last the snapshot could be silently broken.

Quoted 2 lines

Thanks,

Agree, let's reach consensus before doing anything. For the concurrent RAM block discards it seems clear enough that they should be disabled for the duration of snapshot, like it's done when incoming postcopy is active.

For the discards that happen before snapshot is started, I need to dig into Linux and QEMU virtio-baloon code more to get clear with it. Anyhow I'm quite sure that adding global MISSING handler for snapshotting is too heavy and not really needed.

Thanks,

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#32 lore raw
Quoted 59 lines · Andrey Gruzdev
Quoted 48 lines · Peter Xu

Hi, Andrey,

Quoted 12 lines · Andrey Gruzdev
Quoted 11 lines · Peter Xu
Quoted 10 lines · David Hildenbrand
Quoted 4 lines · Peter Xu
Quoted 1 line · David Hildenbrand

The issue is when the discard happened before starting the snapshot. Write-protection won‘t work and the zeroed content won‘t be retained in the snapshot.

I see what you mean now, and iiuc it will only be a problem if init_on_free=1. I think CONFIG_INIT_ON_FREE_DEFAULT_ON should be off for most distros, so the

Yes, some distros seem to enable init_on_alloc instead. Looking at the introducing commit 6471384af2a6 ("mm: security: introduce init_on_alloc=1 and init_on_free=1 boot options") there are security use cases and it might become important with memory tagging.

Quoted 7 lines
Quoted 6 lines
Quoted 6 lines

Note that in Linux, there was also the option to poison pages with 0, removed via f289041ed4cf ("mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO"), available in some kernels that supported free page reporting.

It got removed and use cases got told to use init_on_free.

I think we talk about init_on_free()/init_on_alloc() on guest side, right?

Right. IIUC it's the init_on_free() that matters.

We'll have no issue if init_on_alloc=1 && init_on_free=0, since in that case all pages will be zeroed after all before the new page returned to the caller to allocate the page. Then we're safe, I think.

Quoted 6 lines

Still can't get how it relates to host's unpopulated pages..
Try to look from hardware side. Untouched SDRAM in hardware is required to contain zeroes somehow? No. These 'trash' pages in migration stream are like never written physical memory pages, they are really not needed in snapshot but they don't do any harm as well as there's no harm in that never-written physical page is full of garbage.

Quoted 6 lines

Do these 'trash' pages in snapshot contain sensitive information not allowed to be accessed by the same VM? I think no. Or we need a good example how it can be potentially exploited.

The only issue that I see is madvise(MADV_DONTNEED) for RAM blocks during snapshotting. And free page reporting or memory balloon is secondary - the point is that UFFD_WP snapshot is incompatible with madvise(MADV_DONTNEED) on hypervisor side. No matter which guest functionality can induce it.

I think the problem is if with init_on_free=1, the kernel will assume that all the pages that got freed has been zeroed before-hand so it thinks that it's a waste of time to zero it again when the page is reused/reallocated. As a reference see kernel prep_new_page() where there's:

	if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags))
		kernel_init_free_pages(page, 1 << order);
Quoted 9 lines

In this case I believe free_pages_prezeroed() will return true, then we don't even need to check want_init_on_alloc() at all. Note that it'll cover all the cases where kernel allocates with __GFP_ZERO: it means it could happen that even the guest kernel tries to alloc_page(__GFP_ZERO) it may got a page with random data after the live snapshot is loaded. So it's not about any hardware, it's the optimization of guest kernel instead. It is actually reasonable and efficient since if we *know* that page is zero page then we shouldn't bother zeroing it again. However it brought us a bit of trouble on live snapshot that the current solution might not work for all guest OS configurations.

Quoted 3 lines

So I'd like to clarify that guest's init_on_alloc/init_on_free cannot bring any problems if we don't consider virtio-baloon here.. If these pages have been zeroed inside the guest they certainly have got populated on the host. And UFFD_WP should work as expected.

Yes, no discards, no problem.

Signature · 3 lines
Thanks,

David / dhildenb
#33 lore raw
In reply to Andrey Gruzdev

Andrey,

Quoted 2 lines · Andrey Gruzdev

For the discards that happen before snapshot is started, I need to dig into Linux and QEMU virtio-baloon code more to get clear with it.

Yes it's very tricky on how the error could trigger.

Let's think of below sequence:

- Start a guest with init_on_free=1 set and also a virtio-balloon device

- Guest frees a page P and zeroed it (since init_on_free=1). Now P contains all zeros.

- Virtio-balloon reports this page to host, MADV_DONTNEED sent, then this page is dropped on the host.

- Start live snapshot, wr-protect all pages (but not including page P because it's currently missing). Let's call it $SNAPSHOT1.

- Guest does alloc_page(__GFP_ZERO), accidentally fetching this page P and returned

- So far, page P is still all zero (which is good!), then guest uses page P and writes data to it (say, now P has data P1 rather than all zeros).

- Live snapshot saves page P, which content P1 rather than all zeros.

- Live snapshot completed. Saved as $SNAPSHOT1.

Then when load snapshot $SNAPSHOT1, we'll have P contains data P1. After snapshot loaded, when guest allocate again with alloc_page(__GFP_ZERO) on this page P, since guest kernel "thought" this page is all-zero already so memzero() is skipped even if __GFP_ZERO is provided. Then this page P (with content P1) got returned for the alloc_page(__GFP_ZERO) even if __GFP_ZERO set. That could break the caller of alloc_page().

Quoted 2 lines

Anyhow I'm quite sure that adding global MISSING handler for snapshotting is too heavy and not really needed.

UFFDIO_ZEROCOPY installs a zero pfn and that should be all of it. There'll definitely be overhead, but it may not be that huge as imagined. Live snapshot is great in that we have point-in-time image of guest without stopping the guest, so taking slightly longer time won't be a huge loss to us too.

Actually we can also think of other ways to work around it. One way is we can pre-fault all guest pages before wr-protect. Note that we don't need to write to the guest page because read would suffice, since uffd-wp would also work with zero pfn. It's just that this workaround won't help on saving snapshot disk space, but it seems working. It would be great if you have other workarounds, maybe as you said UFFDIO_ZEROCOPY is not the only route.

Thanks,

Signature · 1 line
Peter Xu
#34 lore raw
Quoted 46 lines · Peter Xu

Andrey,

Quoted 2 lines · Andrey Gruzdev

For the discards that happen before snapshot is started, I need to dig into Linux and QEMU virtio-baloon code more to get clear with it.

Yes it's very tricky on how the error could trigger.

Let's think of below sequence:

- Start a guest with init_on_free=1 set and also a virtio-balloon device

- Guest frees a page P and zeroed it (since init_on_free=1). Now P contains all zeros.

- Virtio-balloon reports this page to host, MADV_DONTNEED sent, then this page is dropped on the host.

- Start live snapshot, wr-protect all pages (but not including page P because it's currently missing). Let's call it $SNAPSHOT1.

- Guest does alloc_page(__GFP_ZERO), accidentally fetching this page P and returned

- So far, page P is still all zero (which is good!), then guest uses page P and writes data to it (say, now P has data P1 rather than all zeros).

- Live snapshot saves page P, which content P1 rather than all zeros.

- Live snapshot completed. Saved as $SNAPSHOT1.

Then when load snapshot $SNAPSHOT1, we'll have P contains data P1. After snapshot loaded, when guest allocate again with alloc_page(__GFP_ZERO) on this page P, since guest kernel "thought" this page is all-zero already so memzero() is skipped even if __GFP_ZERO is provided. Then this page P (with content P1) got returned for the alloc_page(__GFP_ZERO) even if __GFP_ZERO set. That could break the caller of alloc_page().

Quoted 2 lines

Anyhow I'm quite sure that adding global MISSING handler for snapshotting is too heavy and not really needed.

UFFDIO_ZEROCOPY installs a zero pfn and that should be all of it. There'll definitely be overhead, but it may not be that huge as imagined. Live snapshot is great in that we have point-in-time image of guest without stopping the guest, so taking slightly longer time won't be a huge loss to us too.

Quoted 6 lines

Actually we can also think of other ways to work around it. One way is we can pre-fault all guest pages before wr-protect. Note that we don't need to write to the guest page because read would suffice, since uffd-wp would also work with zero pfn. It's just that this workaround won't help on saving snapshot disk space, but it seems working. It would be great if you have other workarounds, maybe as you said UFFDIO_ZEROCOPY is not the only route.

Wait.. it actually seems to also solve the disk usage issue.. :)

We should just need to make sure to prohibit balloon before staring to pre-fault read on all guest ram. Seems awkward, but also seems working.. Hmm..

Signature · 1 line
Peter Xu
#35 lore raw
Quoted 57 lines

Am 19.02.2021 um 22:10 schrieb Peter Xu <[email protected]>:

Quoted 46 lines · Peter Xu

Andrey,

Quoted 3 lines · Andrey Gruzdev

For the discards that happen before snapshot is started, I need to dig into Linux and QEMU virtio-baloon code more to get clear with it.

Yes it's very tricky on how the error could trigger.

Let's think of below sequence:

- Start a guest with init_on_free=1 set and also a virtio-balloon device

- Guest frees a page P and zeroed it (since init_on_free=1). Now P contains all zeros.

- Virtio-balloon reports this page to host, MADV_DONTNEED sent, then this page is dropped on the host.

- Start live snapshot, wr-protect all pages (but not including page P because it's currently missing). Let's call it $SNAPSHOT1.

- Guest does alloc_page(__GFP_ZERO), accidentally fetching this page P and returned

- So far, page P is still all zero (which is good!), then guest uses page P and writes data to it (say, now P has data P1 rather than all zeros).

- Live snapshot saves page P, which content P1 rather than all zeros.

- Live snapshot completed. Saved as $SNAPSHOT1.

Then when load snapshot $SNAPSHOT1, we'll have P contains data P1. After snapshot loaded, when guest allocate again with alloc_page(__GFP_ZERO) on this page P, since guest kernel "thought" this page is all-zero already so memzero() is skipped even if __GFP_ZERO is provided. Then this page P (with content P1) got returned for the alloc_page(__GFP_ZERO) even if __GFP_ZERO set. That could break the caller of alloc_page().

Quoted 2 lines

Anyhow I'm quite sure that adding global MISSING handler for snapshotting is too heavy and not really needed.

UFFDIO_ZEROCOPY installs a zero pfn and that should be all of it. There'll definitely be overhead, but it may not be that huge as imagined. Live snapshot is great in that we have point-in-time image of guest without stopping the guest, so taking slightly longer time won't be a huge loss to us too.

Quoted 6 lines

Actually we can also think of other ways to work around it. One way is we can pre-fault all guest pages before wr-protect. Note that we don't need to write to the guest page because read would suffice, since uffd-wp would also work with zero pfn. It's just that this workaround won't help on saving snapshot disk space, but it seems working. It would be great if you have other workarounds, maybe as you said UFFDIO_ZEROCOPY is not the only route.

Quoted 4 lines

Wait.. it actually seems to also solve the disk usage issue.. :)

We should just need to make sure to prohibit balloon before staring to pre-fault read on all guest ram. Seems awkward, but also seems working.. Hmm..

A shiver just went down my spine. Please don‘t just for the sake of creating a snapshot.

(Just imagine you don‘t have a shared zeropage...)

Quoted 3 lines
Signature · 1 line
Peter Xu
#36 lore raw
Quoted 60 lines

Am 19.02.2021 um 22:14 schrieb David Hildenbrand <[email protected]>:



Quoted 56 lines
Quoted 55 lines

Am 19.02.2021 um 22:10 schrieb Peter Xu <[email protected]>:

On Fri, Feb 19, 2021 at 03:50:52PM -0500, Peter Xu wrote:
Andrey,

Quoted 3 lines · Andrey Gruzdev

For the discards that happen before snapshot is started, I need to dig into Linux and QEMU virtio-baloon code more to get clear with it.

Yes it's very tricky on how the error could trigger.

Let's think of below sequence:

- Start a guest with init_on_free=1 set and also a virtio-balloon device

- Guest frees a page P and zeroed it (since init_on_free=1). Now P contains all zeros.

- Virtio-balloon reports this page to host, MADV_DONTNEED sent, then this page is dropped on the host.

- Start live snapshot, wr-protect all pages (but not including page P because it's currently missing). Let's call it $SNAPSHOT1.

- Guest does alloc_page(__GFP_ZERO), accidentally fetching this page P and returned

- So far, page P is still all zero (which is good!), then guest uses page P and writes data to it (say, now P has data P1 rather than all zeros).

- Live snapshot saves page P, which content P1 rather than all zeros.

- Live snapshot completed. Saved as $SNAPSHOT1.

Then when load snapshot $SNAPSHOT1, we'll have P contains data P1. After snapshot loaded, when guest allocate again with alloc_page(__GFP_ZERO) on this page P, since guest kernel "thought" this page is all-zero already so memzero() is skipped even if __GFP_ZERO is provided. Then this page P (with content P1) got returned for the alloc_page(__GFP_ZERO) even if __GFP_ZERO set. That could break the caller of alloc_page().

Quoted 2 lines

Anyhow I'm quite sure that adding global MISSING handler for snapshotting is too heavy and not really needed.

UFFDIO_ZEROCOPY installs a zero pfn and that should be all of it. There'll definitely be overhead, but it may not be that huge as imagined. Live snapshot is great in that we have point-in-time image of guest without stopping the guest, so taking slightly longer time won't be a huge loss to us too.

Actually we can also think of other ways to work around it. One way is we can pre-fault all guest pages before wr-protect. Note that we don't need to write to the guest page because read would suffice, since uffd-wp would also work with zero pfn. It's just that this workaround won't help on saving snapshot disk space, but it seems working. It would be great if you have other workarounds, maybe as you said UFFDIO_ZEROCOPY is not the only route.

Quoted 8 lines
Quoted 4 lines

Wait.. it actually seems to also solve the disk usage issue.. :)

We should just need to make sure to prohibit balloon before staring to pre-fault read on all guest ram. Seems awkward, but also seems working.. Hmm..

A shiver just went down my spine. Please don‘t just for the sake of creating a snapshot.

(Just imagine you don‘t have a shared zeropage...)

... and I just remembered we read all memory either way. Gah.

I have some patches to make snapshots fly with virtio-mem so exactly that won‘t happen. But they depend on vfio support, so it might take a while.

#37 lore raw
Quoted 7 lines · David Hildenbrand
Quoted 3 lines

A shiver just went down my spine. Please don‘t just for the sake of creating a snapshot.

(Just imagine you don‘t have a shared zeropage...)

... and I just remembered we read all memory either way. Gah.

I have some patches to make snapshots fly with virtio-mem so exactly that won‘t happen. But they depend on vfio support, so it might take a while.

Sorry I can't really follow.

It'll be great if virtio-mem won't have similar problem with live snapshot finally. Is that idea applicable to balloon too, then?

Signature · 1 line
Peter Xu
#38 lore raw
Quoted 6 lines

Am 19.02.2021 um 23:47 schrieb Peter Xu <[email protected]>:

Quoted 2 lines · David Hildenbrand
Quoted 2 lines

A shiver just went down my spine. Please don‘t just for the sake of creating a snapshot.

Quoted 8 lines
Quoted 5 lines
Quoted 1 line

(Just imagine you don‘t have a shared zeropage...)

... and I just remembered we read all memory either way. Gah.

I have some patches to make snapshots fly with virtio-mem so exactly that won‘t happen. But they depend on vfio support, so it might take a while.

Sorry I can't really follow.

Live snapshotting ends up reading all guest memory (dirty bitmap starts with all 1s), which is not what we want for virtio-mem - we don’t want to read and migrate memory that has been discarded and has no stable content.

For ordinary migration we use the guest page hint API to clear bits in the dirty bitmap after dirty bitmap sync. Well, if we don‘t do bitmap syncs we‘ll never clear any dirty bits. That‘s the problem.

Quoted 2 lines

It'll be great if virtio-mem won't have similar problem with live snapshot finally. Is that idea applicable to balloon too, then?

The idea is to reuse the RamDiscardMgr as to be introduced with vfio support to teach migration code which parts of specific RAMBlock never to migrate. It avoids the hack with reusing the guest page hint API.

As virtio-balloon is not applicable to RamDiscardMgr (and virtio-balloon has no memory about what has been inflated) it won‘t affect virtio-balloon.

Quoted 4 lines
Signature · 2 lines
-- 
Peter Xu
#39 lore raw
Quoted 3 lines · David Hildenbrand

Live snapshotting ends up reading all guest memory (dirty bitmap starts with all 1s), which is not what we want for virtio-mem - we don’t want to read and migrate memory that has been discarded and has no stable content.

For ordinary migration we use the guest page hint API to clear bits in the dirty bitmap after dirty bitmap sync. Well, if we don‘t do bitmap syncs we‘ll never clear any dirty bits. That‘s the problem.

Using dirty bitmap for that information is less efficient, becase it's definitely a larger granularity information than PAGE_SIZE. If the disgarded ranges are always continuous and at the end of a memory region, we should have some parameter in the ramblock showing that where we got shrinked then we don't check dirty bitmap at all, rather than always assuming used_length is the one.

Thanks,

Signature · 1 line
Peter Xu
#40 lore raw
Quoted 10 lines · Peter Xu
Quoted 3 lines · David Hildenbrand

Live snapshotting ends up reading all guest memory (dirty bitmap starts with all 1s), which is not what we want for virtio-mem - we don’t want to read and migrate memory that has been discarded and has no stable content.

For ordinary migration we use the guest page hint API to clear bits in the dirty bitmap after dirty bitmap sync. Well, if we don‘t do bitmap syncs we‘ll never clear any dirty bits. That‘s the problem.

Using dirty bitmap for that information is less efficient, becase it's definitely a larger granularity information than PAGE_SIZE. If the disgarded ranges are always continuous and at the end of a memory region, we should have some parameter in the ramblock showing that where we got shrinked then we don't check dirty bitmap at all, rather than always assuming used_length is the one.

They are randomly scattered across the whole RAMBlock. Shrinking/growing will be done to some degree in the future (but it won't get rid of the general sparse layout we can produce).

Signature · 3 lines
Thanks,

David / dhildenb
#41 lore raw
Quoted 12 lines · David Hildenbrand
Quoted 10 lines · Peter Xu
Quoted 3 lines · David Hildenbrand

Live snapshotting ends up reading all guest memory (dirty bitmap starts with all 1s), which is not what we want for virtio-mem - we don’t want to read and migrate memory that has been discarded and has no stable content.

For ordinary migration we use the guest page hint API to clear bits in the dirty bitmap after dirty bitmap sync. Well, if we don‘t do bitmap syncs we‘ll never clear any dirty bits. That‘s the problem.

Using dirty bitmap for that information is less efficient, becase it's definitely a larger granularity information than PAGE_SIZE. If the disgarded ranges are always continuous and at the end of a memory region, we should have some parameter in the ramblock showing that where we got shrinked then we don't check dirty bitmap at all, rather than always assuming used_length is the one.

Quoted 3 lines

They are randomly scattered across the whole RAMBlock. Shrinking/growing will be done to some degree in the future (but it won't get rid of the general sparse layout we can produce).

OK. Btw I think currently live snapshot should still be reading dirty bitmap, so maybe it's still fine. It's just that it's still not very clear to hide virtio-mem information into dirty bitmap, imho, since that's not how we interpret dirty bitmap - which is only for the sake of tracking page changes.

What's the granule of virtio-mem for this discard behavior? Maybe we could decouple it with dirty bitmap some day; if the unit is big enough it's also a gain on efficiency so we skip in chunk rather than looping over tons of pages knowing that they're discarded.

Thanks,

Signature · 1 line
Peter Xu
#42 lore raw
Quoted 13 lines · Peter Xu
Quoted 12 lines · David Hildenbrand
Quoted 10 lines · Peter Xu
Quoted 3 lines · David Hildenbrand

Live snapshotting ends up reading all guest memory (dirty bitmap starts with all 1s), which is not what we want for virtio-mem - we don’t want to read and migrate memory that has been discarded and has no stable content.

For ordinary migration we use the guest page hint API to clear bits in the dirty bitmap after dirty bitmap sync. Well, if we don‘t do bitmap syncs we‘ll never clear any dirty bits. That‘s the problem.

Using dirty bitmap for that information is less efficient, becase it's definitely a larger granularity information than PAGE_SIZE. If the disgarded ranges are always continuous and at the end of a memory region, we should have some parameter in the ramblock showing that where we got shrinked then we don't check dirty bitmap at all, rather than always assuming used_length is the one.

Quoted 8 lines
Quoted 3 lines

They are randomly scattered across the whole RAMBlock. Shrinking/growing will be done to some degree in the future (but it won't get rid of the general sparse layout we can produce).

OK. Btw I think currently live snapshot should still be reading dirty bitmap, so maybe it's still fine. It's just that it's still not very clear to hide virtio-mem information into dirty bitmap, imho, since that's not how we interpret dirty bitmap - which is only for the sake of tracking page changes.

Well, currently it is "what do we have to migrate".

Quoted 2 lines

What's the granule of virtio-mem for this discard behavior? Maybe we could

virtio-mem granularity is at least 1MB. This corresponds to 256 bits (32 bytes) in the dirty bitmap I think.

Quoted 3 lines

decouple it with dirty bitmap some day; if the unit is big enough it's also a gain on efficiency so we skip in chunk rather than looping over tons of pages knowing that they're discarded.

Yeah, it's not optimal having to go over the dirty bitmap to cross off "discarded" parts and later having to find bits to migrate.

At least find_next_bit() can skip whole longs (8 bytes) and is fairly efficient. There is certainly room for improvement (the current guest free page hinting API is certainly a hack).

Signature · 3 lines
Thanks,

David / dhildenb
#43 lore raw
Quoted 18 lines · David Hildenbrand
Quoted 17 lines · Peter Xu
Quoted 15 lines · David Hildenbrand
Quoted 10 lines · Peter Xu
Quoted 3 lines · David Hildenbrand

Live snapshotting ends up reading all guest memory (dirty bitmap starts with all 1s), which is not what we want for virtio-mem - we don’t want to read and migrate memory that has been discarded and has no stable content.

For ordinary migration we use the guest page hint API to clear bits in the dirty bitmap after dirty bitmap sync. Well, if we don‘t do bitmap syncs we‘ll never clear any dirty bits. That‘s the problem.

Using dirty bitmap for that information is less efficient, becase it's definitely a larger granularity information than PAGE_SIZE. If the disgarded ranges are always continuous and at the end of a memory region, we should have some parameter in the ramblock showing that where we got shrinked then we don't check dirty bitmap at all, rather than always assuming used_length is the one.

They are randomly scattered across the whole RAMBlock. Shrinking/growing will be done to some degree in the future (but it won't get rid of the general sparse layout we can produce).

Quoted 7 lines
Quoted 4 lines

OK. Btw I think currently live snapshot should still be reading dirty bitmap, so maybe it's still fine.  It's just that it's still not very clear to hide virtio-mem information into dirty bitmap, imho, since that's not how we interpret dirty bitmap - which is only for the sake of tracking page changes.

Well, currently it is "what do we have to migrate".

Using dirty bitmap can prohibit unexpected (overwritten) content of pre-discarded pages, but they'll appear as zeroed on destination. What about other virtio-baloon features like HW_POISON when poisoned pages should also be retained on population filled with certain pattern?

Thanks,

Quoted 13 lines
Quoted 2 lines

What's the granule of virtio-mem for this discard behavior? Maybe we could

virtio-mem granularity is at least 1MB. This corresponds to 256 bits (32 bytes) in the dirty bitmap I think.

Quoted 3 lines

decouple it with dirty bitmap some day; if the unit is big enough it's also a gain on efficiency so we skip in chunk rather than looping over tons of pages knowing that they're discarded.

Yeah, it's not optimal having to go over the dirty bitmap to cross off "discarded" parts and later having to find bits to migrate.

At least find_next_bit() can skip whole longs (8 bytes) and is fairly efficient. There is certainly room for improvement (the current guest free page hinting API is certainly a hack).

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#44 lore raw
Quoted 38 lines · Andrey Gruzdev
Quoted 37 lines · David Hildenbrand
Quoted 35 lines · Peter Xu
Quoted 22 lines · David Hildenbrand
Quoted 11 lines · Peter Xu
Quoted 9 lines · David Hildenbrand

Live snapshotting ends up reading all guest memory (dirty bitmap starts with all 1s), which is not what we want for virtio-mem - we don’t want to read and migrate memory that has been discarded and has no stable content.

For ordinary migration we use the guest page hint API to clear bits in the dirty bitmap after dirty bitmap sync. Well, if we don‘t do bitmap syncs we‘ll never clear any dirty bits. That‘s the problem.

Quoted 9 lines

Using dirty bitmap for that information is less efficient, becase it's definitely a larger granularity information than PAGE_SIZE. If the disgarded
ranges are always continuous and at the end of a memory region, we should have
some parameter in the ramblock showing that where we got shrinked then we don't
check dirty bitmap at all, rather than always assuming used_length is the one.

Quoted 4 lines

They are randomly scattered across the whole RAMBlock. Shrinking/growing
will be done to some degree in the future (but it won't get rid of the general sparse layout we can produce).

OK. Btw I think currently live snapshot should still be reading dirty bitmap,
so maybe it's still fine.  It's just that it's still not very clear to hide
virtio-mem information into dirty bitmap, imho, since that's not how we interpret dirty bitmap - which is only for the sake of tracking page changes.

Quoted 4 lines
Quoted 2 lines

Well, currently it is "what do we have to migrate".

Using dirty bitmap can prohibit unexpected (overwritten) content of pre-discarded pages, but they'll appear as zeroed on destination.

To be precise, they'll usually appear as discarded (no pages in the migration stream).

Quoted 2 lines

What about other virtio-baloon features like HW_POISON when poisoned pages should also be retained on population filled with certain pattern?

In case of free page reporting, we skip discarding if poisoning is set to != 0 because of that reason:

if (virtio_balloon_inhibited() || dev->poison_val) {
	goto skip_element;
}
Signature · 3 lines
Thanks,

David / dhildenb
#45 lore raw
Quoted 39 lines · David Hildenbrand
Quoted 38 lines · Andrey Gruzdev
Quoted 37 lines · David Hildenbrand
Quoted 35 lines · Peter Xu
Quoted 22 lines · David Hildenbrand
Quoted 11 lines · Peter Xu
Quoted 9 lines · David Hildenbrand

Live snapshotting ends up reading all guest memory (dirty bitmap starts with all 1s), which is not what we want for virtio-mem - we don’t want to read and migrate memory that has been discarded and has no stable content.

For ordinary migration we use the guest page hint API to clear bits in the dirty bitmap after dirty bitmap sync. Well, if we don‘t do bitmap syncs we‘ll never clear any dirty bits. That‘s the problem.

Quoted 9 lines

Using dirty bitmap for that information is less efficient, becase it's definitely a larger granularity information than PAGE_SIZE. If the disgarded
ranges are always continuous and at the end of a memory region, we should have
some parameter in the ramblock showing that where we got shrinked then we don't
check dirty bitmap at all, rather than always assuming used_length is the one.

Quoted 4 lines

They are randomly scattered across the whole RAMBlock. Shrinking/growing
will be done to some degree in the future (but it won't get rid of the general sparse layout we can produce).

OK. Btw I think currently live snapshot should still be reading dirty bitmap,
so maybe it's still fine.  It's just that it's still not very clear to hide
virtio-mem information into dirty bitmap, imho, since that's not how we interpret dirty bitmap - which is only for the sake of tracking page changes.

Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

Well, currently it is "what do we have to migrate".

Using dirty bitmap can prohibit unexpected (overwritten) content of pre-discarded pages, but they'll appear as zeroed on destination.

To be precise, they'll usually appear as discarded (no pages in the migration stream).

I just mean the retained content of the page after population - zeroes.

Quoted 10 lines
Quoted 3 lines

What about other virtio-baloon features like HW_POISON when poisoned pages should also be retained on population filled with certain pattern?

In case of free page reporting, we skip discarding if poisoning is set to != 0 because of that reason:

if (virtio_balloon_inhibited() || dev->poison_val) { goto skip_element;
}

Got it, thanks.

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#46 lore raw
In reply to Peter Xu
Quoted 28 lines · Peter Xu

Andrey,

Quoted 2 lines · Andrey Gruzdev

For the discards that happen before snapshot is started, I need to dig into Linux and QEMU virtio-baloon code more to get clear with it.

Yes it's very tricky on how the error could trigger.

Let's think of below sequence:

- Start a guest with init_on_free=1 set and also a virtio-balloon device

- Guest frees a page P and zeroed it (since init_on_free=1). Now P contains all zeros.

- Virtio-balloon reports this page to host, MADV_DONTNEED sent, then this page is dropped on the host.

- Start live snapshot, wr-protect all pages (but not including page P because it's currently missing). Let's call it $SNAPSHOT1.

- Guest does alloc_page(__GFP_ZERO), accidentally fetching this page P and returned

- So far, page P is still all zero (which is good!), then guest uses page P and writes data to it (say, now P has data P1 rather than all zeros).

- Live snapshot saves page P, which content P1 rather than all zeros.

Quoted 8 lines

- Live snapshot completed. Saved as $SNAPSHOT1.

Then when load snapshot $SNAPSHOT1, we'll have P contains data P1. After snapshot loaded, when guest allocate again with alloc_page(__GFP_ZERO) on this page P, since guest kernel "thought" this page is all-zero already so memzero() is skipped even if __GFP_ZERO is provided. Then this page P (with content P1) got returned for the alloc_page(__GFP_ZERO) even if __GFP_ZERO set. That could break the caller of alloc_page().

Yep, that's quite clear.

Quoted 7 lines
Quoted 2 lines

Anyhow I'm quite sure that adding global MISSING handler for snapshotting is too heavy and not really needed.

UFFDIO_ZEROCOPY installs a zero pfn and that should be all of it. There'll definitely be overhead, but it may not be that huge as imagined. Live snapshot is great in that we have point-in-time image of guest without stopping the guest, so taking slightly longer time won't be a huge loss to us too.

Quoted 9 lines

Actually we can also think of other ways to work around it. One way is we can pre-fault all guest pages before wr-protect. Note that we don't need to write to the guest page because read would suffice, since uffd-wp would also work with zero pfn. It's just that this workaround won't help on saving snapshot disk space, but it seems working. It would be great if you have other workarounds, maybe as you said UFFDIO_ZEROCOPY is not the only route.

Thanks,

Just to add: one of the good options is too keep track of virtio-baloon discarded pages and pre-fault them before migration starts. What do you think?

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#47 lore raw
Quoted 14 lines
Quoted 14 lines
Quoted 2 lines

Anyhow I'm quite sure that adding global MISSING handler for snapshotting is too heavy and not really needed.

UFFDIO_ZEROCOPY installs a zero pfn and that should be all of it. There'll definitely be overhead, but it may not be that huge as imagined. Live snapshot is great in that we have point-in-time image of guest without stopping the guest, so taking slightly longer time won't be a huge loss to us too.

Actually we can also think of other ways to work around it. One way is we can pre-fault all guest pages before wr-protect. Note that we don't need to write to the guest page because read would suffice, since uffd-wp would also work with zero pfn. It's just that this workaround won't help on saving snapshot disk space, but it seems working. It would be great if you have other workarounds, maybe as you said UFFDIO_ZEROCOPY is not the only route.

Quoted 4 lines
Quoted 2 lines

Thanks,

Just to add: one of the good options is too keep track of virtio-baloon discarded pages and pre-fault them before migration starts. What do you think?

Just pre-fault everything and inhibit the balloon. That should work.

Signature · 3 lines
Thanks,

David / dhildenb
#48 lore raw
Quoted 14 lines · David Hildenbrand
Quoted 14 lines
Quoted 14 lines
Quoted 2 lines

Anyhow I'm quite sure that adding global MISSING handler for snapshotting is too heavy and not really needed.

UFFDIO_ZEROCOPY installs a zero pfn and that should be all of it.  There'll definitely be overhead, but it may not be that huge as imagined.  Live snapshot is great in that we have point-in-time image of guest without stopping the guest, so taking slightly longer time won't be a huge loss to us too.

Actually we can also think of other ways to work around it. One way is we can pre-fault all guest pages before wr-protect.  Note that we don't need to write to the guest page because read would suffice, since uffd-wp would also work with zero pfn.  It's just that this workaround won't help on saving snapshot disk space, but it seems working.  It would be great if you have other workarounds, maybe as you said UFFDIO_ZEROCOPY is not the only route.

Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

Thanks,

Just to add: one of the good options is too keep track of virtio-baloon discarded pages and pre-fault them before migration starts. What do you think?

Just pre-fault everything and inhibit the balloon. That should work.

Yep.

Signature · 3 lines
Andrey Gruzdev, Principal Engineer
Virtuozzo GmbH  +7-903-247-6397
                virtuzzo.com
#49 lore raw
In reply to Andrey Gruzdev
Quoted 58 lines · Andrey Gruzdev
Quoted 48 lines · David Hildenbrand
Quoted 21 lines · andrey.gruzdev--- via

This patch series is a kind of 'rethinking' of Denis Plotnikov's ideas he's
implemented in his series '[PATCH v0 0/4] migration: add background snapshot'.

Currently the only way to make (external) live VM snapshot is using existing
dirty page logging migration mechanism. The main problem is that it tends to
produce a lot of page duplicates while running VM goes on updating already
saved pages. That leads to the fact that vmstate image size is commonly several
times bigger then non-zero part of virtual machine's RSS. Time required to
converge RAM migration and the size of snapshot image severely depend on the
guest memory write rate, sometimes resulting in unacceptably long snapshot
creation time and huge image size.

Quoted 13 lines

This series propose a way to solve the aforementioned problems. This is done
by using different RAM migration mechanism based on UFFD write protection
management introduced in v5.7 kernel. The migration strategy is to 'freeze'
guest RAM content using write-protection and iteratively release protection
for memory ranges that have already been saved to the migration stream. At the same time we read in pending UFFD write fault events and save those
pages out-of-order with higher priority.

Hi,

just stumbled over this, quick question:

I recently played with UFFD_WP and notices that write protection is only effective on pages/ranges that have already pages populated (IOW:
!pte_none() in the kernel).

In case memory was never populated (or was discarded using e.g., madvice(DONTNEED)), write-protection will be skipped silently and you won't get WP events for applicable pages.

Quoted 9 lines

So if someone writes to a yet unpoupulated page ("zero"), you won't get WP events.

I can spot that you do a single uffd_change_protection() on the whole RAMBlock.

How are you handling that scenario, or why don't you have to handle that scenario?

Quoted 8 lines

Hi David,

I really wonder if such a problem exists.. If we are talking about a write to an unpopulated page, we should get first page fault on non-present page and populate it with protection bits from respective vma. For UFFD_WP vma's  page will be populated non-writable. So we'll get another page fault on present but read-only page and go to handle_userfault.

Hi,

here is another fun issue.

Assume you

1. Have a populated page, with some valuable content
2. WP protected the page
3. madvise(DONTNEED) that page
4. Write to the page

On write access, you won't get a WP event!

Instead, you will get a UFFD_EVENT_REMOVE during 3. But you cannot stop that event (dont wake), so you cannot simply defer as you can do with WP events.

So if the guest inflates the balloon (including balloon page migration in Linux) or free-page-reporting reports a free page while snapshotting is active, you won't be able to save the old content before it is zapped and your snapshot misses pages with actual content.

Something similar would happen with virtio-mem when unplugging blocks, however, it does not discard any pages while migration is active.

Snapshotting seems to be incompatible with concurrent discards via virtio-balloon. You might want to inhibit ballooning while snapshotting is active in

hw/virtio/virtio-balloon.c:virtio_balloon_inhibited() just as we do for postcopy.

Signature · 3 lines
Thanks,

David / dhildenb