Improve (Reduce) Downtime when Migrating [Tracking Issue]

オープン
#8,899 コメント 2 件 リアクション 0 件 担当者 1 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

@phip1611 がすでに取り組んでいます。

2026年9月18日 から。

評価

この issue はまだ評価されていません。

説明

Legend: 🟢 probably trivial · 🟡 needs some work · 🔴 probably a bigger surgery

Used to track further performance improvements regarding the downtime of a migration. This ticket is part of #7111. Everyone is welcome to pick individual items and work on them!

The general goal is to focus on high impact and low complexity items first.

Measurements and analysis might show that some of these items should not be implemented. In that case just mark it as strike through and add more words in the details section below!

All are outcome of an intense LLM assisted analysis.

  • 1. 🟢 vm-memory optimization:
  • 2. 🟢 remove too much logging in dirty_range() code
    • #8898
  • 3. 🟡 bundle scattered memory ranges: use writev() for sending memory?
    • #8944
  • 4. 🟡 bundle scattered memory ranges: use readv() for receiving memory
    • #8944
  • 5. 🟢 TCP Nagle / TCP NODELAY
    • #8944
  • 6. 🟢 Prevent useless copies in memory range table merging
    • #8898
  • 7. 🟢 Buffer in logger to prevent multiple system calls
    • #8914
  • 8. 🟢 THP lost when prefaulting
    • #8915
  • 9. 🟡 Destination memory could always be prefaulted
  • 10. 🟡 Dirty bitmap converted to ranges one bit at a time
  • 11. 🟢 The final iteration uses a single connection
    • #8943
  • 12. 🟢 get_prefault_num_threads threshold is off by 64x
    • #8785
  • 13. 🟡 RAM and device dirty tables are concatenated
  • 14. 🟢 The final iteration concatenates two dirty sets (instead of merging)
    • #8898

VM state handover:

  • 15. 🟢 Redundant common-CPUID generation while the VM is stopped
    • #8916
  • 16. 🟢 PCI configuration space serialized in full (mostly zeros)
    • #8904
  • 17. 🟡 Every vCPU carries the state all vCPUs have in common
  • 18. 🟡 vCPU states captured and restored one by one
    • #8961
  • 19. 🔴 The destination builds the whole VM inside the downtime
  • 20. 🟢 Serde-heavy crates built for size, not for speed
  • 21. 🔴 The state encoding itself (JSON inside JSON)

Off the critical path:

  • 22. 🟡 Pause/resume of vCPUs polls with 1ms sleeps
  • 23. 🟢 Completion request waits for the destination's restore
  • 24. 🟢 Memory send workers joined while the VM is stopped
  • 25. 🟢 qcow2 metadata flushed during pause
    • #8982

Accounting and budget:

  • 26. 🟢 Downtime breakdown does not add up
  • 27. 🟡 downtime_ms is a budget for the memory delta only (smarter downtime estimation)

Dirty tracking (guest impact during precopy):

  • 28. 🔴 Dirty tracking re-arms the whole slot every iteration

1. AtomicBitmap::get_and_reset() (rust-vmm/vm-memory)

TL;DR: load before swap; the win for idle or huge VMs.

  • fetch_and(0) on every word: cost follows RAM size, not the dirty set
    (~4.3 ns/word).
  • Fix: swap only non-zero words; a bit set in between is either returned by the
    swap or reported next iteration.
  • Gain: 5-19x - 140 us to ~7 us (8 GiB), 1.2 to 0.2 ms (64 GiB), 10 to 1.3 ms
    (512 GiB) per call; 70-80% of userspace dirty-log time when sparse, and two
    calls run while the VM is paused.
  • Related: mark_dirty() is per page; word-at-a-time is 13-70x faster
    (matters for device I/O, not migration).

✅ 2. remove too much logging in dirty_range() code

  • Code is mature, no need to log this as debug
  • consolidate into a single statement
  • Printing provides almost no value, use trace!

✅ 3. Bundle scattered memory ranges (write)

  • Throughput drops significantly for scattered memory ranges in a memory iteration
  • Batching or vectored I/O might make sense

✅ 4. Bundle scattered memory ranges (read)

  • Throughput drops significantly for scattered memory ranges in a memory iteration
  • Batching or vectored I/O might make sense

✅ 5. Nagle stalls

TL;DR: TCP_NODELAY, but only after items 3 and 4.

  • Request/response pattern + delayed ACK = ~40 ms per affected request.
  • Gain: size independent; whenever the last TCP segment cannot be fully be populated

✅ 6. Range tables copied on merge

