The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(vmm): restore split VM state and RAM snapshots via Vm::from_state (#2985)
lfld287dc427c822193
diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.mdindex 233a93075..3185fd368 100644--- a/docs/contributing/architecture/vmm/README.md+++ b/docs/contributing/architecture/vmm/README.md@@ -450,8 +450,8 @@ worker slot synchronously.- **vCPU threads.**- `run()` spawns one per vCPU, named `vcpuN`. Each creates and configures its- vCPU and waits at a start gate until every vCPU is configured; a thread- that fails to start aborts the gate.+ vCPU and waits at a start gate until the driver allows guest entry.+ A spawn or setup failure aborts the gate.- Before each guest entry, a vCPU checks the pause and stop state. It waitson a condition variable while parked.- When the VM is running, idle vCPUs wait inside the host. KVM's in-kernel@@ -485,8 +485,12 @@ worker slot synchronously.buffered network traffic.- **The `run()` thread.**- It waits on one `EventLoop` poller for control wakeups, stop requests,- vCPU outcomes and device failures. The `RECHECK` interval is one second,- so the mailbox and terminal queue are revisited even if a wakeup is lost.+ vCPU outcomes and device failures. During vCPU setup, the same loop+ processes control requests and retries kicks. The last ready vCPU wakes+ the poller; the loop checks terminal events and processes pending pause+ requests before opening the start gate. The `RECHECK` interval is one+ second, so the mailbox and terminal queue are revisited even if a wakeup+ is lost.- The poller is `mio`, which uses epoll on Linux and kqueue on macOS and isalready in `Cargo.lock` through tokio. rust-vmm's event-manager and crosvm's`WaitContext` are epoll-only.@@ -640,6 +644,36 @@ after creating a file, `boxlite-vmm` leaves it in place, even if partiallywritten. The caller (runtime or runner) is responsible for cleanup, for exampleby exporting into a temporary directory and atomically renaming it on success.+### Snapshot restore++On Linux x86_64, `Vm::from_state(state_path, memory_path)` opens the two files+produced by `VmControl::export`. It validates the v1 header, vCPU and IRQ chip+order, RAM layout, and KVM GPA limit. Each file must end at its declared+payload boundary. The constructor streams the RAM image into anonymous+mappings, creates the host VM, and registers the mappings. A successful+import returns a device-less VM in `Created`.++`Vm::run` installs the saved machine state in order.++1. The driver calls `restore_before_vcpus` to restore the VM clock before it+ starts the vCPU threads.+2. Each vCPU owner creates its vCPU, calls `restore_state` with the saved CPU+ state, and calls `notify_guest_stopped` to notify the guest clock. It then+ waits at the start gate.+3. The driver handles queued terminal events first. Once every vCPU is ready,+ if the stop latch is clear, the driver calls `restore_after_vcpus` to restore+ the IRQ chips and PIT. Only success opens the gate for guest entry.++A setup failure aborts guest entry. The driver joins every started vCPU and+publishes `Exited`. A `control.request_pause()` reservation made in `Created` keeps+guest entry closed through `Paused` until `control.resume()`.++On Linux x86_64 with read/write `/dev/kvm`, `make test:integration:vmm:kvm`+exercises flat-guest restore, including a 3073 MiB snapshot across the+32-bit MMIO hole. `make test:integration:vmm:linux` uses `VMM_KERNEL` for the+Linux restore round trip. `make coverage:vmm:kvm` and `make coverage:vmm:boot`+exercise the same restore paths under coverage.+### Where the engine plugs in (M2)- **Engine choice.** The `native-vmm` experimental token gates@@ -843,7 +877,8 @@ The kernel then boots itself (Linux v6.12):- vCPU registers, interrupt-controller state (`hv_gic_state_*` on HVF, vgicattributes on KVM) and device state are plain data. They are serialisedwith serde, as in all four surveyed VMMs that take snapshots.- - A restore maps the memory file copy-on-write through `map_memory`.+ - Device snapshots plan to map the memory file copy-on-write through+ `map_memory`.- **M9, GPU.**- BoxLite's own devices stay on virtio-mmio.- A PCI transport serves only passed-through devices, in the ECAM and BARdiff --git a/make/coverage.mk b/make/coverage.mkindex 317c270e3..c9571b38b 100644--- a/make/coverage.mk+++ b/make/coverage.mk@@ -71,13 +71,12 @@ coverage\:report:# Codecov enforces patch coverage against the PR base; total coverage is reported.codecov: coverage\:lcov-# Add real KVM execution to the unit profiles before the CI upload. The CI-# profile bounds each test; disabling retries preserves the first failure. Every-# passing test is listed by name, so the CI log shows which hardware tests ran.+# Add real KVM execution before the CI upload. The vm profile allows time for+# the 3073 MiB split-RAM round trip. List each passing test and disable retries.coverage\:vmm\:kvm: _ensure-kvm- @cargo llvm-cov nextest --no-report --no-tests=fail --profile ci --retries 0 --status-level pass \+ @cargo llvm-cov nextest --no-report --no-tests=fail --profile vm --retries 0 --status-level pass \-p boxlite-hypervisor -p boxlite-vmm --lib --run-ignored only --test-threads=1 \- -E '(package(boxlite-hypervisor) & test(/^kvm::/)) | (package(boxlite-vmm) & (test(/^vm::tests::/) | test(tests::kvm::) | test(snapshot::execution_tests::kvm_)))'+ -E '(package(boxlite-hypervisor) & test(/^kvm::/)) | (package(boxlite-vmm) & ((test(/^vm::tests::/) | test(tests::kvm::) $(foreach test,$(VMM_KVM_SNAPSHOT_TESTS),| test($(test)))) - test($(VMM_LINUX_SNAPSHOT_TESTS))))'@cargo llvm-cov report $(COVERAGE_REPORT_ARGS) --lcov --output-path target/coverage/lcov.info# Add the real-kernel boots of VMM_KERNEL to the same profiles, listed the same way.@@ -85,7 +84,7 @@ coverage\:vmm\:kvm: _ensure-kvmcoverage\:vmm\:boot: export VMM_GUEST_MOUNT_INIT := $(PROJECT_ROOT)/target/vmm/guest-mount/x86_64-unknown-linux-musl/release/boxlite-guestcoverage\:vmm\:boot: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT) $(VMM_DISK_GROW_INIT) $(VMM_HOTPLUG_INIT) vmm\:guest-mount-init@cargo llvm-cov nextest --no-report --no-tests=fail --profile ci --retries 0 --status-level pass \- -p boxlite-vmm --lib --run-ignored only --test-threads=1 -E 'test(boot::tests::)'+ -p boxlite-vmm --lib --run-ignored only --test-threads=1 -E 'test(boot::tests::) | test($(VMM_LINUX_SNAPSHOT_TESTS))'@cargo llvm-cov report $(COVERAGE_REPORT_ARGS) --lcov --output-path target/coverage/lcov.infoGO_SDK_COVERAGE_TAGS ?= boxlite_runnerdiff --git a/make/test.mk b/make/test.mkindex 4689b72bf..6df2bc8e7 100644--- a/make/test.mk+++ b/make/test.mk@@ -305,11 +305,15 @@ _ensure-kvm:# Run the ignored hardware tests explicitly and bound a stalled guest with a timeout.# Both crates run even when one fails, so one report shows every result.+VMM_KVM_TESTS_TIMEOUT ?= 600s+VMM_KVM_SNAPSHOT_TESTS := snapshot::tests::execution::kvm_ snapshot::tests::restore::kvm_+VMM_LINUX_SNAPSHOT_TESTS := snapshot::tests::restore::kvm_linux_+test\:integration\:vmm\:kvm: _ensure-kvm@cargo test -p boxlite-hypervisor -p boxlite-vmm --lib --no-run@status=0; \timeout 60s cargo test -p boxlite-hypervisor --lib kvm:: -- --ignored --test-threads=1 || status=1; \- timeout 60s cargo test -p boxlite-vmm --lib -- --ignored --test-threads=1 vm::tests:: tests::kvm:: snapshot::execution_tests::kvm_ || status=1; \+ timeout $(VMM_KVM_TESTS_TIMEOUT) cargo test -p boxlite-vmm --lib -- --ignored --test-threads=1 vm::tests:: tests::kvm:: $(VMM_KVM_SNAPSHOT_TESTS) --skip $(VMM_LINUX_SNAPSHOT_TESTS) || status=1; \exit $$status# make vmm:boot produces this kernel by default.@@ -354,7 +358,7 @@ VMM_BOOT_TESTS_TIMEOUT ?= 900s# init restarts, once through the public Vm::new as the M1 smoke test.test\:integration\:vmm\:linux: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT) $(VMM_DISK_GROW_INIT) $(VMM_HOTPLUG_INIT)@cargo test -p boxlite-vmm --lib --no-run- @timeout $(VMM_BOOT_TESTS_TIMEOUT) cargo test -p boxlite-vmm --lib boot::tests:: -- --ignored --test-threads=1 --nocapture --skip boot::tests::guest_mounts::+ @timeout $(VMM_BOOT_TESTS_TIMEOUT) cargo test -p boxlite-vmm --lib -- --ignored --test-threads=1 --nocapture boot::tests:: $(VMM_LINUX_SNAPSHOT_TESTS) --skip boot::tests::guest_mounts::# Exercise the production guest mount adapter inside a real initramfs guest.PHONY_TARGETS += test\:integration\:vmm\:mountsdiff --git a/src/vmm/README.md b/src/vmm/README.mdindex 37cbca505..6db1d65dc 100644--- a/src/vmm/README.md+++ b/src/vmm/README.md@@ -37,12 +37,12 @@ boxlite-vmm| `vm` | `Vm<H>`: validate the configuration, allocate and register RAM on host backend `H`, compose the devices through `build` and `devices::add_all`, load the boot data, and run the vCPUs until the first event; `with_backend` is the test seam || `control` | `VmControl` provides runtime controls for VM status, pause, resume, export, stop, and `resize_disk` by configured ID || `lifecycle` | `Lifecycle` coordinates the one-shot run, pause epochs, the control mailbox, and the shared stop latch |-| `snapshot` | Captures and exports machine state and raw guest RAM for paused device-less VMs on Linux x86_64 || `boot` | Linux x86_64 boot: `prepare` loads the pinned ELF kernel through linux-loader, places an optional initramfs at the top of low RAM, writes the zero page, E820 map, command line and MP table, and sets up the 64-bit entry state (GDT, identity page tables, registers) || `config` | `VmConfig`: CPU, RAM, kernel and initramfs, disks, optional filesystem/vsock/network, and virtio console; 1..=64 vCPUs, nonzero `u32` MiB of RAM whose layout must pass host and boot address checks, a printable-ASCII command line under 2048 bytes, and at most 8 disks || `error` | VMM errors that keep the hypervisor's cause chain, including a virtio device that cannot continue || `memory` | `GuestRam`: owned guest RAM, the RAM layout, and the registration lifetime rules || `hotplug` | `HotplugMemory` places a window after boot RAM, plugs 2 MiB blocks and maps 128 MiB slots |+| `snapshot` | Linux x86_64 device-less snapshot export and restore, including machine state and packed boot RAM || `cpu_features` | x86_64 guest-memory capability preflight, CPUID for each vCPU, and the boot MSRs || `vcpu` | x86_64 vCPU workers create and configure each vCPU, hold them at a start gate, check for pause or stop before guest entry, and dispatch guest exits || `chipset` | `ChipsetBuilder`, the one registry of ranges and interrupt lines, and `Chipset`, the read-only machine it builds |@@ -690,12 +690,14 @@ it registers any RAM, `Vm::with_backend` builds the `Chipset` from thedevices it is given, so a conflict fails with `ChipsetConflicts` and leavesnothing mapped.-1. It starts one scoped thread per vCPU, named `vcpuN`. Each creates its vCPU,- sets its CPUID from `vcpu_cpuid` and the boot MSRs, and on vCPU 0 the entry- registers, then waits at a start gate until every vCPU is configured. A- vCPU that fails setup sends `VcpuFailed` before it arrives, so the latch- keeps every vCPU out of the guest, and a thread that fails to start aborts- the gate, so no worker waits forever.+1. It starts one scoped thread per vCPU, named `vcpuN`. On boot each thread+ sets its CPUID and boot MSRs, and vCPU 0 also sets the entry registers.+ On restore the thread installs the saved state. Each waits at the start+ gate until the driver allows guest entry. The driver handles pause, stop,+ and kick retries in the event loop during setup. The last ready vCPU wakes+ the loop, and the driver handles queued terminal events and pending pause+ requests before opening the gate. A spawn or setup failure sets the stop+ latch and aborts the gate.2. Before each guest entry, the worker calls `checkpoint` and checks the stoplatch. To park, it calls `complete_pending_io` and dispatches each`Ok(IoCompletion::Exit(exit))` until completion returns `Ok(IoCompletion::Done)`.@@ -709,7 +711,7 @@ nothing mapped.drains pending I/O and preserves the latched outcome.3. `EventSender::send` sets the stop latch before it queues, so the vCPUthat sends, such as the one whose `0xFE` reached the i8042, never enters- the guest again. `run` takes the first event from the `EventLoop`, opens+ the guest again. `run` takes the first event from the `EventLoop`, abortsthe start gate for teardown, releases and kicks the vCPUs, and joins themall before it returns. Before joining, shutdown retries kicks that failwith `WouldBlock` or `Interrupted`, including when the terminal event@@ -785,6 +787,33 @@ Raw RAM starts at offset zero and follows guest physical address order,skipping the `[3 GiB, 4 GiB)` PCI hole. Machine state targets the same hostand KVM environment.+### Restoring a snapshot++On Linux x86_64, `Vm::from_state(state_path, memory_path)` imports the files+written by `control.export(state_path, memory_path)`. The constructor checks+the exact file boundaries, machine state, and KVM GPA limit. It loads and+registers RAM and returns a device-less VM in `Created`. Image I/O, host VM+creation, and RAM registration errors are returned by the constructor.++During `vm.run()`, the driver calls `restore_before_vcpus` before starting+the vCPU threads. Each vCPU calls `restore_state` and `notify_guest_stopped`+on its owning thread. The event loop calls `restore_after_vcpus` when all vCPUs+are ready at the start gate and no stop is pending. Only success opens the gate.+A setup error keeps the guest from entering, and `run()` returns the error+after joining every started vCPU and publishing `Exited`.++To inspect or re-export the restored state before guest entry, reserve a+pause with `control.request_pause()` while the VM is in `Created`. Start `vm.run()`+on the VM owner thread and use `control.wait_paused(timeout)` from a control+thread. Call `control.resume()` when the guest can enter.++On Linux x86_64 with read/write `/dev/kvm`, run+`make test:integration:vmm:kvm` for flat-guest round trips, including the+3073 MiB split-RAM case, which writes the full 3073 MiB RAM file and state+file under the temporary directory and requires matching free temporary disk+space. Run `make test:integration:vmm:linux` with `VMM_KERNEL` set to a readable+`vmlinux` for the Linux round trip.+## Long-mode entryOn Linux x86_64, `boot::entry::long_mode_entry(ram, entry, boot_params, plan)`diff --git a/src/vmm/src/memory.rs b/src/vmm/src/memory.rsindex 5c7417fc5..85409043e 100644--- a/src/vmm/src/memory.rs+++ b/src/vmm/src/memory.rs@@ -13,6 +13,8 @@use std::{io, ptr::NonNull, sync::Arc};use boxlite_hypervisor::{MemoryRegion, Vm};+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+use vm_memory::Bytes;use vm_memory::{GuestAddress, GuestMemoryBackend, GuestMemoryRegion, VolatileSlice};use crate::error::{Error, Result};@@ -326,6 +328,23 @@ impl GuestRam {.map(|region| (region.start_addr(), region.len() as usize))}+ /// Fills fresh RAM in ascending GPA order from the packed image.+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ pub(crate) fn read_image(&self, source: &mut impl io::Read) -> Result<()> {+ const CHUNK: usize = MIB as usize;+ let mut buffer = vec![0; CHUNK];+ for (start, size) in self.ranges() {+ for offset in (0..size).step_by(CHUNK) {+ let chunk = &mut buffer[..CHUNK.min(size - offset)];+ source.read_exact(chunk).map_err(Error::Snapshot)?;+ self.boot_memory()+ .write_slice(chunk, GuestAddress(start.0 + offset as u64))+ .map_err(|error| Error::Snapshot(io::Error::other(error)))?;+ }+ }+ Ok(())+ }+/// Each RAM range as the hypervisor registers it, in ascending guest order.pub(crate) fn regions(&self) -> impl Iterator<Item = MemoryRegion> + '_ {self.boot_memory().iter().map(|region| MemoryRegion {diff --git a/src/vmm/src/snapshot/image.rs b/src/vmm/src/snapshot/image.rsindex 70a7b8843..958f951a8 100644--- a/src/vmm/src/snapshot/image.rs+++ b/src/vmm/src/snapshot/image.rs@@ -5,19 +5,23 @@use std::{fs::{File, OpenOptions},- io::{self, Write},+ io::{self, Read, Write},os::unix::fs::OpenOptionsExt,path::Path,};use vm_memory::{Bytes, GuestAddress};-use crate::{Error, Result, memory::GuestRam};+use super::state::MachineState;+use crate::{Error, Result, config::MAX_VCPUS, memory::GuestRam};pub(super) const MAGIC: &[u8; 8] = b"BXLVMST1";pub(super) const VERSION: u32 = 1;pub(super) const HEADER_LEN: usize = 32;pub(super) const CHUNK: usize = 1 << 20;+// Bound allocation before decoding, with room for 64 vCPUs at the decoder's+// XSAVE, MSR and CPUID limits, including Postcard's varint overhead.+pub(super) const MAX_MACHINE_STATE_LEN: u64 = 32 << 20;pub(super) struct Header {pub(super) vcpus: u32,@@ -25,6 +29,50 @@ pub(super) struct Header {machine_len: u64,}+impl Header {+ pub(super) fn read(reader: &mut impl Read) -> Result<Self> {+ let mut bytes = [0; HEADER_LEN];+ reader.read_exact(&mut bytes).map_err(Error::Snapshot)?;+ if &bytes[..8] != MAGIC || u32::from_le_bytes(bytes[8..12].try_into().unwrap()) != VERSION {+ return Err(invalid_data("unknown snapshot magic or version"));+ }+ let header = Self {+ vcpus: u32::from_le_bytes(bytes[12..16].try_into().unwrap()),+ ram_len: u64::from_le_bytes(bytes[16..24].try_into().unwrap()),+ machine_len: u64::from_le_bytes(bytes[24..32].try_into().unwrap()),+ };+ if !(1..=u32::from(MAX_VCPUS)).contains(&header.vcpus) {+ return Err(invalid_data("invalid snapshot vCPU count"));+ }+ if header.ram_len == 0 {+ return Err(invalid_data("empty snapshot RAM"));+ }+ if !(1..=MAX_MACHINE_STATE_LEN).contains(&header.machine_len) {+ return Err(invalid_data("invalid machine state length"));+ }+ Ok(header)+ }++ pub(super) fn read_machine(&self, reader: &mut impl Read) -> Result<MachineState> {+ let mut bytes = vec![0; self.machine_len as usize];+ reader.read_exact(&mut bytes).map_err(Error::Snapshot)?;+ expect_eof(reader, "trailing bytes in snapshot state file")?;+ MachineState::decode(&bytes, self.vcpus)+ }+}++pub(super) fn expect_eof(reader: &mut impl Read, message: &'static str) -> Result<()> {+ match reader.read_exact(&mut [0]) {+ Ok(()) => Err(invalid_data(message)),+ Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => Ok(()),+ Err(error) => Err(Error::Snapshot(error)),+ }+}++fn invalid_data(message: &'static str) -> Error {+ Error::Snapshot(io::Error::new(io::ErrorKind::InvalidData, message))+}+pub(crate) fn write_to(state_writer: &mut dyn Write,memory_writer: &mut dyn Write,diff --git a/src/vmm/src/snapshot/mod.rs b/src/vmm/src/snapshot/mod.rsindex 4382852cf..b11953821 100644--- a/src/vmm/src/snapshot/mod.rs+++ b/src/vmm/src/snapshot/mod.rs@@ -3,8 +3,9 @@pub(crate) mod export;pub(crate) mod image;+pub(crate) mod restore;pub(crate) mod state;#[cfg(test)]-#[path = "../../tests/snapshot/execution.rs"]-mod execution_tests;+#[path = "../../tests/snapshot/import.rs"]+mod tests;diff --git a/src/vmm/src/snapshot/restore.rs b/src/vmm/src/snapshot/restore.rsnew file mode 100644index 000000000..a88a02a61--- /dev/null+++ b/src/vmm/src/snapshot/restore.rs@@ -0,0 +1,92 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++use std::{+ fs::File,+ io::{self, Read},+ path::Path,+};++use boxlite_hypervisor::{KvmVm, X86Vm};+use vm_memory::GuestAddress;++use super::image::{Header, expect_eof};+use crate::{+ Error, Result, Vm,+ cpu_features::X86MemoryCaps,+ memory::{GuestRam, X86_LAYOUT},+};++pub(crate) fn from_paths(state_path: &Path, memory_path: &Path) -> Result<Vm<KvmVm>> {+ let mut state = File::open(state_path).map_err(Error::Snapshot)?;+ let mut memory = File::open(memory_path).map_err(Error::Snapshot)?;+ let header = Header::read(&mut state)?;+ let meta = memory.metadata().map_err(Error::Snapshot)?;+ if meta.is_file() && meta.len() != header.ram_len {+ return Err(Error::Snapshot(io::Error::new(+ io::ErrorKind::InvalidData,+ "snapshot memory file length does not match the header",+ )));+ }+ from_header(header, &mut state, &mut memory, prepare_kvm)+}++fn prepare_kvm(+ ranges: &[(GuestAddress, usize)],+) -> Result<impl FnOnce() -> boxlite_hypervisor::Result<KvmVm> + use<>> {+ let prepared = KvmVm::prepare()?;+ let caps = X86MemoryCaps::from_cpuid(prepared.supported_cpuid())+ .map_err(Error::HostMemoryCapability)?;+ check_gpa_limit(ranges, caps.physical_end)?;+ Ok(move || KvmVm::from_prepared(prepared))+}++pub(super) fn check_gpa_limit(ranges: &[(GuestAddress, usize)], physical_end: u64) -> Result<()> {+ // X86_LAYOUT returns ordered ranges with checked end addresses.+ let &(start, size) = ranges.last().expect("validated nonempty RAM");+ let end = start.0 + size as u64;+ if end > physical_end {+ return Err(Error::Snapshot(io::Error::new(+ io::ErrorKind::InvalidData,+ format!(+ "snapshot RAM ends at GPA {end:#x}, beyond KVM exclusive limit {physical_end:#x}"+ ),+ )));+ }+ Ok(())+}++#[cfg(test)]+pub(super) fn from_readers<H, C>(+ state_reader: &mut impl Read,+ memory_reader: &mut impl Read,+ prepare: impl FnOnce(&[(GuestAddress, usize)]) -> Result<C>,+) -> Result<Vm<H>>+where+ H: X86Vm + 'static,+ C: FnOnce() -> boxlite_hypervisor::Result<H>,+{+ let header = Header::read(state_reader)?;+ from_header(header, state_reader, memory_reader, prepare)+}++fn from_header<H, C>(+ header: Header,+ state_reader: &mut impl Read,+ memory_reader: &mut impl Read,+ prepare: impl FnOnce(&[(GuestAddress, usize)]) -> Result<C>,+) -> Result<Vm<H>>+where+ H: X86Vm + 'static,+ C: FnOnce() -> boxlite_hypervisor::Result<H>,+{+ let ranges = X86_LAYOUT+ .ranges(header.ram_len)+ .map_err(|error| Error::Snapshot(io::Error::new(io::ErrorKind::InvalidData, error)))?;+ let machine = header.read_machine(state_reader)?;+ let create = prepare(&ranges)?;+ let ram = GuestRam::new(&ranges)?;+ ram.read_image(memory_reader)?;+ expect_eof(memory_reader, "trailing bytes in snapshot memory file")?;+ Vm::with_restored_ram(ram, machine, create)+}diff --git a/src/vmm/src/snapshot/state.rs b/src/vmm/src/snapshot/state.rsindex 53a001978..3239554ff 100644--- a/src/vmm/src/snapshot/state.rs+++ b/src/vmm/src/snapshot/state.rs@@ -1,10 +1,16 @@// Copyright 2026 BoxLite Contributors// SPDX-License-Identifier: Apache-2.0+use std::io;+use boxlite_hypervisor::{X86VcpuState, X86VmState};use serde::{Deserialize, Serialize};-use crate::{Error, Result};+use crate::{Error, Result, config::MAX_VCPUS};++const CR0_PG: u64 = 1 << 31;+const CR4_PAE: u64 = 1 << 5;+const EFER_LMA: u64 = 1 << 10;#[derive(Debug, Deserialize, Serialize)]pub(crate) struct MachineState {@@ -22,4 +28,40 @@ impl MachineState {pub(crate) fn encode(&self) -> Result<Vec<u8>> {postcard::to_allocvec(self).map_err(|error| Error::Snapshot(std::io::Error::other(error)))}++ pub(crate) fn decode(bytes: &[u8], expected: u32) -> Result<Self> {+ let invalid = |reason| Error::Snapshot(io::Error::new(io::ErrorKind::InvalidData, reason));+ let decode_error =+ |error| Error::Snapshot(io::Error::new(io::ErrorKind::InvalidData, error));+ // Read the leading sequence length before deserializing its records.+ let (count, _) = postcard::take_from_bytes::<usize>(bytes).map_err(decode_error)?;+ if !(1..=usize::from(MAX_VCPUS)).contains(&count) || count != expected as usize {+ return Err(invalid("invalid machine vCPU count"));+ }+ let (state, trailing) = postcard::take_from_bytes::<Self>(bytes).map_err(decode_error)?;+ if !trailing.is_empty() {+ return Err(invalid("trailing bytes in machine state"));+ }+ for (id, record) in state.vcpus.iter().enumerate() {+ if usize::from(record.id) != id {+ return Err(invalid("vCPU records must be contiguous and ordered by id"));+ }+ let sregs = &record.state.sregs;+ if sregs.cr0 & CR0_PG != 0 && sregs.cr4 & CR4_PAE != 0 && sregs.efer & EFER_LMA == 0 {+ return Err(invalid("32-bit paged PAE vCPU state is unsupported"));+ }+ }+ let irqchip_ids = state+ .platform+ .irqchips+ .each_ref()+ .map(|chip| chip.as_kvm().chip_id);+ if irqchip_ids != [0, 1, 2] {+ return Err(invalid("IRQ chip IDs must be 0, 1, and 2 in order"));+ }+ if state.platform.pit.is_none() {+ return Err(invalid("missing PIT state"));+ }+ Ok(state)+ }}diff --git a/src/vmm/src/vcpu.rs b/src/vmm/src/vcpu.rsindex 67c0ce078..ed7d3b284 100644--- a/src/vmm/src/vcpu.rs+++ b/src/vmm/src/vcpu.rs@@ -2,7 +2,7 @@// SPDX-License-Identifier: Apache-2.0//! vCPU workers. Each runs on its own thread: it creates and configures its-//! vCPU, waits until every vCPU is configured, then runs the guest and+//! vCPU, waits for the VM driver to open the start gate, then runs the guest and//! dispatches its exits until the VM ends. Every way a worker ends sends one//! event, except a stop it observed, which some other sender already caused.@@ -17,7 +17,7 @@ use boxlite_hypervisor::{IoCompletion, Vcpu, VcpuExit};use boxlite_hypervisor::{X86BootRegisters, X86Vcpu, X86Vm};#[cfg(all(target_os = "linux", target_arch = "x86_64"))]-use crate::snapshot::state::VcpuRecord;+use crate::snapshot::state::{MachineState, VcpuRecord};use crate::{chipset::Chipset,error::{Error, Result},@@ -30,42 +30,69 @@ use crate::{lifecycle::Lifecycle,};-/// Holds the workers until every vCPU is configured, so no vCPU runs before-/// all exist. Unlike `std::sync::Barrier`, [`abort`](Self::abort) releases-/// them when a worker thread fails to start.+/// Holds configured vCPUs until the driver allows guest entry.#[derive(Default)]#[cfg(target_arch = "x86_64")]pub(crate) struct StartGate {- /// Workers that arrived, and whether the gate was aborted.- state: Mutex<(u8, bool)>,+ state: Mutex<StartState>,changed: Condvar,}+#[derive(Default)]+#[cfg(target_arch = "x86_64")]+struct StartState {+ ready: u8,+ go: bool,+ aborted: bool,+}+#[cfg(target_arch = "x86_64")]impl StartGate {- fn arrive_and_wait(&self, count: u8) {+ fn arrive_and_wait(&self, count: u8, sender: &EventSender) -> bool {let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);- state.0 += 1;+ state.ready += 1;+ if state.ready >= count && !state.aborted {+ sender.wake();+ }+ let state = self+ .changed+ .wait_while(state, |state| !state.go && !state.aborted)+ .unwrap_or_else(PoisonError::into_inner);+ !state.aborted+ }++ pub(crate) fn is_ready(&self, count: u8) -> bool {+ let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);+ state.ready >= count && !state.aborted+ }++ pub(crate) fn release(&self) {+ self.state.lock().unwrap_or_else(PoisonError::into_inner).go = true;self.changed.notify_all();- drop(- self.changed- .wait_while(state, |(arrived, aborted)| *arrived < count && !*aborted)- .unwrap_or_else(PoisonError::into_inner),- );}pub(crate) fn abort(&self) {- self.state.lock().unwrap_or_else(PoisonError::into_inner).1 = true;+ self.state+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .aborted = true;self.changed.notify_all();}}+#[cfg(target_arch = "x86_64")]+pub(crate) enum Startup<'a> {+ Boot(&'a X86BootRegisters),+ #[cfg(target_os = "linux")]+ Restore(&'a MachineState),+}+/// What every worker of one VM shares.#[cfg(target_arch = "x86_64")]pub(crate) struct Workers<'a, H: X86Vm> {pub(crate) host_vm: &'a H,pub(crate) vcpu_count: u8,- pub(crate) boot_regs: &'a X86BootRegisters,+ pub(crate) startup: Startup<'a>,pub(crate) chipset: &'a Chipset,pub(crate) sender: &'a EventSender,pub(crate) lifecycle: &'a Lifecycle,@@ -80,34 +107,43 @@ impl<H: X86Vm> Workers<'_, H> {/// whose lock an earlier panic poisoned, ends the VM with/// [`Error::VcpuPanicked`] instead of leaving the thread.pub(crate) fn run(&self, id: u8) {- let vcpu = match catch_panic(id, || self.configure(id)) {- Ok(vcpu) => Some(vcpu),- Err(error) => {- // Sent before arriving, so the latch is set before any vCPU- // leaves the gate and none enters the guest.- self.sender.send(Event::VcpuFailed(error));- None+ match catch_panic(id, || {+ let mut vcpu = self.configure(id)?;+ if !self.gate.arrive_and_wait(self.vcpu_count, self.sender) {+ return Ok(None);}- };- // A failed vCPU still arrives, so the others are never left waiting.- self.gate.arrive_and_wait(self.vcpu_count);- let Some(mut vcpu) = vcpu else {- return;- };- match catch_panic(id, || self.run_guest(&mut vcpu, id)) {+ self.run_guest(&mut vcpu, id)+ }) {Ok(Some(event)) => self.sender.send(event),Ok(None) => {}- Err(error) => self.sender.send(Event::VcpuFailed(error)),+ Err(error) => {+ self.sender.send(Event::VcpuFailed(error));+ self.gate.abort();+ }}}fn configure(&self, id: u8) -> Result<H::Vcpu> {let mut vcpu = self.host_vm.create_vcpu(id.into())?;- let cpuid = vcpu_cpuid(self.host_vm.supported_cpuid(), id, self.vcpu_count);- vcpu.set_cpu_features(&cpuid, &BOOT_MSRS)?;- // The other vCPUs wait in their reset state for INIT and SIPI.- if id == 0 {- vcpu.set_boot_registers(self.boot_regs)?;+ match self.startup {+ Startup::Boot(regs) => {+ let cpuid = vcpu_cpuid(self.host_vm.supported_cpuid(), id, self.vcpu_count);+ vcpu.set_cpu_features(&cpuid, &BOOT_MSRS)?;+ // The other vCPUs wait in their reset state for INIT and SIPI.+ if id == 0 {+ vcpu.set_boot_registers(regs)?;+ }+ }+ #[cfg(target_os = "linux")]+ Startup::Restore(machine) => {+ let record = &machine.vcpus[usize::from(id)];+ vcpu.restore_state(&record.state)?;+ match vcpu.notify_guest_stopped() {+ Err(boxlite_hypervisor::Error::ConfigureVcpu { source, .. })+ if source.kind() == std::io::ErrorKind::Unsupported => {}+ result => result?,+ }+ }}self.kicks.lock()diff --git a/src/vmm/src/vm.rs b/src/vmm/src/vm.rsindex 3c4a57f48..a8ee71a0b 100644--- a/src/vmm/src/vm.rs+++ b/src/vmm/src/vm.rs@@ -4,12 +4,14 @@//! The VM facade: configuration, host VM creation, RAM registration, boot//! loading, and running the vCPUs until the VM ends.+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+use std::path::Path;use std::sync::{Arc, Mutex, PoisonError};use boxlite_hypervisor::Vm as HostVm;#[cfg(all(target_os = "linux", target_arch = "x86_64"))]-use crate::snapshot::export;+use crate::snapshot::{export, restore, state::MachineState};use crate::{chipset::{Chipset, ChipsetBuilder},config::VmConfig,@@ -72,6 +74,8 @@ pub struct Vm<H: HostVm> {events: Mutex<EventLoop>,sender: EventSender,boot_regs: BootRegisters,+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ restore: Option<Box<MachineState>>,vcpu_count: u8,lifecycle: Arc<Lifecycle>,fresh_vm: bool,@@ -91,6 +95,19 @@ impl<H: HostVm> std::fmt::Debug for Vm<H> {#[cfg(all(target_os = "linux", target_arch = "x86_64"))]impl Vm<boxlite_hypervisor::KvmVm> {+ /// Imports the state and RAM files of a device-less snapshot into a VM in `Created`.+ ///+ /// `state_path` and `memory_path` must come from the same successful export and+ /// remain unchanged during import.+ /// Import allocates and fills anonymous host RAM sized by the snapshot header's+ /// logical `ram_len`, so callers should check their memory budget before importing.+ ///+ /// Call [`Self::run`] to install saved CPU and platform state and execute it.+ /// Reserve a pause through [`Self::control`] before running to hold guest entry.+ pub fn from_state(state_path: impl AsRef<Path>, memory_path: impl AsRef<Path>) -> Result<Self> {+ restore::from_paths(state_path.as_ref(), memory_path.as_ref())+ }+/// Builds a KVM VM with an empty chipset and no console worker./// Rejects userspace device configuration before opening KVM.#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]@@ -211,11 +228,56 @@ impl<H: HostVm> Vm<H> {{let mut config = config;config.validate()?;+ let ram = GuestRam::new(&ram_ranges(config.memory_mib))?;+ let mut vm = Self::with_ram(+ ram,+ config.vcpu_count,+ host_vm,+ fresh_vm,+ create_workers,+ |chipset, ctx, host_vm| devices(chipset, ctx, &mut config, host_vm),+ )?;+ vm.vcpu_count = config.vcpu_count;+ vm.boot_regs = boot(&vm.ram, &config)?;+ Ok(vm)+ }++ /// Builds a device-less VM around a validated image and a fresh host VM.+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ pub(crate) fn with_restored_ram(+ ram: GuestRam,+ machine: MachineState,+ create: impl FnOnce() -> boxlite_hypervisor::Result<H>,+ ) -> Result<Self>+ where+ H: 'static,+ {+ let mut vm = Self::with_ram(+ ram,+ machine.vcpus.len() as u8,+ create,+ true,+ VirtioWorkers::new,+ |_, _, _| Ok(()),+ )?;+ vm.restore = Some(Box::new(machine));+ Ok(vm)+ }++ /// Builds the chipset and registers the supplied RAM before the first run.+ fn with_ram(+ mut ram: GuestRam,+ vcpu_count: u8,+ host_vm: impl FnOnce() -> boxlite_hypervisor::Result<H>,+ fresh_vm: bool,+ create_workers: impl FnOnce(EventSender) -> std::io::Result<VirtioWorkers>,+ devices: impl FnOnce(&mut ChipsetBuilder, DeviceContext<'_>, &Arc<H>) -> Result<()>,+ ) -> Result<Self>+ where+ H: 'static,+ {let events = EventLoop::new().map_err(Error::EventLoop)?;let sender = events.sender();- // Allocating first keeps the drop order safe on every early return:- // locals drop in reverse order, so the host VM goes before the RAM.- let mut ram = GuestRam::new(&ram_ranges(config.memory_mib))?;let host_vm = Arc::new(host_vm()?);// No worker thread starts before a virtio device activates, so an// early return leaves nothing running.@@ -229,7 +291,6 @@ impl<H: HostVm> Vm<H> {workers: &workers,controls: &mut controls,},- &mut config,&host_vm,)?;let chipset = chipset.build()?;@@ -251,7 +312,7 @@ impl<H: HostVm> Vm<H> {}let lifecycle = Arc::new(Lifecycle::new(sender.clone(), device_less));- let mut vm = Self {+ Ok(Self {chipset: Some(chipset),workers: Some(workers),console: Mutex::new(None),@@ -260,13 +321,13 @@ impl<H: HostVm> Vm<H> {lifecycle,sender,boot_regs: BootRegisters::default(),- vcpu_count: config.vcpu_count,+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ restore: None,+ vcpu_count,fresh_vm,host_vm: Some(host_vm),ram,- };- vm.boot_regs = boot(&vm.ram, &config)?;- Ok(vm)+ })}/// A handle that stops this VM from another thread, even before@@ -301,7 +362,7 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {use crate::{events::{Event, RECHECK},lifecycle::VmStatus,- vcpu::{StartGate, Workers},+ vcpu::{StartGate, Startup, Workers},};const KICK_RETRY: Duration = Duration::from_millis(10);@@ -311,23 +372,45 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {if matches!(source.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted))}+ let exit_from_event = |event| match event {+ Event::StopRequested => Ok(VmExit::StopRequested),+ Event::GuestShutdown => Ok(VmExit::GuestShutdown),+ Event::GuestReset => Ok(VmExit::GuestReset),+ Event::VcpuFailed(error) | Event::DeviceFailed(error) => Err(error),+ };+ let events = self+ .events+ .get_mut()+ .unwrap_or_else(PoisonError::into_inner);+ let host_vm = self.host_vm.as_deref().expect("live VM has a host VM");+ let startup = Startup::Boot(&self.boot_regs);+ #[cfg(target_os = "linux")]+ let startup = self.restore.as_deref().map_or(startup, Startup::Restore);+ #[cfg(target_os = "linux")]+ if let Startup::Restore(machine) = startup+ && let Err(error) = install_platform(|| host_vm.restore_before_vcpus(&machine.platform))+ {+ self.sender.send(Event::VcpuFailed(error));+ let event = events+ .wait(Some(std::time::Duration::ZERO))+ .map_err(Error::EventLoop)?+ .expect("platform restore failure queued a terminal event");+ return exit_from_event(event);+ }+self.fresh_vm = false;let gate = StartGate::default();let kicks = Mutex::new(Vec::new());let vcpus = Workers {- host_vm: self.host_vm.as_deref().expect("live VM has a host VM"),+ host_vm,vcpu_count: self.vcpu_count,- boot_regs: &self.boot_regs,+ startup,chipset: self.chipset.as_ref().expect("live VM has a chipset"),sender: &self.sender,lifecycle: &self.lifecycle,kicks: &kicks,gate: &gate,};- let events = self- .events- .get_mut()- .unwrap_or_else(PoisonError::into_inner);let event = thread::scope(|scope| {// Release workers before the scope joins them, including on unwind.struct StopVcpus<'a, H: VcpuHandle> {@@ -338,8 +421,8 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {impl<H: VcpuHandle> Drop for StopVcpus<'_, H> {fn drop(&mut self) {- self.lifecycle.mark_stopping();self.gate.abort();+ self.lifecycle.mark_stopping();// Late registrations cannot enter the guest after the stop latch.let mut pending = std::mem::take(&mut *self.kicks.lock().unwrap_or_else(PoisonError::into_inner),@@ -381,6 +464,7 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {}}let mut pending_kicks = 0u64;+ let mut gate_settled = false;loop {let wait = if pending_kicks != 0 {KICK_RETRY@@ -389,7 +473,7 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {};match events.wait(Some(wait)) {Ok(Some(event)) => break Ok(event),- Err(error) => break Err(error),+ Err(error) => break Err(Error::EventLoop(error)),Ok(None) => {}}let kick_all = self.lifecycle.drive(self.vcpu_count);@@ -417,17 +501,30 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {}}}+ // Drive a pending pause before opening the gate so workers+ // see it at their first checkpoint.+ if !gate_settled && gate.is_ready(vcpus.vcpu_count) && !vcpus.sender.is_stopping() {+ gate_settled = true;+ let installed = match vcpus.startup {+ Startup::Boot(_) => Ok(()),+ #[cfg(target_os = "linux")]+ Startup::Restore(machine) => {+ install_platform(|| host_vm.restore_after_vcpus(&machine.platform))+ }+ };+ match installed {+ Ok(()) => gate.release(),+ Err(error) => {+ vcpus.sender.send(Event::VcpuFailed(error));+ gate.abort();+ }+ }+ }#[cfg(target_os = "linux")]export::drive(vcpus.lifecycle, vcpus.host_vm, &self.ram, self.vcpu_count);}- });- match event {- Ok(Event::StopRequested) => Ok(VmExit::StopRequested),- Ok(Event::GuestShutdown) => Ok(VmExit::GuestShutdown),- Ok(Event::GuestReset) => Ok(VmExit::GuestReset),- Ok(Event::VcpuFailed(error) | Event::DeviceFailed(error)) => Err(error),- Err(error) => Err(Error::EventLoop(error)),- }+ })?;+ exit_from_event(event)}/// Runs every vCPU on its own thread until the first event ends the VM,@@ -476,6 +573,13 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {}}+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+fn install_platform(restore: impl FnOnce() -> boxlite_hypervisor::Result<()>) -> Result<()> {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(restore))+ .map_err(|_| Error::Snapshot(std::io::Error::other("platform restore panicked")))??;+ Ok(())+}+impl<H: HostVm> Drop for Vm<H> {fn drop(&mut self) {self.control.close_memory();diff --git a/src/vmm/tests/boot/initramfs.rs b/src/vmm/tests/boot/initramfs.rsnew file mode 100644index 000000000..488dbfd00--- /dev/null+++ b/src/vmm/tests/boot/initramfs.rs@@ -0,0 +1,69 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++/// Where `static_program` loads its one segment, and the length of the ELF+/// and program headers in front of the code.+pub(super) const PROGRAM_BASE: u64 = 0x40_0000;+pub(super) const PROGRAM_HEADERS: u64 = 64 + 56;++/// A static x86_64 executable: one read-only, executable `PT_LOAD` at+/// `PROGRAM_BASE` holding the headers and then `text`, its entry point.+pub(super) fn static_program(text: &[u8]) -> Vec<u8> {+ let size = PROGRAM_HEADERS + text.len() as u64;+ let mut elf = vec![0x7f, b'E', b'L', b'F', 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];+ elf.extend_from_slice(&2u16.to_le_bytes()); // ET_EXEC+ elf.extend_from_slice(&62u16.to_le_bytes()); // EM_X86_64+ elf.extend_from_slice(&1u32.to_le_bytes()); // EV_CURRENT+ elf.extend_from_slice(&(PROGRAM_BASE + PROGRAM_HEADERS).to_le_bytes()); // entry+ elf.extend_from_slice(&64u64.to_le_bytes()); // program headers+ elf.extend_from_slice(&0u64.to_le_bytes()); // no section headers+ elf.extend_from_slice(&0u32.to_le_bytes()); // flags+ for half in [64u16, 56, 1, 0, 0, 0] {+ // header size, program header size and count, no sections+ elf.extend_from_slice(&half.to_le_bytes());+ }+ elf.extend_from_slice(&1u32.to_le_bytes()); // PT_LOAD+ elf.extend_from_slice(&5u32.to_le_bytes()); // R and X+ for word in [0, PROGRAM_BASE, PROGRAM_BASE, size, size, 0x1000] {+ // offset, virtual and physical address, file and memory size, alignment+ elf.extend_from_slice(&word.to_le_bytes());+ }+ elf.extend_from_slice(text);+ elf+}++/// An uncompressed newc archive holding one executable file, `name`+/// (`Documentation/driver-api/early-userspace/buffer-format.rst`).+pub(super) fn newc_archive(name: &str, data: &[u8]) -> Vec<u8> {+ fn entry(archive: &mut Vec<u8>, ino: u32, mode: u32, name: &str, data: &[u8]) {+ let fields = [+ ino,+ mode,+ 0,+ 0,+ 1,+ 0,+ data.len() as u32,+ 0,+ 0,+ 0,+ 0,+ name.len() as u32 + 1,+ 0,+ ];+ archive.extend_from_slice(b"070701");+ for field in fields {+ archive.extend_from_slice(format!("{field:08X}").as_bytes());+ }+ archive.extend_from_slice(name.as_bytes());+ archive.push(0);+ archive.resize(archive.len().next_multiple_of(4), 0);+ archive.extend_from_slice(data);+ archive.resize(archive.len().next_multiple_of(4), 0);+ }++ let mut archive = Vec::new();+ entry(&mut archive, 1, 0o100_755, name, data);+ entry(&mut archive, 0, 0, "TRAILER!!!", &[]);+ archive+}diff --git a/src/vmm/tests/boot/mod.rs b/src/vmm/tests/boot/mod.rsindex d3ad7039e..ab9a9190d 100644--- a/src/vmm/tests/boot/mod.rs+++ b/src/vmm/tests/boot/mod.rs@@ -42,6 +42,9 @@ use crate::{mod balloon;mod hotplug;+mod initramfs;++use initramfs::{PROGRAM_BASE, PROGRAM_HEADERS, newc_archive, static_program};#[cfg(target_os = "linux")]#[path = "virtio_blk.rs"]mod virtio_blk;@@ -631,37 +634,6 @@ fn boots_linux_with_six_gib_of_ram() {assert!(log.contains("VFS: Unable to mount root fs"), "{log}");}-/// Where `static_program` loads its one segment, and the length of the ELF-/// and program headers in front of the code.-const PROGRAM_BASE: u64 = 0x40_0000;-const PROGRAM_HEADERS: u64 = 64 + 56;--/// A static x86_64 executable: one read-only, executable `PT_LOAD` at-/// `PROGRAM_BASE` holding the headers and then `text`, its entry point.-fn static_program(text: &[u8]) -> Vec<u8> {- let size = PROGRAM_HEADERS + text.len() as u64;- let mut elf = vec![0x7f, b'E', b'L', b'F', 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];- elf.extend_from_slice(&2u16.to_le_bytes()); // ET_EXEC- elf.extend_from_slice(&62u16.to_le_bytes()); // EM_X86_64- elf.extend_from_slice(&1u32.to_le_bytes()); // EV_CURRENT- elf.extend_from_slice(&(PROGRAM_BASE + PROGRAM_HEADERS).to_le_bytes()); // entry- elf.extend_from_slice(&64u64.to_le_bytes()); // program headers- elf.extend_from_slice(&0u64.to_le_bytes()); // no section headers- elf.extend_from_slice(&0u32.to_le_bytes()); // flags- for half in [64u16, 56, 1, 0, 0, 0] {- // header size, program header size and count, no sections- elf.extend_from_slice(&half.to_le_bytes());- }- elf.extend_from_slice(&1u32.to_le_bytes()); // PT_LOAD- elf.extend_from_slice(&5u32.to_le_bytes()); // R and X- for word in [0, PROGRAM_BASE, PROGRAM_BASE, size, size, 0x1000] {- // offset, virtual and physical address, file and memory size, alignment- elf.extend_from_slice(&word.to_le_bytes());- }- elf.extend_from_slice(text);- elf-}-/// A static executable that calls `exit_group(code)`.fn exit_program(code: u8) -> Vec<u8> {// mov edi, code; mov eax, 231 (exit_group); syscall@@ -814,42 +786,6 @@ fn affinity_program(count: u8) -> Vec<u8> {static_program(&text)}-/// An uncompressed newc archive holding one executable file, `name`-/// (`Documentation/driver-api/early-userspace/buffer-format.rst`).-fn newc_archive(name: &str, data: &[u8]) -> Vec<u8> {- fn entry(archive: &mut Vec<u8>, ino: u32, mode: u32, name: &str, data: &[u8]) {- let fields = [- ino,- mode,- 0,- 0,- 1,- 0,- data.len() as u32,- 0,- 0,- 0,- 0,- name.len() as u32 + 1,- 0,- ];- archive.extend_from_slice(b"070701");- for field in fields {- archive.extend_from_slice(format!("{field:08X}").as_bytes());- }- archive.extend_from_slice(name.as_bytes());- archive.push(0);- archive.resize(archive.len().next_multiple_of(4), 0);- archive.extend_from_slice(data);- archive.resize(archive.len().next_multiple_of(4), 0);- }-- let mut archive = Vec::new();- entry(&mut archive, 1, 0o100_755, name, data);- entry(&mut archive, 0, 0, "TRAILER!!!", &[]);- archive-}-/// Asserts that each of `steps` is a line of `log`, in that order.fn assert_in_order(log: &str, steps: &[&str]) {let lines: Vec<&str> = log.lines().collect();diff --git a/src/vmm/tests/snapshot/execution.rs b/src/vmm/tests/snapshot/execution.rsindex 44b3b2f76..b019a024b 100644--- a/src/vmm/tests/snapshot/execution.rs+++ b/src/vmm/tests/snapshot/execution.rs@@ -53,7 +53,7 @@ fn platform() -> X86VmState {X86IrqchipState::pic(1, Default::default()),X86IrqchipState::ioapic(Default::default()),],- pit: None,+ pit: Some(Default::default()),clock: Default::default(),}}@@ -255,10 +255,9 @@ fn with_paused<H: X86Vm, R>(}fn decode(mut bytes: &[u8], memory: &[u8]) -> (Header, MachineState) {- let len = bytes.len() as u64;- let header = Header::read_from(&mut bytes, len, memory.len() as u64).unwrap();- let (state, tail) = postcard::take_from_bytes(bytes).unwrap();- assert!(tail.is_empty());+ let header = Header::read(&mut bytes).unwrap();+ let state = header.read_machine(&mut bytes).unwrap();+ assert_eq!(header.ram_len, memory.len() as u64);(header, state)}diff --git a/src/vmm/tests/snapshot/image.rs b/src/vmm/tests/snapshot/image.rsindex aed5be9a2..1b11ff465 100644--- a/src/vmm/tests/snapshot/image.rs+++ b/src/vmm/tests/snapshot/image.rs@@ -5,51 +5,22 @@mod linux {use std::{fs::{self, File},- io::{self, Read, Write},+ io::{self, Write},};use vm_memory::{Bytes, GuestAddress};use crate::{- ControlReason, Error, Result,+ ControlReason, Error,events::EventLoop,lifecycle::Lifecycle,memory::{GuestRam, MMIO_HOLE_START, X86_LAYOUT},- snapshot::image::{HEADER_LEN, Header, MAGIC, VERSION, create_new_file, write_to},+ snapshot::image::{Header, MAX_MACHINE_STATE_LEN, create_new_file, write_to},};const MIB: usize = 1 << 20;const PAGE: usize = 4096;- impl Header {- pub(crate) fn read_from(- reader: &mut impl Read,- state_len: u64,- memory_len: u64,- ) -> Result<Self> {- let mut bytes = [0; HEADER_LEN];- reader.read_exact(&mut bytes).map_err(Error::Snapshot)?;- let invalid =- |reason| Error::Snapshot(io::Error::new(io::ErrorKind::InvalidData, reason));- if &bytes[..8] != MAGIC- || u32::from_le_bytes(bytes[8..12].try_into().unwrap()) != VERSION- {- return Err(invalid("unknown snapshot magic or version"));- }- let header = Self {- vcpus: u32::from_le_bytes(bytes[12..16].try_into().unwrap()),- ram_len: u64::from_le_bytes(bytes[16..24].try_into().unwrap()),- machine_len: u64::from_le_bytes(bytes[24..32].try_into().unwrap()),- };- if (HEADER_LEN as u64).checked_add(header.machine_len) != Some(state_len)- || header.ram_len != memory_len- {- return Err(invalid("snapshot lengths do not match the files"));- }- Ok(header)- }- }-#[derive(Default)]struct RecordingWriter {output: Vec<u8>,@@ -122,31 +93,45 @@ mod linux {let mut state = Vec::new();let mut memory = Vec::new();write_to(&mut state, &mut memory, 2, b"state", &ram).unwrap();- let state_len = state.len() as u64;- let memory_len = memory.len() as u64;- let header = Header::read_from(&mut state.as_slice(), state_len, memory_len).unwrap();+ let header = Header::read(&mut state.as_slice()).unwrap();assert_eq!((header.vcpus, header.ram_len, header.machine_len),(2, PAGE as u64, 5));assert!(matches!(- Header::read_from(&mut &state[..31], 31, memory_len),+ Header::read(&mut &state[..31]),Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::UnexpectedEof));- for len in [state_len - 1, state_len + 1] {- assert!(Header::read_from(&mut state.as_slice(), len, memory_len).is_err());- }- for len in [memory_len - 1, memory_len + 1] {- assert!(Header::read_from(&mut state.as_slice(), state_len, len).is_err());- }- for offset in [0, 8] {+ for (field, value) in [+ (0..1, &[0][..]), // magic+ (8..9, &[2]), // version+ (12..13, &[0]), // zero vCPUs+ (12..13, &[65]),+ (16..24, &0u64.to_le_bytes()), // RAM length+ (24..32, &0u64.to_le_bytes()), // machine state length+ (24..32, &(MAX_MACHINE_STATE_LEN + 1).to_le_bytes()),+ ] {let mut corrupt = state.clone();- corrupt[offset] ^= 0xff;- assert!(Header::read_from(&mut corrupt.as_slice(), state_len, memory_len).is_err());+ corrupt[field].copy_from_slice(value);+ assert!(matches!(+ Header::read(&mut corrupt.as_slice()),+ Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::InvalidData+ ));}- state[24..32].copy_from_slice(&u64::MAX.to_le_bytes());- assert!(Header::read_from(&mut state.as_slice(), state_len, memory_len).is_err());++ let mut truncated = &state[..state.len() - 1];+ assert!(matches!(+ Header::read(&mut truncated).unwrap().read_machine(&mut truncated),+ Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::UnexpectedEof+ ));+ state.push(0);+ let mut trailing = state.as_slice();+ assert!(matches!(+ Header::read(&mut trailing).unwrap().read_machine(&mut trailing),+ Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::InvalidData+ && error.to_string() == "trailing bytes in snapshot state file"+ ));}#[test]diff --git a/src/vmm/tests/snapshot/import.rs b/src/vmm/tests/snapshot/import.rsnew file mode 100644index 000000000..7843758ed--- /dev/null+++ b/src/vmm/tests/snapshot/import.rs@@ -0,0 +1,407 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++use std::{+ cell::Cell,+ fs::{self, File},+ io::{self, Read},+};++use boxlite_hypervisor::{X86IrqchipState, X86VcpuState, X86VmState};+use vm_memory::{Bytes, GuestAddress};++use super::{image, state};+use crate::{+ Error, Vm, VmStatus,+ memory::{GuestRam, MMIO_HOLE_START, X86_LAYOUT},+ mock_vm::{Call, MockVm},+ snapshot::{+ restore::{check_gpa_limit, from_readers},+ state::{MachineState, VcpuRecord},+ },+};++#[path = "execution.rs"]+mod execution;+#[path = "restore.rs"]+mod restore;++const PAGE: usize = 4096;+const MIB: usize = 1 << 20;++fn machine(count: u8) -> MachineState {+ MachineState {+ vcpus: (0..count)+ .map(|id| {+ let state = X86VcpuState {+ regs: Default::default(),+ sregs: Default::default(),+ fpu: Default::default(),+ xsave: vec![],+ cpuid: vec![],+ msrs: vec![],+ xcrs: Default::default(),+ debug_regs: Default::default(),+ events: Default::default(),+ mp_state: Default::default(),+ lapic: Default::default(),+ tsc_khz: 1000,+ };+ let mut record = VcpuRecord { id, state };+ record.state.regs.rax = u64::from(id) + 10;+ record+ })+ .collect(),+ platform: X86VmState {+ irqchips: [+ X86IrqchipState::pic(0, Default::default()),+ X86IrqchipState::pic(1, Default::default()),+ X86IrqchipState::ioapic(Default::default()),+ ],+ pit: Some(Default::default()),+ clock: Default::default(),+ },+ }+}++fn snapshot(count: u32, payload: &[u8]) -> (Vec<u8>, Vec<u8>) {+ let ram = GuestRam::new(&[(GuestAddress(0), PAGE)]).unwrap();+ let mut state = Vec::new();+ let mut memory = Vec::new();+ image::write_to(&mut state, &mut memory, count, payload, &ram).unwrap();+ (state, memory)+}++struct ShortReads<'a> {+ bytes: &'a [u8],+ largest: &'a Cell<usize>,+}++impl Read for ShortReads<'_> {+ fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {+ assert!(bytes.len() <= MIB);+ self.largest.set(self.largest.get().max(bytes.len()));+ let len = bytes.len().min(self.bytes.len()).min(65537);+ bytes[..len].copy_from_slice(&self.bytes[..len]);+ self.bytes = &self.bytes[len..];+ Ok(len)+ }+}++#[test]+fn ram_import_streams_short_reads_across_the_mmio_hole() {+ let low_len = 2 * MIB + PAGE;+ let low = GuestAddress(MMIO_HOLE_START - low_len as u64);+ let high = GuestAddress(1 << 32);+ let mut bytes: Vec<_> = (0..low_len).map(|index| (index % 251) as u8).collect();+ bytes.extend([0xd6; PAGE]);+ let largest = Cell::new(0);+ let mut reader = ShortReads {+ bytes: &bytes,+ largest: &largest,+ };+ let ram = GuestRam::new(&[(low, low_len), (high, PAGE)]).unwrap();++ ram.read_image(&mut reader).unwrap();++ assert!(reader.bytes.is_empty());+ assert_eq!(largest.get(), MIB);+ for (address, expected) in [(low, &bytes[..low_len]), (high, &bytes[low_len..])] {+ let mut actual = vec![0; expected.len()];+ ram.boot_memory().read_slice(&mut actual, address).unwrap();+ assert_eq!(actual, expected);+ }+}++#[test]+fn import_consumes_both_readers_with_short_reads() {+ for count in [1, 64] {+ let (state, memory) = snapshot(u32::from(count), &machine(count).encode().unwrap());+ let largest = Cell::new(0);+ let mut state_reader = ShortReads {+ bytes: &state,+ largest: &largest,+ };+ let mut memory_reader = ShortReads {+ bytes: &memory,+ largest: &largest,+ };+ let vm = from_readers(&mut state_reader, &mut memory_reader, |_| {+ Ok(|| Ok(MockVm::new()))+ })+ .unwrap();++ assert_eq!(vm.control().status(), VmStatus::Created);+ assert!(state_reader.bytes.is_empty());+ assert!(memory_reader.bytes.is_empty());+ }+}++fn reject_before_host_prepare(mut reader: impl Read) -> io::Error {+ let error = from_readers::<MockVm, fn() -> boxlite_hypervisor::Result<MockVm>>(+ &mut reader,+ &mut io::empty(),+ |_| panic!("malformed snapshot reached host preparation"),+ )+ .unwrap_err();+ let Error::Snapshot(error) = error else {+ panic!("expected snapshot error, got {error:?}");+ };+ error+}++#[test]+fn kvm_gpa_limit_accounts_for_high_ram_above_the_mmio_hole() {+ let physical_end = (1 << 32) + PAGE as u64;+ let ram_len = MMIO_HOLE_START + PAGE as u64;+ let ranges = X86_LAYOUT.ranges(ram_len).unwrap();+ check_gpa_limit(&ranges, physical_end).unwrap();++ let ranges = X86_LAYOUT.ranges(ram_len + PAGE as u64).unwrap();+ assert!(matches!(+ check_gpa_limit(&ranges, physical_end),+ Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::InvalidData+ ));+}++#[test]+fn import_rejects_aligned_ram_length_whose_end_gpa_overflows() {+ let (mut state, _) = snapshot(1, &machine(1).encode().unwrap());+ state[16..24].copy_from_slice(&(u64::MAX - 4095).to_le_bytes());++ let error = reject_before_host_prepare(state.as_slice());+ assert_eq!(error.kind(), io::ErrorKind::InvalidData);+ assert_eq!(error.to_string(), "guest RAM end GPA overflows");+}++#[test]+fn malformed_headers_and_machine_records_fail_before_host_preparation() {+ let payload = machine(2).encode().unwrap();+ let (valid, _) = snapshot(2, &payload);+ for (offset, value) in [+ (0, 0), // magic+ (8, 2), // version+ (12, 0), // zero vCPUs+ (12, 65), // too many vCPUs+ (12, 1), // count disagrees with Postcard+ ] {+ let mut invalid = valid.clone();+ invalid[offset] = value;+ assert_eq!(+ reject_before_host_prepare(invalid.as_slice()).kind(),+ io::ErrorKind::InvalidData+ );+ }+ let mut unaligned = valid.clone();+ unaligned[16] = 1;+ assert_eq!(+ reject_before_host_prepare(unaligned.as_slice()).kind(),+ io::ErrorKind::InvalidData+ );+ for (offset, value) in [+ (16, 0),+ (16, u64::MAX),+ (24, 0),+ (24, image::MAX_MACHINE_STATE_LEN + 1),+ ] {+ let mut invalid = valid.clone();+ invalid[offset..offset + 8].copy_from_slice(&value.to_le_bytes());+ assert_eq!(+ reject_before_host_prepare(invalid.as_slice()).kind(),+ io::ErrorKind::InvalidData+ );+ }+ for ids in [[0, 0], [1, 0], [0, 2]] {+ let mut state = machine(2);+ for (record, id) in state.vcpus.iter_mut().zip(ids) {+ record.id = id;+ }+ let (invalid, _) = snapshot(2, &state.encode().unwrap());+ let error = reject_before_host_prepare(invalid.as_slice());+ assert!(error.to_string().contains("contiguous and ordered"));+ }+ let mut trailing = payload.clone();+ trailing.push(0);+ let excessive_count = postcard::to_allocvec(&usize::MAX).unwrap();+ for invalid in [&payload[..1], &trailing, &excessive_count] {+ let (invalid, _) = snapshot(2, invalid);+ assert_eq!(+ reject_before_host_prepare(invalid.as_slice()).kind(),+ io::ErrorKind::InvalidData+ );+ }+}++#[test]+fn machine_import_rejects_missing_pit() {+ let mut state = machine(1);+ state.platform.pit = None;+ let (bytes, _) = snapshot(1, &state.encode().unwrap());++ let error = reject_before_host_prepare(bytes.as_slice());+ assert_eq!(error.kind(), io::ErrorKind::InvalidData);+ assert!(error.to_string().contains("PIT"));+}++#[test]+fn machine_import_rejects_32_bit_paged_pae() {+ let mut state = machine(2);+ let sregs = &mut state.vcpus[1].state.sregs;+ sregs.cr0 = 1 << 31;+ sregs.cr4 = 1 << 5;+ let (bytes, _) = snapshot(2, &state.encode().unwrap());++ let error = reject_before_host_prepare(bytes.as_slice());+ assert_eq!(error.kind(), io::ErrorKind::InvalidData);+ assert!(error.to_string().contains("32-bit paged PAE"));+}++#[test]+fn machine_import_rejects_out_of_order_irqchip_ids() {+ let mut state = machine(1);+ state.platform.irqchips.swap(0, 1);+ let (bytes, _) = snapshot(1, &state.encode().unwrap());++ let error = reject_before_host_prepare(bytes.as_slice());+ assert_eq!(error.kind(), io::ErrorKind::InvalidData);+ assert!(error.to_string().contains("IRQ chip IDs"));+}++#[test]+fn machine_import_rejects_duplicate_irqchip_ids() {+ let mut state = machine(1);+ state.platform.irqchips[1] = X86IrqchipState::pic(0, Default::default());+ let (bytes, _) = snapshot(1, &state.encode().unwrap());+ let mut reader = bytes.as_slice();+ let header = image::Header::read(&mut reader).unwrap();++ let error = header+ .read_machine(&mut reader)+ .expect_err("machine import accepted duplicate IRQ chip IDs");+ assert!(matches!(+ error,+ Error::Snapshot(error) if error.kind() == io::ErrorKind::InvalidData+ ));+}++#[test]+fn file_import_rejects_truncated_or_trailing_state_bytes() {+ let dir = tempfile::tempdir().unwrap();+ let state_path = dir.path().join("state");+ let memory_path = dir.path().join("memory");+ let (mut state, memory) = snapshot(1, &machine(1).encode().unwrap());+ fs::write(&memory_path, memory).unwrap();+ state.push(0);+ fs::write(&state_path, &state).unwrap();+ assert!(matches!(+ Vm::from_state(&state_path, &memory_path),+ Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::InvalidData+ ));++ fs::write(&state_path, &state[..state.len() - 2]).unwrap();+ assert!(matches!(+ Vm::from_state(&state_path, &memory_path),+ Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::UnexpectedEof+ ));+}++#[test]+fn file_import_rejects_either_missing_file() {+ let dir = tempfile::tempdir().unwrap();+ let state_path = dir.path().join("state");+ let memory_path = dir.path().join("memory");+ let missing_path = dir.path().join("missing");+ let (state, memory) = snapshot(1, &machine(1).encode().unwrap());+ fs::write(&state_path, state).unwrap();+ fs::write(&memory_path, memory).unwrap();+ for (state_path, memory_path) in [(&state_path, &missing_path), (&missing_path, &memory_path)] {+ assert!(matches!(+ Vm::from_state(state_path, memory_path),+ Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::NotFound+ ));+ }+}++#[test]+fn file_import_rejects_short_or_long_memory_before_host_creation() {+ let dir = tempfile::tempdir().unwrap();+ let state_path = dir.path().join("state");+ let path = dir.path().join("memory");+ let (state, mut memory) = snapshot(1, &machine(1).encode().unwrap());+ fs::write(&state_path, &state).unwrap();+ memory.push(0);+ for (length, kind) in [+ (PAGE - 1, io::ErrorKind::UnexpectedEof),+ (PAGE + 1, io::ErrorKind::InvalidData),+ ] {+ fs::write(&path, &memory[..length]).unwrap();+ assert!(matches!(+ Vm::from_state(&state_path, &path),+ Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::InvalidData+ ));++ let result = from_readers::<MockVm, _>(+ &mut state.as_slice(),+ &mut File::open(&path).unwrap(),+ |_| Ok(|| panic!("incorrect RAM length reached host creation")),+ );+ assert!(matches!(result, Err(Error::Snapshot(error)) if error.kind() == kind));+ }+}++#[test]+fn payload_read_errors_do_not_create_a_vm() {+ let payload = machine(1).encode().unwrap();+ let (state, memory) = snapshot(1, &payload);++ struct Fail;+ impl Read for Fail {+ fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {+ Err(io::Error::other("RAM read failed"))+ }+ }++ let never_create =+ |_: &[(GuestAddress, usize)]| -> crate::Result<fn() -> boxlite_hypervisor::Result<MockVm>> {+ Ok(|| panic!("incomplete RAM reached host creation"))+ };+ let result = from_readers(+ &mut state.as_slice(),+ &mut memory[..memory.len() - 1].chain(Fail),+ never_create,+ );+ assert!(matches!(result, Err(Error::Snapshot(e)) if e.to_string() == "RAM read failed"));+}++#[test]+fn host_creation_and_failed_registration_are_constructor_errors() {+ let (state, memory) = snapshot(1, &machine(1).encode().unwrap());+ let result = from_readers::<MockVm, _>(&mut state.as_slice(), &mut memory.as_slice(), |_| {+ Ok(|| {+ Err(boxlite_hypervisor::Error::CreateVm(io::Error::other(+ "create failure",+ )))+ })+ });+ assert!(matches!(+ result,+ Err(Error::Hypervisor(boxlite_hypervisor::Error::CreateVm(error)))+ if error.to_string() == "create failure"+ ));++ let host = MockVm::failing_at(&[0]);+ let calls = host.log();+ let result = from_readers(&mut state.as_slice(), &mut memory.as_slice(), |_| {+ Ok(move || Ok(host))+ });+ assert!(matches!(+ result,+ Err(Error::Hypervisor(+ boxlite_hypervisor::Error::MapMemory { .. }+ ))+ ));+ assert!(matches!(+ calls.lock().unwrap().as_slice(),+ [Call::Map { .. }, Call::Unmap { .. }]+ ));+}diff --git a/src/vmm/tests/snapshot/restore.rs b/src/vmm/tests/snapshot/restore.rsnew file mode 100644index 000000000..4287b07fe--- /dev/null+++ b/src/vmm/tests/snapshot/restore.rs@@ -0,0 +1,1152 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++use std::{+ fs::{self, File},+ io,+ marker::PhantomData,+ path::{Path, PathBuf},+ rc::Rc,+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, AtomicUsize, Ordering},+ mpsc,+ },+ thread::{self, ThreadId},+ time::{Duration, Instant},+};++use boxlite_hypervisor::{+ IoCompletion, KvmVm, MemoryRegion, Vcpu, VcpuExit, X86BootRegisters, X86CpuidEntry, X86Msr,+ X86Vcpu, X86VcpuState, X86Vm, X86VmState,+};+use vm_memory::{Bytes, GuestAddress};++use super::{image::Header, machine, state::MachineState};+use crate::{+ ControlReason, Error, Vm, VmConfig, VmControl, VmExit, VmStatus,+ memory::GuestRam,+ mock_vm::{Call, MockHandle, MockVcpu, MockVm},+};++const WAIT: Duration = Duration::from_secs(5);+const COUNT: u8 = 3;++#[derive(Clone, Copy, Debug, PartialEq)]+enum Failure {+ None,+ BeforeVcpus,+ AfterVcpus,+ PlatformPanic,+ CreateCpu,+ RestoreRegs,+ NotifyStopped,+ NotifyUnsupported,+ InitialPark,+ CpuPanic,+}++#[derive(Debug)]+enum Install {+ BeforeVcpus(ThreadId),+ Cpu(u32, ThreadId),+ Notified(u32, ThreadId),+ AfterVcpus(ThreadId),+ Entry,+}++struct Backend {+ inner: MockVm,+ failure: Failure,+ observed: mpsc::Sender<Install>,+ before_vcpus_done: AtomicBool,+ after_vcpus_done: Arc<AtomicBool>,+ create_attempts: Arc<AtomicUsize>,+ hold_last: Mutex<Option<mpsc::Receiver<()>>>,+ hold_failure: Mutex<Option<mpsc::Receiver<()>>>,+}++struct Cpu {+ inner: MockVcpu,+ id: u32,+ owner: ThreadId,+ failure: Failure,+ observed: mpsc::Sender<Install>,+ after_vcpus_done: Arc<AtomicBool>,+ notified: bool,+ hold: Option<mpsc::Receiver<()>>,+ local: PhantomData<Rc<()>>,+}++fn failure() -> io::Error {+ io::Error::other("injected install failure")+}++impl Backend {+ fn platform_failure(&self, operation: &'static str) -> boxlite_hypervisor::Error {+ if let Some(hold) = self.hold_failure.lock().unwrap().take() {+ hold.recv_timeout(WAIT).unwrap();+ }+ boxlite_hypervisor::Error::VmState {+ operation,+ source: failure(),+ }+ }+}++impl boxlite_hypervisor::Vm for Backend {+ type Vcpu = Cpu;++ unsafe fn map_memory(&self, region: &MemoryRegion) -> boxlite_hypervisor::Result<()> {+ // SAFETY: forwards the caller's unchanged registration contract.+ unsafe { self.inner.map_memory(region) }+ }++ fn unmap_memory(&self, region: &MemoryRegion) -> boxlite_hypervisor::Result<()> {+ self.inner.unmap_memory(region)+ }++ fn set_irq_line(&self, line: u32, level: bool) -> boxlite_hypervisor::Result<()> {+ self.inner.set_irq_line(line, level)+ }++ fn create_vcpu(&self, id: u32) -> boxlite_hypervisor::Result<Cpu> {+ self.create_attempts.fetch_add(1, Ordering::SeqCst);+ assert!(self.before_vcpus_done.load(Ordering::SeqCst));+ if id == 1 && self.failure == Failure::CreateCpu {+ return Err(boxlite_hypervisor::Error::CreateVcpu {+ id,+ source: failure(),+ });+ }+ let hold = if id == u32::from(COUNT - 1) {+ self.hold_last.lock().unwrap().take()+ } else {+ None+ };+ Ok(Cpu {+ inner: self.inner.create_vcpu(id)?,+ id,+ owner: thread::current().id(),+ failure: self.failure,+ observed: self.observed.clone(),+ after_vcpus_done: self.after_vcpus_done.clone(),+ notified: false,+ hold,+ local: PhantomData,+ })+ }+}++impl X86Vm for Backend {+ fn supported_cpuid(&self) -> &[X86CpuidEntry] {+ panic!("restore queried boot CPUID")+ }++ fn restore_before_vcpus(&self, state: &X86VmState) -> boxlite_hypervisor::Result<()> {+ self.observed+ .send(Install::BeforeVcpus(thread::current().id()))+ .unwrap();+ assert_eq!(state, &machine(COUNT).platform);+ assert_ne!(self.failure, Failure::PlatformPanic, "platform panic");+ if self.failure == Failure::BeforeVcpus {+ return Err(self.platform_failure("restore before vCPUs"));+ }+ self.before_vcpus_done.store(true, Ordering::SeqCst);+ Ok(())+ }++ fn restore_after_vcpus(&self, state: &X86VmState) -> boxlite_hypervisor::Result<()> {+ self.observed+ .send(Install::AfterVcpus(thread::current().id()))+ .unwrap();+ assert_eq!(state, &machine(COUNT).platform);+ if self.failure == Failure::AfterVcpus {+ return Err(self.platform_failure("restore after vCPUs"));+ }+ self.after_vcpus_done.store(true, Ordering::SeqCst);+ Ok(())+ }+}++impl Vcpu for Cpu {+ type Handle = MockHandle;++ fn run(&mut self) -> boxlite_hypervisor::Result<VcpuExit<'_>> {+ self.observed.send(Install::Entry).unwrap();+ assert!(self.after_vcpus_done.load(Ordering::SeqCst));+ self.inner.run()+ }++ fn complete_pending_io(&mut self) -> boxlite_hypervisor::Result<IoCompletion<'_>> {+ self.inner.complete_pending_io()+ }++ fn notify_guest_stopped(&mut self) -> boxlite_hypervisor::Result<()> {+ assert_eq!(thread::current().id(), self.owner);+ if self.notified {+ if self.id == 1 && self.failure == Failure::InitialPark {+ return Err(self.error("notify guest stopped"));+ }+ return Ok(());+ }+ if let Some(hold) = self.hold.take() {+ hold.recv_timeout(WAIT).unwrap();+ }+ self.notified = true;+ self.observed+ .send(Install::Notified(self.id, self.owner))+ .unwrap();+ if self.id == 1 && self.failure == Failure::NotifyStopped {+ return Err(self.error("notify guest stopped"));+ }+ if self.id == 1 && self.failure == Failure::NotifyUnsupported {+ return Err(boxlite_hypervisor::Error::ConfigureVcpu {+ id: self.id,+ operation: "notify guest stopped",+ source: io::Error::from(io::ErrorKind::Unsupported),+ });+ }+ Ok(())+ }++ fn handle(&self) -> MockHandle {+ self.inner.handle()+ }+}++impl X86Vcpu for Cpu {+ fn set_cpu_features(+ &mut self,+ _: &[X86CpuidEntry],+ _: &[X86Msr],+ ) -> boxlite_hypervisor::Result<()> {+ panic!("restore applied boot CPU features")+ }++ fn set_boot_registers(&mut self, _: &X86BootRegisters) -> boxlite_hypervisor::Result<()> {+ panic!("restore applied boot registers")+ }++ fn restore_state(&mut self, state: &X86VcpuState) -> boxlite_hypervisor::Result<()> {+ assert_eq!(thread::current().id(), self.owner);+ assert_eq!(state.regs.rax, u64::from(self.id) + 10);+ if self.id == 1 {+ assert_ne!(self.failure, Failure::CpuPanic, "vCPU restore panic");+ if self.failure == Failure::RestoreRegs {+ return Err(self.error("restore CPU state"));+ }+ }+ self.observed+ .send(Install::Cpu(self.id, self.owner))+ .unwrap();+ Ok(())+ }+}++impl Cpu {+ fn error(&self, operation: &'static str) -> boxlite_hypervisor::Error {+ boxlite_hypervisor::Error::ConfigureVcpu {+ id: self.id,+ operation,+ source: failure(),+ }+ }+}++fn backend(failure: Failure) -> (Backend, mpsc::Receiver<Install>) {+ let (observed, events) = mpsc::channel();+ (+ Backend {+ inner: MockVm::new(),+ failure,+ observed,+ before_vcpus_done: AtomicBool::new(false),+ after_vcpus_done: Arc::new(AtomicBool::new(false)),+ create_attempts: Arc::new(AtomicUsize::new(0)),+ hold_last: Mutex::new(None),+ hold_failure: Mutex::new(None),+ },+ events,+ )+}++fn ram() -> GuestRam {+ GuestRam::new(&[(GuestAddress(0), 4096)]).unwrap()+}++struct StopOnDrop<'a>(&'a VmControl);++impl Drop for StopOnDrop<'_> {+ fn drop(&mut self) {+ self.0.stop();+ }+}++fn drive<H: X86Vm, T>(+ vm: &mut Vm<H>,+ initially_paused: bool,+ test: impl FnOnce(&VmControl, ThreadId) -> T,+) -> T {+ let control = vm.control();+ if initially_paused {+ control.request_pause().unwrap();+ assert_eq!(control.status(), VmStatus::Created);+ }+ let result = thread::scope(|scope| {+ let driver = scope.spawn(|| vm.run());+ let stop = StopOnDrop(&control);+ let result = test(&control, driver.thread().id());+ drop(stop);+ assert_eq!(driver.join().unwrap().unwrap(), VmExit::StopRequested);+ result+ });+ assert_eq!(control.status(), VmStatus::Exited);+ result+}++#[test]+fn restore_installs_platform_on_driver_and_vcpus_on_their_owners_before_guest_entry() {+ for (initially_paused, injected) in [+ (false, Failure::None),+ (true, Failure::None),+ (false, Failure::NotifyUnsupported),+ ] {+ let (backend, observed) = backend(injected);+ let (release, hold) = mpsc::channel();+ *backend.hold_last.lock().unwrap() = Some(hold);+ let entries = backend.inner.entries();+ let mut vm = Vm::with_restored_ram(ram(), machine(COUNT), || Ok(backend)).unwrap();+ assert_eq!(vm.control().status(), VmStatus::Created);+ assert!(matches!(+ observed.try_recv(),+ Err(mpsc::TryRecvError::Empty)+ ));++ drive(&mut vm, initially_paused, |control, driver| {+ assert!(+ matches!(observed.recv_timeout(WAIT).unwrap(), Install::BeforeVcpus(owner) if owner == driver)+ );+ let mut workers = [None; COUNT as usize];+ let mut notified = [false; COUNT as usize];+ for _ in 0..(COUNT * 2 - 1) {+ match observed.recv_timeout(WAIT).unwrap() {+ Install::Cpu(id, owner) => {+ assert_ne!(owner, driver);+ assert!(!workers.contains(&Some(owner)));+ assert!(workers[id as usize].replace(owner).is_none());+ }+ Install::Notified(id, owner) => {+ assert_eq!(workers[id as usize], Some(owner));+ assert!(!notified[id as usize]);+ notified[id as usize] = true;+ }+ event => panic!("unexpected event before every vCPU was ready: {event:?}"),+ }+ }+ assert_eq!(notified, [true, true, false]);+ assert!(entries.lock().unwrap().is_empty());+ release.send(()).unwrap();+ assert!(matches!(+ observed.recv_timeout(WAIT).unwrap(),+ Install::Notified(2, owner) if Some(owner) == workers[2]+ ));+ assert!(matches!(+ observed.recv_timeout(WAIT).unwrap(),+ Install::AfterVcpus(owner) if owner == driver+ ));++ if initially_paused {+ control.wait_paused(WAIT).unwrap();+ assert_eq!(control.status(), VmStatus::Paused);+ assert!(entries.lock().unwrap().is_empty());+ assert!(matches!(+ observed.try_recv(),+ Err(mpsc::TryRecvError::Empty)+ ));+ control.resume().unwrap();+ }+ assert!(matches!(+ observed.recv_timeout(WAIT).unwrap(),+ Install::Entry+ ));+ assert_eq!(control.status(), VmStatus::Running);+ });+ }+}++#[test]+fn pause_during_restore_startup_parks_vcpus_before_guest_entry() {+ let (backend, observed) = backend(Failure::None);+ let (release, hold) = mpsc::channel();+ *backend.hold_last.lock().unwrap() = Some(hold);+ let entries = backend.inner.entries();+ let mut vm = Vm::with_restored_ram(ram(), machine(COUNT), || Ok(backend)).unwrap();++ drive(&mut vm, false, |control, _| {+ while !matches!(+ observed.recv_timeout(WAIT).unwrap(),+ Install::Cpu(id, _) if id == u32::from(COUNT - 1)+ ) {}+ control.request_pause().unwrap();+ // Observe acceptance before the last vCPU's setup hold can time out.+ let deadline = Instant::now() + WAIT / 2;+ while control.status() == VmStatus::Running && Instant::now() < deadline {+ thread::sleep(Duration::from_millis(1));+ }+ let status = control.status();+ release.send(()).unwrap();+ assert_eq!(+ status,+ VmStatus::Pausing,+ "pause must be accepted during setup"+ );+ control.wait_paused(WAIT).unwrap();++ assert_eq!(control.status(), VmStatus::Paused);+ assert!(entries.lock().unwrap().is_empty());+ control.resume().unwrap();+ while !matches!(observed.recv_timeout(WAIT).unwrap(), Install::Entry) {}+ });+}++#[test]+fn stop_before_all_vcpus_are_ready_skips_final_platform_restore_and_guest_entry() {+ let (backend, observed) = backend(Failure::None);+ let (release, hold) = mpsc::channel();+ *backend.hold_last.lock().unwrap() = Some(hold);+ let entries = backend.inner.entries();+ let mut vm = Vm::with_restored_ram(ram(), machine(COUNT), || Ok(backend)).unwrap();++ drive(&mut vm, false, |control, _| {+ while !matches!(+ observed.recv_timeout(WAIT).unwrap(),+ Install::Cpu(id, _) if id == u32::from(COUNT - 1)+ ) {}+ control.stop();+ release.send(()).unwrap();+ });++ let mut last_ready = false;+ for event in observed.try_iter() {+ match event {+ Install::Notified(id, _) if id == u32::from(COUNT - 1) => last_ready = true,+ Install::AfterVcpus(_) | Install::Entry => panic!("unexpected event: {event:?}"),+ _ => {}+ }+ }+ assert!(last_ready);+ assert!(entries.lock().unwrap().is_empty());+}++#[test]+fn stop_wins_over_a_later_platform_restore_failure() {+ for injected in [Failure::AfterVcpus, Failure::BeforeVcpus] {+ let (backend, observed) = backend(injected);+ let (release, hold) = mpsc::channel();+ *backend.hold_failure.lock().unwrap() = Some(hold);+ let entries = backend.inner.entries();+ let mut vm = Vm::with_restored_ram(ram(), machine(COUNT), || Ok(backend)).unwrap();++ drive(&mut vm, false, |control, driver| {+ loop {+ match (injected, observed.recv_timeout(WAIT).unwrap()) {+ (Failure::BeforeVcpus, Install::BeforeVcpus(owner))+ | (Failure::AfterVcpus, Install::AfterVcpus(owner)) => {+ assert_eq!(owner, driver);+ break;+ }+ (_, Install::Entry) => panic!("guest entered during platform restore"),+ _ => {}+ }+ }+ control.stop();+ release.send(()).unwrap();+ });++ assert!(entries.lock().unwrap().is_empty());+ assert!(+ !observed+ .try_iter()+ .any(|event| matches!(event, Install::Entry))+ );+ }+}++#[test]+fn run_reports_install_failures_wakes_pause_waiters_and_joins_every_started_vcpu() {+ use boxlite_hypervisor::Error as HostError;++ for injected in [+ Failure::BeforeVcpus,+ Failure::AfterVcpus,+ Failure::PlatformPanic,+ Failure::CreateCpu,+ Failure::RestoreRegs,+ Failure::NotifyStopped,+ Failure::InitialPark,+ Failure::CpuPanic,+ ] {+ let (backend, observed) = backend(injected);+ let calls = backend.inner.log();+ let entries = backend.inner.entries();+ let create_attempts = Arc::clone(&backend.create_attempts);+ let ram = ram();+ let backing = Arc::downgrade(ram.boot_memory());+ let mut vm = Vm::with_restored_ram(ram, machine(COUNT), || Ok(backend)).unwrap();+ let control = vm.control();+ control.request_pause().unwrap();+ let error = thread::scope(|scope| {+ let (ready, started) = mpsc::channel();+ let (reply, result) = mpsc::channel();+ let control = &control;+ scope.spawn(move || {+ ready.send(()).unwrap();+ reply+ .send(control.wait_paused(Duration::from_secs(30)))+ .unwrap();+ });+ started.recv_timeout(WAIT).unwrap();+ let driver = scope.spawn(|| vm.run());+ let _stop = StopOnDrop(control);+ assert!(+ matches!(+ result.recv_timeout(WAIT).unwrap(),+ Err(Error::Control {+ operation: "wait_paused",+ reason: ControlReason::TerminalOutcome,+ })+ ),+ "{injected:?}"+ );+ driver.join().unwrap().unwrap_err()+ });+ assert_eq!(control.status(), VmStatus::Exited);+ assert!(matches!(vm.run(), Err(Error::AlreadyRan)));+ assert!(entries.lock().unwrap().is_empty(), "{injected:?}");+ let events: Vec<_> = observed.try_iter().collect();+ assert!(!events.iter().any(|event| matches!(event, Install::Entry)));+ assert_eq!(+ events+ .iter()+ .any(|event| matches!(event, Install::AfterVcpus(_))),+ matches!(injected, Failure::AfterVcpus | Failure::InitialPark)+ );++ let expected_drops: &[u32] = match (&error, injected) {+ (+ Error::Hypervisor(HostError::VmState {+ operation: "restore before vCPUs",+ source,+ }),+ Failure::BeforeVcpus,+ ) if source.to_string() == "injected install failure" => {+ assert!(matches!(events.as_slice(), [Install::BeforeVcpus(_)]));+ assert_eq!(create_attempts.load(Ordering::SeqCst), 0);+ &[]+ }+ (+ Error::Hypervisor(HostError::VmState {+ operation: "restore after vCPUs",+ source,+ }),+ Failure::AfterVcpus,+ ) if source.to_string() == "injected install failure" => &[0, 1, 2],+ (Error::Snapshot(source), Failure::PlatformPanic)+ if source.to_string() == "platform restore panicked" =>+ {+ &[]+ }+ (Error::Hypervisor(HostError::CreateVcpu { id: 1, source }), Failure::CreateCpu)+ if source.to_string() == "injected install failure" =>+ {+ &[0, 2]+ }+ (+ Error::Hypervisor(HostError::ConfigureVcpu {+ id: 1,+ operation: "restore CPU state",+ source,+ }),+ Failure::RestoreRegs,+ )+ | (+ Error::Hypervisor(HostError::ConfigureVcpu {+ id: 1,+ operation: "notify guest stopped",+ source,+ }),+ Failure::InitialPark | Failure::NotifyStopped,+ ) if source.to_string() == "injected install failure" => &[0, 1, 2],+ (Error::VcpuPanicked { vcpu: 1 }, Failure::CpuPanic) => &[0, 1, 2],+ _ => panic!("unexpected error for {injected:?}: {error:?}"),+ };+ let mut dropped: Vec<_> = calls+ .lock()+ .unwrap()+ .iter()+ .filter_map(|call| match call {+ Call::DropVcpu { id } => Some(*id),+ _ => None,+ })+ .collect();+ dropped.sort_unstable();+ assert_eq!(dropped, expected_drops);+ assert!(backing.upgrade().is_some());+ assert!(+ !calls+ .lock()+ .unwrap()+ .iter()+ .any(|call| matches!(call, Call::Unmap { .. }))+ );++ drop(vm);+ assert!(backing.upgrade().is_none(), "{injected:?}");+ assert!(matches!(+ calls.lock().unwrap().last(),+ Some(Call::Unmap { .. })+ ));+ }+}++fn flat_config(vcpu_count: u8, memory_mib: u32) -> VmConfig {+ VmConfig {+ vcpu_count,+ memory_mib,+ kernel: "unused".into(),+ cmdline: String::new(),+ initramfs: None,+ disks: vec![],+ filesystem: None,+ vsock: None,+ network: None,+ virtio_console: false,+ hotplug_mib: 0,+ }+}++fn flat_vm(vcpu_count: u8, program: &[u8]) -> Vm<KvmVm> {+ Vm::with_backend(+ flat_config(vcpu_count, 1),+ KvmVm::new,+ |ram, _| Ok(crate::flat_guest::load(ram.boot_memory(), program)),+ |_, _| Ok(()),+ )+ .unwrap()+}++// inc dword [0x8000]; jmp back, using the flat guest's identity mapping.+const INCREMENT: &[u8] = &[0xff, 0x05, 0x00, 0x80, 0x00, 0x00, 0xeb, 0xf8];++struct SnapshotFiles {+ state: PathBuf,+ memory: PathBuf,+}++impl SnapshotFiles {+ fn new(dir: &Path, name: &str) -> Self {+ let base = dir.join(name);+ Self {+ state: base.with_extension("state"),+ memory: base.with_extension("memory"),+ }+ }++ fn remove(&self) {+ fs::remove_file(&self.state).unwrap();+ fs::remove_file(&self.memory).unwrap();+ }+}++fn export_after_progress(+ control: &VmControl,+ files: &SnapshotFiles,+ timeout: Duration,+ mut progressed: impl FnMut(&Path) -> bool,+) {+ let deadline = Instant::now() + timeout;+ loop {+ control.resume().unwrap();+ thread::sleep(Duration::from_millis(10));+ control.request_pause().unwrap();+ control.wait_paused(WAIT).unwrap();+ control.export(&files.state, &files.memory).unwrap();+ if progressed(&files.memory) {+ return;+ }+ assert!(+ Instant::now() < deadline,+ "guest counters did not advance for {}",+ files.memory.display()+ );+ files.remove();+ }+}++#[test]+#[ignore = "requires /dev/kvm"]+fn kvm_export_restores_and_resumes() {+ let mut source_vm = flat_vm(1, &[0xeb, 0xfe]);+ let dir = tempfile::tempdir().unwrap();+ let files = SnapshotFiles::new(dir.path(), "source");+ drive(&mut source_vm, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ control.export(&files.state, &files.memory).unwrap();+ });+ drop(source_vm);++ let header = Header::read(&mut File::open(&files.state).unwrap()).unwrap();+ assert_eq!(header.vcpus, 1);+ assert_eq!(header.ram_len, 1 << 20);+ let mut restored = Vm::from_state(&files.state, &files.memory).unwrap();+ drive(&mut restored, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ control.resume().unwrap();+ assert_eq!(control.status(), VmStatus::Running);+ });+}++#[test]+#[ignore = "requires /dev/kvm"]+fn kvm_export_destroy_restore_resume_continues_counter() {+ let mut source_vm = flat_vm(1, INCREMENT);+ let dir = tempfile::tempdir().unwrap();+ let source = SnapshotFiles::new(dir.path(), "source");+ let destination = SnapshotFiles::new(dir.path(), "destination");+ let resumed = SnapshotFiles::new(dir.path(), "resumed");+ drive(&mut source_vm, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ export_after_progress(control, &source, WAIT, |path| counter(path) > 0);+ });+ drop(source_vm);++ let saved = counter(&source.memory);+ let mut restored = Vm::from_state(&source.state, &source.memory).unwrap();+ drive(&mut restored, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ control+ .export(&destination.state, &destination.memory)+ .unwrap();+ assert_eq!(counter(&destination.memory), saved);+ export_after_progress(control, &resumed, WAIT, |path| counter(path) > saved);+ });+}++#[test]+#[ignore = "requires /dev/kvm"]+fn kvm_split_ram_export_destroy_restore_resume_continues_both_counters() {+ use std::io::{Read, Seek, SeekFrom};++ use crate::{+ boot::{BOOT_LEAF, entry::long_mode_entry},+ flat_guest::CODE,+ x86_boot_layout::plan_boot_tables,+ };++ const MEMORY_MIB: u32 = 3073;+ const LOW_RAM_LEN: u64 = 3072 << 20;+ const RAM_LEN: u64 = (MEMORY_MIB as u64) << 20;+ const LOW_COUNTER: u32 = 0x8000;+ const HIGH_COUNTER: u64 = 0x1_0000_0000;+ const RELEASE: GuestAddress = GuestAddress(LOW_COUNTER as u64 + 4);+ const INITIAL: [u32; 2] = [0x1234_5678, 0x9abc_def0];++ let mut source_memory = None;+ let mut source_vm = Vm::with_backend(+ flat_config(1, MEMORY_MIB),+ KvmVm::new,+ |ram, _| {+ source_memory = Some(Arc::clone(ram.boot_memory()));+ // Park at the release byte after both initial increments. After+ // resume, each INC reads its saved counter and writes the next value.+ let mut program = vec![0xbf]; // mov edi, LOW_COUNTER+ program.extend_from_slice(&LOW_COUNTER.to_le_bytes());+ program.extend_from_slice(&[0x48, 0xbb]); // mov rbx, HIGH_COUNTER+ program.extend_from_slice(&HIGH_COUNTER.to_le_bytes());+ program.extend_from_slice(&[+ 0xff, 0x07, // inc dword [rdi]+ 0xff, 0x03, // inc dword [rbx]+ 0x80, 0x7f, 0x04, 0x00, // wait: cmp byte [rdi + 4], 0+ 0x74, 0xfa, // je wait+ 0xff, 0x07, // inc dword [rdi]+ 0xff, 0x03, // inc dword [rbx]+ 0xeb, 0xfe, // jmp $ (keep the final counters stable)+ ]);+ let memory = ram.boot_memory().as_ref();+ memory+ .write_obj(INITIAL[0], GuestAddress(u64::from(LOW_COUNTER)))+ .unwrap();+ memory+ .write_obj(INITIAL[1], GuestAddress(HIGH_COUNTER))+ .unwrap();+ memory.write_slice(&program, GuestAddress(CODE)).unwrap();+ let ranges: Vec<_> = ram.ranges().collect();+ let plan = plan_boot_tables(+ &ranges,+ (CODE, CODE + program.len() as u64),+ None,+ BOOT_LEAF,+ )+ .unwrap();+ Ok(long_mode_entry(memory, CODE, 0, &plan).unwrap())+ },+ |_, _| Ok(()),+ )+ .unwrap();++ let dir = tempfile::tempdir().unwrap();+ let files = SnapshotFiles::new(dir.path(), "split-ram");+ let read_counters = |path: &Path| {+ let mut file = File::open(path).unwrap();+ assert_eq!(file.metadata().unwrap().len(), RAM_LEN);+ // Packed high RAM follows the low band directly in the memory file.+ [u64::from(LOW_COUNTER), LOW_RAM_LEN].map(|offset| {+ file.seek(SeekFrom::Start(offset)).unwrap();+ let mut bytes = [0; 4];+ file.read_exact(&mut bytes).unwrap();+ u32::from_le_bytes(bytes)+ })+ };++ let memory = source_memory.unwrap();+ let checkpoint = INITIAL.map(|value| value + 1);+ let timeout = Duration::from_secs(10);+ drive(&mut source_vm, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ control.resume().unwrap();+ let deadline = Instant::now() + timeout;+ while memory.read_obj::<u32>(GuestAddress(HIGH_COUNTER)).unwrap() != checkpoint[1] {+ assert!(+ Instant::now() < deadline,+ "source guest missed its checkpoint"+ );+ thread::sleep(Duration::from_millis(10));+ }+ control.request_pause().unwrap();+ control.wait_paused(WAIT).unwrap();+ // The release byte takes effect when the restored vCPU resumes.+ memory.write_obj(1u8, RELEASE).unwrap();+ control.export(&files.state, &files.memory).unwrap();+ let header = Header::read(&mut File::open(&files.state).unwrap()).unwrap();+ assert_eq!(header.ram_len, RAM_LEN);+ assert_eq!(+ read_counters(&files.memory),+ checkpoint,+ "packed source counters"+ );+ });+ drop(memory);+ drop(source_vm);++ let advanced = checkpoint.map(|value| value + 1);+ let mut restored = Vm::from_state(&files.state, &files.memory).unwrap();+ drive(&mut restored, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ files.remove();+ export_after_progress(control, &files, Duration::from_secs(120), |path| {+ let counters = read_counters(path);+ for ((counter, saved), next) in counters.into_iter().zip(checkpoint).zip(advanced) {+ assert!(+ (saved..=next).contains(&counter),+ "unexpected packed restored counter"+ );+ }+ counters == advanced+ });+ });+}++#[test]+#[ignore = "requires /dev/kvm"]+fn kvm_three_vcpu_export_destroy_restore_resume_preserves_worker_state() {+ // Only the BSP receives boot registers. APs wait for INIT/SIPI.+ let mut source_vm = flat_vm(3, INCREMENT);+ let dir = tempfile::tempdir().unwrap();+ let source = SnapshotFiles::new(dir.path(), "source");+ let destination = SnapshotFiles::new(dir.path(), "destination");+ let resumed = SnapshotFiles::new(dir.path(), "resumed");+ drive(&mut source_vm, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ export_after_progress(control, &source, WAIT, |path| counter(path) > 0);+ });+ drop(source_vm);++ let read_machine = |path: &Path| {+ let mut file = File::open(path).unwrap();+ let header = Header::read(&mut file).unwrap();+ assert_eq!(header.vcpus, 3);+ header.read_machine(&mut file).unwrap()+ };+ let before = read_machine(&source.state);+ // LAPIC IDs distinguish the APs even when their reset registers agree.+ for i in 0..3 {+ for j in i + 1..3 {+ assert_ne!(before.vcpus[i].state.lapic, before.vcpus[j].state.lapic);+ }+ }+ let saved = counter(&source.memory);+ let mut restored = Vm::from_state(&source.state, &source.memory).unwrap();+ drive(&mut restored, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ control+ .export(&destination.state, &destination.memory)+ .unwrap();+ let after = read_machine(&destination.state);+ for (id, (before, after)) in before.vcpus.iter().zip(&after.vcpus).enumerate() {+ assert_eq!(before.id as usize, id);+ assert_eq!(after.id as usize, id);+ assert_eq!(before.state.regs, after.state.regs, "vCPU {id} registers");+ assert_eq!(before.state.sregs, after.state.sregs, "vCPU {id} sregs");+ assert_eq!(before.state.lapic, after.state.lapic, "vCPU {id} LAPIC");+ assert_eq!(before.state.cpuid, after.state.cpuid, "vCPU {id} CPUID");+ assert_eq!(before.state.mp_state, after.state.mp_state, "vCPU {id} MP");+ }+ assert_eq!(counter(&destination.memory), saved);+ export_after_progress(control, &resumed, WAIT, |path| counter(path) > saved);+ });+}++fn counter(path: &Path) -> u32 {+ use std::io::{Read, Seek, SeekFrom};++ let mut file = File::open(path).unwrap();+ file.seek(SeekFrom::Start(0x8000)).unwrap();+ let mut bytes = [0; 4];+ file.read_exact(&mut bytes).unwrap();+ u32::from_le_bytes(bytes)+}++#[expect(+ clippy::duplicate_mod,+ reason = "Share boot fixtures without exposing private production test modules."+)]+#[path = "../boot/initramfs.rs"]+mod linux_initramfs;++fn linux_snapshot(files: &SnapshotFiles) -> (MachineState, Vec<u8>) {+ let mut file = File::open(&files.state).unwrap();+ let header = Header::read(&mut file).unwrap();+ let machine = header.read_machine(&mut file).unwrap();+ let ram = fs::read(&files.memory).unwrap();+ assert_eq!(ram.len() as u64, header.ram_len);+ (machine, ram)+}++/// APIC_TMCCT is a 32-bit countdown derived by KVM from host time, even while+/// Paused. Its entire four bytes are excluded on both sides of comparisons.+/// Initial count (0x380) and LVT timer (0x320) remain compared, preserving guest+/// timer reprogramming signals.+const APIC_TMCCT: std::ops::RangeInclusive<usize> = 0x390..=0x393;++/// Compare all LAPIC bytes except the four-byte APIC_TMCCT derived from host+/// time. Initial count and LVT timer still detect guest timer reprogramming;+/// PPR and the reserved bytes after APIC_TMCCT remain strictly compared here.+fn lapic_timer_state_changed(before: &[i8; 1024], after: &[i8; 1024]) -> bool {+ before+ .iter()+ .zip(after)+ .enumerate()+ .any(|(offset, (before, after))| !APIC_TMCCT.contains(&offset) && before != after)+}++fn linux_timer_changed(before: &MachineState, after: &MachineState) -> bool {+ // Linux uses TSC-deadline mode on capable hosts, otherwise LAPIC counters.+ // Unlike TSC/KVM clock reads, reprogramming this MSR requires guest activity.+ let deadline = |machine: &MachineState| {+ machine.vcpus[0]+ .state+ .msrs+ .iter()+ .find(|msr| msr.index == 0x6e0) // IA32_TSC_DEADLINE+ .map(|msr| msr.data)+ };+ lapic_timer_state_changed(+ &before.vcpus[0].state.lapic.regs,+ &after.vcpus[0].state.lapic.regs,+ ) || deadline(before) != deadline(after)+}++/// Returns Paused, after observed progress, or fails at the deadline.+fn linux_wait_for_progress(+ control: &VmControl,+ before: &(MachineState, Vec<u8>),+ files: &SnapshotFiles,+ timeout: Duration,+ wait_for_init: bool,+) -> (MachineState, Vec<u8>) {+ let deadline = std::time::Instant::now() + timeout;+ loop {+ assert!(+ std::time::Instant::now() < deadline,+ "Linux guest progress timed out (wait_for_init={wait_for_init})"+ );+ control.resume().unwrap();+ thread::sleep(Duration::from_millis(200));+ control.request_pause().unwrap();+ control.wait_paused(WAIT).unwrap();+ control.export(&files.state, &files.memory).unwrap();+ let after = linux_snapshot(files);+ files.remove();+ let ready = !wait_for_init+ || String::from_utf8_lossy(&after.1).contains("Run /init as init process");+ if ready && before.1 != after.1 && linux_timer_changed(&before.0, &after.0) {+ let changed = before+ .1+ .chunks(4096)+ .zip(after.1.chunks(4096))+ .filter(|(a, b)| a != b)+ .map(|(a, b)| a.iter().zip(b).filter(|(a, b)| a != b).count())+ .sum::<usize>();+ eprintln!(+ "Linux progress: RAM changed bytes={changed}, timer state changed, wait_for_init={wait_for_init}"+ );+ return after;+ }+ }+}++/// PPR (0xA0) is KVM's derived shadow of the SDM max(TPR, ISRV) rule: retain+/// full TPR when its priority class is >= ISRV's, otherwise use ISRV & 0xF0.+/// KVM refreshes it on TPR/ISR changes, so KVM_GET_LAPIC can return a stale value:+/// a real failure differed only at 0xA0, with source PPR=0xE0 despite TPR=0x10+/// and an empty ISR (canonical PPR=0x10). Source PPR carries no guest state and+/// is excluded from comparison. KVM_SET_LAPIC recomputes PPR. This test allows+/// no vCPU guest entry before re-export, so restored PPR must be canonical.+///+/// APIC_TMCCT is a 32-bit countdown derived by KVM from host time. Its entire+/// four bytes are excluded on both sides. Initial count (0x380) and LVT timer+/// (0x320) remain compared to detect guest timer reprogramming; all remaining+/// bytes must match.+fn lapic_differences(+ expected: &[i8; 1024],+ actual: &[i8; 1024],+) -> std::result::Result<(), String> {+ let isrv = (0..256)+ .rev()+ .find(|&vector| {+ // Eight 32-bit ISR registers occupy 16-byte slots in the APIC page.+ let offset = 0x100 + (vector / 32) * 16 + (vector % 32) / 8;+ actual[offset] as u8 & (1 << (vector & 7)) != 0+ })+ .unwrap_or(0) as u8;+ let tpr = actual[0x80] as u8;+ let ppr = if tpr >> 4 >= isrv >> 4 {+ tpr+ } else {+ isrv & 0xF0+ };+ let mut differences = Vec::new();+ if actual[0xA0] as u8 != ppr {+ differences.push(format!(+ "0xA0 PPR: expected canonical {ppr:#04x}, actual {:#04x}",+ actual[0xA0] as u8+ ));+ }+ for (offset, (&expected, &actual)) in expected.iter().zip(actual).enumerate() {+ if offset == 0xA0 || APIC_TMCCT.contains(&offset) || expected == actual {+ continue;+ }+ let register = match offset {+ 0x80 => "TPR",+ 0x100..=0x17F => "ISR",+ 0x180..=0x1FF => "TMR",+ 0x200..=0x27F => "IRR",+ 0x320 => "LVT timer",+ 0x380 => "initial count",+ 0x3E0 => "divide configuration",+ _ => "LAPIC",+ };+ differences.push(format!(+ "{offset:#05x} {register}: expected {:#04x}, actual {:#04x}",+ expected as u8, actual as u8+ ));+ }+ if differences.is_empty() {+ Ok(())+ } else {+ Err(differences.join("; "))+ }+}++#[test]+#[ignore = "requires Linux x86_64 with access to /dev/kvm"]+fn kvm_linux_device_less_export_destroy_restore_resume_makes_progress() {+ let dir = tempfile::tempdir().unwrap();+ let initramfs = dir.path().join("init.cpio");+ // /init repeatedly nanosleeps for 10 ms. No device, console, /dev/mem,+ // fixed physical address or host-side RAM writes provide the signal.+ #[rustfmt::skip]+ let init = linux_initramfs::static_program(&[+ 0x68, 0x80, 0x96, 0x98, 0x00, // push 10000000 (tv_nsec)+ 0x6a, 0x00, // push 0 (tv_sec)+ 0x48, 0x89, 0xe7, // again: mov rdi,rsp+ 0x31, 0xf6, // xor esi,esi+ 0xb8, 35, 0, 0, 0, // mov eax,35 (nanosleep)+ 0x0f, 0x05, // syscall+ 0xeb, 0xf2, // jmp again+ ]);+ fs::write(&initramfs, linux_initramfs::newc_archive("init", &init)).unwrap();+ let mut source_vm = Vm::new_device_less(crate::VmConfig {+ vcpu_count: 1,+ memory_mib: 256,+ kernel: std::env::var_os("VMM_KERNEL")+ .expect("run make vmm:boot:host and set VMM_KERNEL to its vmlinux")+ .into(),+ cmdline: "console=null panic=0".into(),+ initramfs: Some(initramfs),+ disks: vec![],+ filesystem: None,+ vsock: None,+ network: None,+ virtio_console: false,+ hotplug_mib: 0,+ })+ .unwrap();+ let scratch = SnapshotFiles::new(dir.path(), "scratch");+ let source = SnapshotFiles::new(dir.path(), "source");+ let before = drive(&mut source_vm, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ control.export(&scratch.state, &scratch.memory).unwrap();+ let initial = linux_snapshot(&scratch);+ scratch.remove();+ let ready =+ linux_wait_for_progress(control, &initial, &scratch, Duration::from_secs(30), true);+ drop(initial);+ // Require a second interval after Linux announces /init.+ let before = linux_wait_for_progress(control, &ready, &scratch, WAIT, false);+ drop(ready);+ control.export(&source.state, &source.memory).unwrap();+ let still = linux_snapshot(&source);+ assert!(before.1 == still.1, "RAM must be stable while Paused");+ assert!(+ !linux_timer_changed(&before.0, &still.0),+ "timer configuration changed without guest entry"+ );+ still+ });+ drop(source_vm);++ let mut restored = Vm::from_state(&source.state, &source.memory).unwrap();+ drive(&mut restored, true, |control, _| {+ control.wait_paused(WAIT).unwrap();+ control.export(&scratch.state, &scratch.memory).unwrap();+ let installed = linux_snapshot(&scratch);+ scratch.remove();+ // Installing KVM's wall-clock MSR can update its shared RAM page.+ assert_eq!(+ before.0.vcpus[0].state.regs,+ installed.0.vcpus[0].state.regs+ );+ if let Err(differences) = lapic_differences(+ &before.0.vcpus[0].state.lapic.regs,+ &installed.0.vcpus[0].state.lapic.regs,+ ) {+ panic!("restored LAPIC: {differences}");+ }+ assert_eq!(before.0.platform.irqchips, installed.0.platform.irqchips);+ let after = linux_wait_for_progress(control, &installed, &scratch, WAIT, false);+ assert!(before.1 != after.1);+ assert!(linux_timer_changed(&before.0, &after.0));+ });+}diff --git a/src/vmm/tests/vm/mod.rs b/src/vmm/tests/vm/mod.rsindex 7576796ef..ec0a67e5d 100644--- a/src/vmm/tests/vm/mod.rs+++ b/src/vmm/tests/vm/mod.rs@@ -2377,3 +2377,51 @@ fn a_hotplug_capacity_adds_virtio_mem_and_registers_its_control() {console.finish();}}++#[test]+#[cfg_attr(+ not(target_arch = "x86_64"),+ expect(clippy::unit_arg, reason = "arm64 has no boot registers yet.")+)]+fn devices_updated_vcpu_count_controls_run_vcpu_count() {+ #[cfg(target_arch = "x86_64")]+ let (backend, log) = {+ use crate::mock_vm::Step;+ let backend = MockVm::with_scripts(vec![vec![Step::Shutdown], vec![Step::Shutdown]]);+ let log = backend.log();+ (backend, log)+ };+ #[cfg(not(target_arch = "x86_64"))]+ let backend = MockVm::new();++ let mut vm = Vm::with_devices(+ config(1, 16),+ || Ok(backend),+ |_, _| Ok(BootRegisters::default()),+ |_, _, config, _| {+ config.vcpu_count = 2;+ Ok(())+ },+ )+ .unwrap();++ assert_eq!(vm.vcpu_count, 2);+ #[cfg(target_arch = "x86_64")]+ {+ assert_eq!(vm.run().unwrap(), crate::VmExit::GuestShutdown);+ let calls = log.lock().unwrap();+ let feature_calls: Vec<_> = calls+ .iter()+ .filter(|call| matches!(call, Call::SetCpuFeatures { .. }))+ .copied()+ .collect();+ assert_eq!(feature_calls.len(), 2, "got {calls:?}");+ assert!(+ feature_calls.contains(&Call::SetCpuFeatures { id: 0 })+ && feature_calls.contains(&Call::SetCpuFeatures { id: 1 }),+ "expected both vCPUs to start after devices updated vcpu_count, got {calls:?}"+ );+ }+ #[cfg(not(target_arch = "x86_64"))]+ let _ = &mut vm;+}