TL;DR: reuse the largest table's allocation.

  • Merging device tables and the final leftover table reallocates and copies.
  • Gain/iteration: 0.28 ms (8 GiB, 10%), 8.6 ms (64 GiB), 133 ms (512 GiB);
    partly inside downtime.

✅ 7. Per-range logging

TL;DR: log a summary; buffer each record.

  • One line per range, and ~20 write(2) per record (unbuffered, per token).
  • Gain: none at default level; with debug logging a 61k-range iteration spent
    0.55 s logging, more than transferring the same data.

✅ 8. THP lost when prefaulting

TL;DR: MADV_HUGEPAGE before MADV_POPULATE_WRITE.

  • With host policy madvise, pages faulted in before the marking stay 4 KiB.
  • Gain (2 GiB): AnonHugePages 0 to fully backed, prefault 0.34 to 0.10 s.
  • Trade-off: on a fragmented host THP faults compact, prefault up to 2.1 s.

9. Destination memory not always populated for precopy

TL;DR: populate before the transfer, always.

  • Precopy writes every page anyway; with prefault=off they fault in one by
    one during the copy.
  • Precopy only (postcopy needs userfaultfd, MemFD passes descriptors); skip
    file/memfd-backed regions, which may stay sparse.
  • Gain (2 GiB): destination CPU 2.09 to 0.58 s, first iteration 0.9 to
    3.5 GiB/s; less with free huge pages (9.9 to 15.0 GiB/s).

❌ 10. Dirty bitmap converted to ranges one bit at a time

TL;DR: emit whole runs per word and reuse the output buffer.

  • MemoryRangeTable::from_dirty_bitmap walks set bits one at a time and
    coalesces afterwards. Items 1 and 6 cover the stages before and after it,
    not this one.
  • Gain: 64 GiB at 10% dirty 25 to 12 ms, 512 GiB at 100% 171 to 4.6 ms per
    iteration. About 10% slower on sparse random bitmaps, so it is a trade.
  • Rejected: sparse random bitmaps are the norm

✅ 11. The final iteration uses a single connection

TL;DR: partition the final table by connection count, not by 64 MiB.

  • SendAdditionalConnections::CHUNK_SIZE is 64 MiB, so any final iteration
    below that becomes one chunk taken by one worker: connections cannot help
    the phase the VM is stopped for.
  • Related to item 27: at 400k dirty pages/s, four connections measured 43.9 to
    47.5 ms, because the faster link makes precopy converge one iteration
    earlier on a larger delta (380 MiB instead of 201 MiB).

✅ 12. get_prefault_num_threads threshold is off by 64x

TL;DR: the code says 4 GiB, the comment says 64 MiB.

  • page_size * num_pages / (64 * (1 << 26)) is size / 4 GiB, so every region
    below 4 GiB is prefaulted single-threaded. prefault_memory also runs one
    region after the other.
  • Caps item 9: measured 30.6 ms/GiB with THP and 148 ms/GiB without, both
    single-threaded; MADV_POPULATE_WRITE scales to ~2.9x at 8 threads on the
    4 KiB path.

❌ 13. RAM and device dirty tables are concatenated

TL;DR: merge the sources before building ranges.

  • Vm::dirty_log appends the device-manager table to the memory-manager one,
    so a page dirtied by both KVM and a vhost-user or VFIO backend is sent twice,
    with the extra ranges that creates.
  • OR the sources at bitmap level and build the ranges once.
  • How much overlap a real workload produces is not measured yet; a vhost-user
    block backend under sustained I/O is enough to find out.
  • Update: Not important enough right now. Needs more investigation.

✅ 14. The final iteration concatenates two dirty sets (instead of merging)

TL;DR: union the bitmaps instead of concatenating the tables.

  • do_memory_migration concatenates the converged iteration's leftover table
    with a freshly fetched dirty log, so pages dirtied in between are sent twice,
    while the VM is stopped. Measured 1.8% of the union in realistic runs, and
    20-42% when the gap between the two fetches is stretched.

✅ 15. Common CPUID regenerated at snapshot time

TL;DR: reuse what the CPU manager already has.

  • Regenerated from the same config the CPU manager used at VM creation, and
    the sender generates it a second time for the config payload; the call
    queries the hypervisor and patches leaves.
  • Gain: ~0.09 ms of downtime, size independent.
  • The TDX flag differs between the call sites, but TDX snapshots are rejected
    earlier, so the results are identical.

✅ 16. PCI configuration space stored in full

TL;DR: serialize only the non-zero registers.

  • 1024 registers per device, listed twice (registers + writable bits), of
    which a few dozen are used: ~4.2 KiB of the 6.7 KiB a virtio-pci device
    contributes; a 16-disk guest spends ~29% of its state on this.
  • Compatible: full-list snapshots are still restored.

17. Identical vCPU state carried per vCPU

TL;DR: carry the common part once, the deltas per vCPU.

  • 44 of 58 CPUID entries and 132 of 144 MSRs are identical on every vCPU; at
    200 vCPUs the CPUID entries alone are 891 KB of a 3.4 MB state, all of it
    serialized, sent, parsed and applied while the VM is stopped.
  • Entries are matched by CPUID function/index and MSR index on merge, never
    positionally; only applied when all vCPUs carry the same set of entries.
  • Gain (200 vCPUs): state 3.45 to 1.71 MB, state handover 45-49 to 37-41 ms.
  • Compatible: snapshots without a shared state restore unchanged.

✅ 18. vCPU states captured and restored serially

TL;DR: fan both directions out over the host's cores.

  • Work per vCPU is independent: ~14 ms of capture on the source and ~16 ms of
    deserialization on the destination at 200 vCPUs.
  • Deserialize all states before creating any vCPU, so creation and applying
    stay in vCPU order (the ioctls serialize in the kernel, and KVM_SET_LAPIC
    rebuilds a VM-wide structure per call).
  • Gain (idle 200 vCPUs, 4-core host): capture 14.5 to 6.6-8.3 ms.

19. The destination builds the whole VM inside the downtime

TL;DR: construct at Config time, apply the state at State time.

  • vm_receive_state creates the device manager, every device, the memslots
    (allocate_address_space, reached from Vm::hypervisor_specific_init) and
    the vCPUs only after the state arrived, although all of it is config-driven
    and needs nothing from the snapshot.
  • Measured: ~38 ms of the 86 ms downtime at 200 vCPUs; 0.19-0.21 ms per virtio
    device, so 16 disks add 5-6 ms; 23.5 us per KVM_CREATE_VCPU; memslots
    7.5 us per region plus 2.14 us/GiB for the KVM dirty bitmap.
  • The largest remaining downtime item at scale, and what makes items 17 and 18
    pay off fully.

❌ 20. Serde-heavy crates built for size, not for speed

TL;DR: opt-level = 3 for the crates that serialize the VM state.

  • The workspace ships opt-level = "s". Overriding it for serde_json,
    serde, hypervisor, vmm, pci, virtio-devices and vm-migration
    measured 84 to 69 ms downtime at 200 vCPUs: capture 14.45 to 8.95 ms,
    serialize 4.48 to 3.11 ms, destination handover 45.3 to 41.3 ms.
  • Cost: +1.07 MiB release binary (6.24 to 7.36 MB) and +29% build time. No
    behaviour change and no compatibility risk.
  • Below ~64 vCPUs it buys nothing measurable. serde_json alone is only a
    third of the gain: the derived impls live in the crates owning the types.
  • Not worth it: adds more than 1 MiB to the crate size, and binary serialization
    (item 21) might be the better replacement.

21. The state encoding itself

TL;DR: JSON inside JSON; a binary encoding is 6.8x faster.

  • Items 16 and 17 shrink what is in the state, this is how it is written.
    SnapshotData { state: String } embeds each component's JSON in a JSON
    string: +24% round-trip CPU and +9% bytes.
  • bincode measured 6.8x faster and 3.4x smaller: 29.6 to 4.3 ms of serde at
    200 vCPUs. At that size serde is about 6x the cost of all KVM vCPU state
    ioctls together.
  • Both change the wire format and need a negotiated state-format version, so
    this is the expensive end of the list.

22. vCPU pause/resume polls an atomic

TL;DR: condvar instead of a 1 ms sleep loop.

  • vCPUs acknowledge within microseconds; source pause and destination resume
    each paid ~1 ms of sleep granularity, ~2 ms per migration - more than half
    the downtime of a small guest.
  • Retry/timeout behavior is preserved (signal every 10 ms, give up at 1000 ms).
  • Gain (idle 2 GiB, TCP): 4 to 1 ms (1 vCPU), 6 to 3-5 ms (8 vCPUs); at
    200 vCPUs the completion step 32 to 9-19 ms.

23. Completion request serialized behind the restore

TL;DR: pipeline it with the state request.

  • The destination answers the state request only after restoring, so the
    source waited, then spent another round trip asking to complete.
  • Send both back to back, collect both responses; the destination processes
    them in order. A failing restore still reports on the state request and
    drops the connection with the pipelined request unread.
  • Gain: one round trip - negligible on loopback, dominant on a real link.

24. Send workers joined inside the downtime

TL;DR: join after the destination acknowledged completion.

  • The join only tells already-finished threads to exit, so it has no reason
    to be on the critical path.
  • Gain: 21 us per connection, 0.13-0.23 ms with four.
  • Not worth it for now: 0.13-0.23 ms does not pay for restructuring the paused
    phase around it.

✅ 25. qcow2 metadata flushed while the VM is stopped

TL;DR: flush the images once precopy converged, before pausing.

  • Pausing a block device flushes cached format metadata; for qcow2 that is a
    full sync, so everything the guest dirtied is written back during pause.
  • Gain: 16 disks with 16 MiB dirty metadata each, 172 ms - an order of
    magnitude more than the rest of the downtime together. Raw images are
    unaffected.
  • The pre-flush is best-effort; the flush during pause is the one that must
    succeed.

26. Downtime breakdown does not add up

TL;DR: report the pause step, derive the rest, print two decimals.

  • Pausing the VM and releasing the disk locks belonged to no step: ~30% of an
    idle guest's downtime was unexplained, and truncation to whole milliseconds
    hid the remainder (3.95 ms printed as "3ms").
  • Now at info level - one line per migration, and the reason to look at the
    log at all.

27. downtime_ms budgets the memory delta, not the downtime (smarter downtime estimation)

TL;DR: subtract the estimated state handover from the budget.

  • Convergence compared only the final memory delta against the request: over
    60 migrations the achieved downtime exceeded the estimate in 55, median
    4 ms. The code assumed ~5 ms of overhead for 1-200 vCPUs; an idle guest
    measures ~80 ms, which is then the whole downtime.
  • Estimate from vCPU and device count - coarse on purpose. Log when the
    requested downtime is below the estimate, i.e. precopy cannot meet it.
Proposed patch (vmm: migration: reserve the VM state handover in the downtime budget)
diff --git a/vmm/src/lib.rs b/vmm/src/lib.rs
index bf713fab8..f76ce9984 100644
--- a/vmm/src/lib.rs
+++ b/vmm/src/lib.rs
@@ -1540,7 +1540,8 @@ fn do_memory_iterations(
     ///    bytes.
     /// 2. **Downtime budget is met** – the estimated downtime for the final
     ///    (paused) iteration is within the caller-specified
-    ///    [`VmSendMigrationData::downtime`] budget.
+    ///    [`VmSendMigrationData::downtime`] budget, minus `fixed_downtime`,
+    ///    the part of the downtime that does not depend on the memory delta.
     /// 3. **Timeout** – the precopy phase has been running for at least
     ///    [`VmSendMigrationData::timeout`]. The outcome depends on
     ///    [`VmSendMigrationData::timeout_strategy`]:
@@ -1561,31 +1562,31 @@ fn do_memory_iterations(
     fn is_precopy_converged(
         ctx: &MemoryMigrationContext,
         send_data_migration: &VmSendMigrationData,
+        fixed_downtime: Duration,
     ) -> result::Result<bool, MigratableError> {
         if ctx.current_iteration_total_bytes == 0 {
             debug!("Precopy: No more memory to transfer");
             return Ok(true);
         }
 
-        // We currently ignore the time required to transfer the final
-        // VM state (device state and vCPUs) and the time needed on the
-        // receiver to create the VM and initialize its data structures
-        // before execution can resume.
-        //
-        // Manual testing showed that migrating an idle VM on a modern
-        // AMD CPU (CHV release build) adds ~5 ms of overhead when
-        // scaling from 1 to 200 vCPUs. Given this small cost, we
-        // deliberately avoid additional heuristics to estimate the
-        // downtime more precisely - for now. Instead, we approximate
-        // the downtime just by the transfer time of the final memory
-        // delta.
+        // Transferring the final memory delta is only one part of the
+        // downtime: the VM also has to be paused, its state captured, sent,
+        // restored and resumed. That part does not depend on the memory
+        // delta, so it is subtracted from the budget rather than estimated
+        // from the transfer.
+        let budget = send_data_migration
+            .downtime()
+            .saturating_sub(fixed_downtime);
         if let Some(memory_downtime) = ctx.estimated_downtime
-            && memory_downtime <= send_data_migration.downtime()
+            && memory_downtime <= budget
         {
             debug!(
-                "Precopy: Target downtime can be met: {}ms <= {}ms",
-                memory_downtime.as_millis(),
-                send_data_migration.downtime().as_millis()
+                "Precopy: Target downtime can be met: {:.2}ms <= {:.2}ms ({:.2}ms of the \
+                 {}ms budget is needed for the VM state)",
+                memory_downtime.as_secs_f64() * 1000.0,
+                budget.as_secs_f64() * 1000.0,
+                fixed_downtime.as_secs_f64() * 1000.0,
+                send_data_migration.downtime().as_millis(),
             );
             return Ok(true);
         }
@@ -1618,6 +1619,29 @@ fn is_precopy_converged(
         Ok(false)
     }
 
+    /// Estimates the part of the downtime that is not the final memory
+    /// transfer: pausing the VM, capturing its state, sending it, and
+    /// restoring and resuming it on the destination.
+    ///
+    /// This cost grows with the number of vCPUs and devices and does not
+    /// depend on the guest memory size. The factors are derived from
+    /// migrating idle guests over TCP, where the final memory iteration is
+    /// empty, and are deliberately kept simple: a rough estimate is much
+    /// closer to the truth than ignoring the cost altogether.
+    fn estimate_fixed_downtime(vm: &Vm) -> Duration {
+        /// What a migration costs even for a single vCPU without devices.
+        const BASE: Duration = Duration::from_micros(1500);
+        /// Per vCPU: mostly capturing, serializing and restoring its state.
+        const PER_VCPU: Duration = Duration::from_micros(400);
+        /// Per device: mostly re-creating it on the destination.
+        const PER_DEVICE: Duration = Duration::from_micros(300);
+
+        let vcpus = vm.get_config().lock().unwrap().cpus.boot_vcpus;
+        let devices = vm.device_tree().lock().unwrap().iter().count();
+
+        BASE + PER_VCPU * vcpus + PER_DEVICE * devices as u32
+    }
+
     /// Performs precopy memory migration including multiple iterations.
     ///
     /// This includes:
@@ -1639,12 +1663,25 @@ fn do_memory_migration(
         let mut mem_ctx = MemoryMigrationContext::new();
 
         vm.start_dirty_log()?;
+
+        let fixed_downtime = Self::estimate_fixed_downtime(vm);
+        if fixed_downtime >= send_data_migration.downtime() {
+            warn!(
+                "Target downtime of {}ms is below the estimated {:.2}ms needed to hand over \
+                 the VM state: precopy continues until no memory is left to transfer or the \
+                 timeout of {}s is reached",
+                send_data_migration.downtime().as_millis(),
+                fixed_downtime.as_secs_f64() * 1000.0,
+                send_data_migration.timeout().as_secs(),
+            );
+        }
+
         let remaining = Self::do_memory_iterations(
             vm,
             socket,
             &mut mem_ctx,
             // We bind send_data_migration to the callback
-            |ctx| Self::is_precopy_converged(ctx, send_data_migration),
+            |ctx| Self::is_precopy_converged(ctx, send_data_migration, fixed_downtime),
             mem_send,
         )?;
         let downtime_begin = Instant::now();

28. Dirty tracking re-arms the whole slot every iteration

TL;DR: KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 with INITIALLY_SET and a lazy
per-chunk clear.

  • Splitting harvest from re-arming buys no ioctl time by itself: GET + CLEAR
    is within 5% of a legacy GET. The value is elsewhere:
    • start_dirty_log 4-5 ms/GiB to ~0.1 ms, i.e. ~34 ms at 8 GiB and
      270-340 ms at 64 GiB, paid before iteration 0 starts.
    • mmu_lock held per cleared chunk (~1.5 ms/GiB) instead of once for the
      whole slot (~0.1 s at 64 GiB mostly dirty), during which vCPU faults block.
    • Fewer pages protected and re-dirtied: the guest pays 260 ns per re-dirtied
      page, about 68 ms of vCPU time per re-dirtied GiB.
  • What it really targets is invisible today: 103-367 ms of guest stall
    accumulated during a precopy phase, against 0-102 ms in a matched baseline
    window. No metric reports this.
  • Pitfalls: clear before copying a page, clear only bits that are actually
    sent, every GET needs a matching CLEAR, and INITIALLY_SET returns all ones
    on the first GET. MSHV would need a no-op clear_dirty_log.
  • Alternative for sparse dirtying on huge VMs: the dirty ring, which is
    mutually exclusive with the bitmap ioctls on x86.
  • Scope: this improves guest impact during precopy and the time before the
    first iteration, more than the downtime itself.
主要言語
Rust
スター
6.3k
フォーク
786
平均マージ
1日 3時間
マージ済み PR(30日)
195

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

cloud-hypervisor/cloud-hypervisor のほかの issue

cloud-hypervisor/cloud-hypervisor の issue をすべて見る

似ている issue

Rust の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。