Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(vmm): add reversible pause and resume on VmControl (#2965)

lfld2874e6843498870
diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.md
index 6ba1b78f5..ca66c1b53 100644
--- a/docs/contributing/architecture/vmm/README.md
+++ b/docs/contributing/architecture/vmm/README.md
@@ -91,7 +91,7 @@ need no hypervisor.
| Create a vCPU | `Vm::create_vcpu`, on the thread that will run it | `hv_vcpu_create`, which also returns the `hv_vcpu_exit_t` the vCPU reports its exits in | `KVM_CREATE_VCPU`, then `mmap` of its `kvm_run`; `KVM_ARM_VCPU_INIT` on arm64, with secondaries powered off (`KVM_ARM_VCPU_POWER_OFF`) | `WHvCreateVirtualProcessor` |
| Set boot registers | x86_64: `X86Vcpu::set_cpu_features`, then `X86Vcpu::set_boot_registers`; arm64 adds its own extension trait | `hv_vcpu_set_reg`, `hv_vcpu_set_sys_reg` | `KVM_SET_ONE_REG` on arm64; on x86_64 `KVM_SET_CPUID2`, then `KVM_SET_MSRS`, `KVM_SET_REGS`, `KVM_SET_FPU` and `KVM_SET_SREGS`, in Firecracker's order ([Firecracker `src/vmm/src/arch/x86_64/vcpu.rs:222–301`](https://github.com/firecracker-microvm/firecracker/blob/68698adfee9b252df130b7a98e3ba04eb81f0f54/src/vmm/src/arch/x86_64/vcpu.rs#L222-L301)); unlike Firecracker, the VMM leaves the local APIC LINT pins in their KVM reset state, ExtINT on the boot vCPU LINT0, and Linux programs LINT1 itself | `WHvSetVirtualProcessorRegisters` |
| Run to the next exit | `Vcpu::run` → `VcpuExit` | `hv_vcpu_run` | `KVM_RUN` | `WHvRunVirtualProcessor` |
-| Complete pending I/O before stop or state capture | `Vcpu::complete_pending_io`; no further guest instruction executes | write the read result and advance PC without `hv_vcpu_run` | `KVM_RUN` with `immediate_exit` set; KVM completes the access before checking it | finish emulation and update registers/RIP without `WHvRunVirtualProcessor` |
+| Complete pending I/O before stop or state capture | Dispatch exits from `Vcpu::complete_pending_io` until `Ok(IoCompletion::Done)` | Write the read result and advance PC without `hv_vcpu_run` | `KVM_RUN` with `immediate_exit` set may return more exits from the same instruction | Finish emulation and update registers/RIP without `WHvRunVirtualProcessor` |
| Read the exit | the backend decodes it into a `VcpuExit` | `hv_vcpu_exit_t`: the reason and, for an exception, the syndrome and guest address | `kvm_run.exit_reason` and its union | the `WHV_RUN_VP_EXIT_CONTEXT` that `WHvRunVirtualProcessor` fills |
| Kick from another thread | `VcpuHandle::kick` | `hv_vcpus_exit` | set `immediate_exit`, then signal the vCPU thread | `WHvCancelRunVirtualProcessor` |
| Set an interrupt line | `Vm::set_irq_line` | `hv_gic_set_spi` | `KVM_IRQ_LINE` | a userspace IOAPIC, in a crate M10 picks, then `WHvRequestInterrupt` |
@@ -191,11 +191,15 @@ inside the guest; only the exits below reach the VMM.
`VcpuExit` (`src/hypervisor/src/exit.rs`) is what `run` returns. MMIO and port
data borrow a per-vCPU buffer inside the backend, as in libkrun and kvm-ioctls.
-The VMM therefore handles an exit before it runs that vCPU again, and the next
-`run` completes the guest's instruction. Before stopping or saving state, the
-VMM releases the borrowed exit and calls `complete_pending_io` instead. That
-operation succeeds without guest execution when nothing is pending, and a
-successfully completed access is not completed again.
+The VMM handles each exit before it runs that vCPU again. The next `run`
+continues the guest's instruction. Before stopping or saving state, the
+VMM releases the borrowed exit and calls `complete_pending_io`. If it receives
+`Ok(IoCompletion::Exit(exit))`, it handles that exit and releases its borrow
+before calling again. For example, KVM can return a second MMIO fragment or the
+write phase of a read-modify-write instruction. `Ok(IoCompletion::Done)` confirms
+completion without executing another guest instruction. With no pending I/O,
+completion is a no-op. `IoCompletion` is `#[must_use]` even after the caller
+unwraps the `Result`.
| Exit | Meaning | HVF | KVM | WHP (M10) |
| --- | --- | --- | --- | --- |
@@ -434,8 +438,9 @@ worker slot synchronously.
- `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.
- - It then loops: run, dispatch the exit through the chipset, run again.
- - An idle vCPU waits inside the host, never in a VMM thread. KVM's in-kernel
+ - Before each guest entry, a vCPU checks the pause and stop state. It waits
+ on a condition variable while parked.
+ - When the VM is running, idle vCPUs wait inside the host. KVM's in-kernel
irqchip waits out `HLT`; with the in-kernel GIC, HVF waits out `WFI` inside
`hv_vcpu_run` and wakes the vCPU for its vtimer and for SPIs set from any
thread, as an M5 Pro on macOS 27 showed
@@ -465,8 +470,9 @@ worker slot synchronously.
cleanup; quiesce success does not imply snapshot support or delivery of
buffered network traffic.
- **The `run()` thread.**
- - It waits on one poller for stop requests, vCPU outcomes and device
- failures.
+ - 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.
- The poller is `mio`, which uses epoll on Linux and kqueue on macOS and is
already in `Cargo.lock` through tokio. rust-vmm's event-manager and crosvm's
`WaitContext` are epoll-only.
@@ -498,14 +504,35 @@ sink to take the rest, and bytes it never takes are counted as dropped and
logged.
The driver holds exclusive access to `Vm` throughout `run`. `VmControl`
-provides backend-independent runtime controls. External threads use `status()`,
-`stop()`, and `resize_disk()` without holding the VM itself.
-`StopHandle::stop` uses the same latch.
-
-`VmStatus` starts at `Created`, advances to `Running` as the driver starts,
-and becomes `Stopping` on a stop request or when the driver processes a
-terminal event. A stop in `Created` goes directly to `Stopping`, so the
-first `run` skips vCPU creation and takes the usual cleanup path.
+provides backend-independent runtime controls. External threads use
+`status()`, `stop()`, `request_pause()`, `wait_paused(timeout)`, `resume()`, and
+`resize_disk()` without holding the VM itself. `StopHandle::stop` uses the
+same stop latch.
+
+`VmStatus` normally moves from `Created` to `Running`. A device-less VM
+can reserve its first pause in `Created`. It keeps that status until
+`run` claims the reservation and enters `Pausing` before releasing the
+vCPU start gate. Every vCPU parks before its first guest entry.
+
+During execution, `request_pause()` posts a command in a single-slot mailbox.
+The driver accepts it in `Running`, enters `Pausing`, and kicks the vCPUs.
+At `checkpoint`, each vCPU owner dispatches exits from `complete_pending_io`
+until it returns `Ok(IoCompletion::Done)`, then calls `notify_guest_stopped`. A
+terminal exit or error returns immediately without acknowledging the pause. The
+checkpoint also skips acknowledgement if a stop arrived during completion.
+The driver publishes `Paused` after one acknowledgement from each vCPU.
+`resume()` uses the same slot and epoch to reopen guest entry and return to
+`Running`. The mailbox lock serializes admission against concurrent clones. A
+pure poller wake prompts the driver to check the mailbox. Terminal events use
+the same poller and keep their queue priority.
+
+`request_pause()` posts the request and wakes the driver without waiting.
+`wait_paused(timeout)` observes the reserved, queued, or active epoch and its
+timeout leaves the pause in place.
+
+A stop or terminal event moves the VM to `Stopping`, releases parked vCPUs,
+and wakes pending control calls with `TerminalOutcome`. A stop in `Created`
+lets the first `run` skip vCPU creation and take the usual cleanup path.
The first terminal event determines the outcome of an active run.
On teardown, the driver joins all scoped vCPUs, shuts down virtio workers,
diff --git a/docs/contributing/architecture/vmm/kvm.md b/docs/contributing/architecture/vmm/kvm.md
index c71e130e7..523c69599 100644
--- a/docs/contributing/architecture/vmm/kvm.md
+++ b/docs/contributing/architecture/vmm/kvm.md
@@ -391,7 +391,7 @@ sequenceDiagram
host_api-->>thread0: KVM_RUN returns EINTR
%% edge:kvm_12_e5
host_api-->>thread1: KVM_RUN returns EINTR
- Note over thread0,host_api: Finish any pending device access with KVM_RUN and immediate_exit set<br/>KVM completes that access without executing another guest instruction
+ Note over thread0,host_api: Complete pending I/O with KVM_RUN and immediate_exit set<br/>Dispatch each follow-up exit and repeat until no I/O remains<br/>The stop latch prevents a pause acknowledgement
%% edge:kvm_12_e6
thread0-->>coordinator: Exit loop, join T0
%% edge:kvm_12_e7
diff --git a/src/hypervisor/README.md b/src/hypervisor/README.md
index 02ef191be..e5baa6540 100644
--- a/src/hypervisor/README.md
+++ b/src/hypervisor/README.md
@@ -89,12 +89,18 @@ assembly, and persistence.
### Save
-Stop all vCPUs and IRQ producers, then call `Vcpu::complete_pending_io` on each
-vCPU's owning thread. Begin the round with `X86Vm::save_state`, then call
-`X86Vcpu::save_state` once per vCPU on its owning thread. A failed vCPU save can
-be retried in the same round. Finish all vCPU saves before starting another
-round. KVM timers can advance during capture, and PIT restore can lose
-sub-tick timing.
+Keep all vCPUs out of the guest and stop IRQ producers. On each vCPU's owning
+thread, call `Vcpu::complete_pending_io` until it returns `Ok(IoCompletion::Done)`.
+Dispatch each `Ok(IoCompletion::Exit(exit))` and release its borrow before the
+next call. Split MMIO can produce multiple exits for one instruction. A
+terminal exit or completion error aborts capture. Both `VcpuExit` and
+`IoCompletion` are `#[must_use]`: discarding either after unwrapping its
+`Result` triggers a lint.
+
+Begin the round with `X86Vm::save_state`, then call `X86Vcpu::save_state` once
+per vCPU on its owning thread. A failed vCPU save can be retried in the same
+round. Finish all vCPU saves before starting another round. KVM timers can
+advance during capture, and PIT restore can lose sub-tick timing.
### Restore
diff --git a/src/hypervisor/src/exit.rs b/src/hypervisor/src/exit.rs
index 9ec7bd56d..6120cf36c 100644
--- a/src/hypervisor/src/exit.rs
+++ b/src/hypervisor/src/exit.rs
@@ -3,6 +3,23 @@
//! Decoded vCPU exits shared by host backends and the VMM.
+/// Completion status of a pending guest I/O operation.
+#[must_use = "handle any returned exit and repeat complete_pending_io until Done"]
+#[derive(Debug)]
+pub enum IoCompletion<'a> {
+ /// No pending I/O remains.
+ Done,
+ /// Another exit from the same guest instruction must be handled before repeating.
+ Exit(VcpuExit<'a>),
+}
+
+impl IoCompletion<'_> {
+ /// Returns `true` if the completion has finished with no remaining I/O.
+ pub fn is_done(&self) -> bool {
+ matches!(self, Self::Done)
+ }
+}
+
/// A guest exit requiring VMM handling, without backend-specific state.
///
/// [`Vcpu::run`](crate::Vcpu::run) ties `'a` to its mutable vCPU borrow: MMIO
@@ -15,8 +32,10 @@
/// Handling an access supplies the device response but does not complete the
/// guest instruction. The backend must finish pending I/O on re-entry. Before
/// stopping the vCPU or saving its state, the caller releases the exit borrow
-/// and calls [`Vcpu::complete_pending_io`](crate::Vcpu::complete_pending_io)
-/// to finish the access without executing further instructions.
+/// and calls [`Vcpu::complete_pending_io`](crate::Vcpu::complete_pending_io).
+/// Handle each `Ok(IoCompletion::Exit(exit))` and release its borrow before
+/// calling again, until `Ok(IoCompletion::Done)` confirms no I/O remains.
+#[must_use = "vCPU exits must be handled; discarding an exit drops guest I/O completions"]
#[derive(Debug)]
pub enum VcpuExit<'a> {
/// Read from an emulated device; fill the entire buffer before re-entry.
diff --git a/src/hypervisor/src/hvf/vcpu.rs b/src/hypervisor/src/hvf/vcpu.rs
index a0228156e..07fa68a1a 100644
--- a/src/hypervisor/src/hvf/vcpu.rs
+++ b/src/hypervisor/src/hvf/vcpu.rs
@@ -15,7 +15,7 @@ use super::{
psci::{self, PsciCall},
syndrome::{MmioAccess, Syndrome, SysRegAccess},
};
-use crate::{Arm64BootRegisters, CpuOnResult, Error, Result, VcpuExit};
+use crate::{Arm64BootRegisters, CpuOnResult, Error, IoCompletion, Result, VcpuExit};
/// An HVF vCPU, bound to the thread that created it.
///
@@ -152,8 +152,9 @@ impl HvfVcpu {
/// Finishes a handled access without executing another guest instruction.
/// A second completion is a no-op; a failure keeps the access pending.
- pub fn complete_pending_io(&mut self) -> Result<()> {
+ pub fn complete_pending_io(&mut self) -> Result<IoCompletion<'_>> {
self.finish_pending()
+ .map(|()| IoCompletion::Done)
.map_err(|source| Error::CompletePendingIo {
id: self.id,
source,
@@ -314,7 +315,7 @@ impl crate::Vcpu for HvfVcpu {
Self::run(self)
}
- fn complete_pending_io(&mut self) -> Result<()> {
+ fn complete_pending_io(&mut self) -> Result<IoCompletion<'_>> {
Self::complete_pending_io(self)
}
diff --git a/src/hypervisor/src/kvm/vcpu.rs b/src/hypervisor/src/kvm/vcpu.rs
index 0464e2697..a8df3a920 100644
--- a/src/hypervisor/src/kvm/vcpu.rs
+++ b/src/hypervisor/src/kvm/vcpu.rs
@@ -31,7 +31,11 @@ use super::{
},
kick::WorkerSignal,
};
-use crate::{Error, Result, VcpuExit, x86::MAX_SNAPSHOT_MSR_ENTRIES};
+use crate::{
+ Error, IoCompletion, Result, VcpuExit,
+ vcpu::{PendingIo, PendingIoStep},
+ x86::MAX_SNAPSHOT_MSR_ENTRIES,
+};
/// Number of u32 words in kvm_xsave.region, before its flexible-array tail.
const XSAVE_REGION_WORDS: usize = 1024;
@@ -409,6 +413,10 @@ impl KvmVcpu {
});
}
}
+ self.decode_last_exit()
+ }
+
+ fn decode_last_exit(&mut self) -> Result<VcpuExit<'_>> {
// Reborrow after rust-vmm's exit: its port variants omit the count that
// distinguishes a single access from a repeated string transfer.
let run = self.fd.get_kvm_run();
@@ -419,9 +427,10 @@ impl KvmVcpu {
}
/// Finishes handled I/O without executing another guest instruction.
- /// A second completion is a no-op; failures retain the pending access.
- pub fn complete_pending_io(&mut self) -> Result<()> {
- self.pending_io
+ /// Handle each returned exit and call again until [`IoCompletion::Done`].
+ pub fn complete_pending_io(&mut self) -> Result<IoCompletion<'_>> {
+ let completion = self
+ .pending_io
.complete(|| {
self.fd.clear_tsc_save_anchor();
self.fd.set_kvm_immediate_exit(1);
@@ -432,7 +441,11 @@ impl KvmVcpu {
.map_err(|source| Error::CompletePendingIo {
id: self.id,
source,
- })
+ })?;
+ match completion {
+ PendingIoStep::Done => Ok(IoCompletion::Done),
+ PendingIoStep::Exit => self.decode_last_exit().map(IoCompletion::Exit),
+ }
}
/// Notifies an enabled KVM pvclock that its vCPU was stopped.
@@ -454,7 +467,7 @@ impl crate::Vcpu for KvmVcpu {
Self::run(self)
}
- fn complete_pending_io(&mut self) -> Result<()> {
+ fn complete_pending_io(&mut self) -> Result<IoCompletion<'_>> {
Self::complete_pending_io(self)
}
@@ -489,27 +502,6 @@ impl crate::X86Vcpu for KvmVcpu {
}
}
-#[derive(Debug, Default)]
-struct PendingIo(bool);
-
-impl PendingIo {
- fn complete(&mut self, enter: impl FnOnce() -> io::Result<()>) -> io::Result<()> {
- if !self.0 {
- return Ok(());
- }
- match enter() {
- Err(error) if error.raw_os_error() == Some(libc::EINTR) => {
- self.0 = false;
- Ok(())
- }
- Err(error) => Err(error),
- Ok(()) => Err(io::Error::other(
- "KVM_RUN returned an exit during I/O completion",
- )),
- }
- }
-}
-
// SAFETY: run must begin a live, exclusively borrowed mapping of run_size bytes.
// No vCPU may enter KVM while the returned exit borrows that mapping.
unsafe fn decode_exit(id: u32, run: &mut kvm_run, run_size: usize) -> Result<VcpuExit<'_>> {
@@ -1834,23 +1826,4 @@ mod tests {
let max_cycles = ns_to_tsc_cycles(elapsed.as_nanos() as u64, state.tsc_khz);
assert!(restored_tsc.wrapping_sub(saved_tsc) <= max_cycles);
}
-
- #[test]
- fn completion_consumes_pending_io_only_after_interrupted_reentry() {
- let mut pending = PendingIo::default();
- pending.complete(|| panic!("no pending I/O")).unwrap();
- pending.0 = true;
- let error = pending
- .complete(|| Err(io::Error::from_raw_os_error(libc::EIO)))
- .unwrap_err();
- assert_eq!(error.raw_os_error(), Some(libc::EIO));
- assert!(pending.0);
- assert!(pending.complete(|| Ok(())).is_err());
- assert!(pending.0);
- pending
- .complete(|| Err(io::Error::from_raw_os_error(libc::EINTR)))
- .unwrap();
- assert!(!pending.0);
- pending.complete(|| panic!("must not enter twice")).unwrap();
- }
}
diff --git a/src/hypervisor/src/kvm/vm.rs b/src/hypervisor/src/kvm/vm.rs
index e8b93970e..391fe1ffc 100644
--- a/src/hypervisor/src/kvm/vm.rs
+++ b/src/hypervisor/src/kvm/vm.rs
@@ -629,7 +629,7 @@ mod tests {
cpu.run().unwrap(),
VcpuExit::IoOut { port: 0x80, .. }
));
- cpu.complete_pending_io().unwrap();
+ assert!(cpu.complete_pending_io().unwrap().is_done());
vm.save_state().unwrap();
let error = cpu.save_state().unwrap_err();
assert!(
@@ -735,7 +735,7 @@ mod tests {
ready.send(()).unwrap();
if wait_for_capture.recv().is_ok() {
if matches!(order, CaptureOrder::NoopIoCompletion) {
- second.complete_pending_io().unwrap();
+ assert!(second.complete_pending_io().unwrap().is_done());
}
saved.send(second.save_state().unwrap()).unwrap();
}
@@ -1368,7 +1368,7 @@ mod tests {
VcpuExit::IoOut { port: 0x81, bytes } => assert_eq!(bytes, &[VECTOR]),
exit => panic!("expected output after LAPIC EOI, got {exit:?}"),
}
- cpu.complete_pending_io().unwrap();
+ assert!(cpu.complete_pending_io().unwrap().is_done());
// SAFETY: GET_IRQCHIP initialized the redirection entries as raw bits.
assert_eq!(
unsafe { read_ioapic(&vm).redirtbl[PIN].bits } & REMOTE_IRR,
@@ -1574,7 +1574,7 @@ mod tests {
source.save_state().unwrap_err(),
"complete pending I/O before saving",
);
- source.complete_pending_io().unwrap();
+ assert!(source.complete_pending_io().unwrap().is_done());
let platform = vm.save_state().unwrap();
let mut state = crate::X86Vcpu::save_state(&mut source).unwrap();
assert_eq!(state.regs.rip, 0x104c);
@@ -1712,7 +1712,7 @@ mod tests {
bsp.run().unwrap(),
VcpuExit::IoOut { port: 0x81, .. }
));
- bsp.complete_pending_io().unwrap();
+ assert!(bsp.complete_pending_io().unwrap().is_done());
});
let mut ap = vm.create_vcpu(1).unwrap();
@@ -1773,7 +1773,7 @@ mod tests {
VcpuExit::IoOut { port: 0x80, bytes } => assert_eq!(bytes, b"S"),
exit => panic!("expected AP output at the SIPI vector, got {exit:?}"),
}
- ap_dst.complete_pending_io().unwrap();
+ assert!(ap_dst.complete_pending_io().unwrap().is_done());
}
#[test]
@@ -1834,7 +1834,7 @@ mod tests {
source.run().unwrap(),
VcpuExit::IoOut { port: 0x80, .. }
));
- source.complete_pending_io().unwrap();
+ assert!(source.complete_pending_io().unwrap().is_done());
let platform = vm.save_state().unwrap();
let state = source.save_state().unwrap();
// The standard XSAVE layout starts YMM_Hi128 at byte 576.
@@ -1931,7 +1931,11 @@ mod tests {
VcpuExit::Interrupted
));
assert_eq!(vcpu.fd.get_regs().unwrap().rip, before.rip);
- crate::Vcpu::complete_pending_io(&mut vcpu).unwrap();
+ assert!(
+ crate::Vcpu::complete_pending_io(&mut vcpu)
+ .unwrap()
+ .is_done()
+ );
drop(vcpu);
handle.kick().unwrap();
}
@@ -2125,7 +2129,7 @@ mod tests {
vm.create_vcpu(0),
Err(Error::CreateVcpu { id: 0, .. })
));
- vcpu.complete_pending_io().unwrap();
+ assert!(vcpu.complete_pending_io().unwrap().is_done());
let mut segments = vcpu.fd.get_sregs().unwrap();
segments.cs.base = 0;
segments.cs.selector = 0;
@@ -2146,9 +2150,9 @@ mod tests {
}
// The I/O exit leaves instruction completion pending until KVM_RUN.
// Complete it without reaching HLT, which can wait in the kernel.
- vcpu.complete_pending_io().unwrap();
+ assert!(vcpu.complete_pending_io().unwrap().is_done());
assert_eq!(vcpu.fd.get_regs().unwrap().rip, 0x1006);
- vcpu.complete_pending_io().unwrap();
+ assert!(vcpu.complete_pending_io().unwrap().is_done());
assert_eq!(vcpu.fd.get_regs().unwrap().rip, 0x1006);
assert_eq!(vcpu.fd.get_kvm_run().immediate_exit, 0);
crate::VcpuHandle::kick(&vcpu.handle()).unwrap();
diff --git a/src/hypervisor/src/lib.rs b/src/hypervisor/src/lib.rs
index f0f62bc6e..be921f022 100644
--- a/src/hypervisor/src/lib.rs
+++ b/src/hypervisor/src/lib.rs
@@ -31,7 +31,7 @@ pub use x86::{X86BootRegisters, X86CpuidEntry, X86Msr, X86Segment, X86Vcpu, X86V
pub use x86::{X86IrqchipState, X86VcpuState, X86VmState};
pub use error::{Error, Result};
-pub use exit::VcpuExit;
+pub use exit::{IoCompletion, VcpuExit};
pub use memory::MemoryRegion;
pub use vcpu::{Vcpu, VcpuHandle};
pub use vm::Vm;
diff --git a/src/hypervisor/src/vcpu.rs b/src/hypervisor/src/vcpu.rs
index d5a52d87e..53cadf09a 100644
--- a/src/hypervisor/src/vcpu.rs
+++ b/src/hypervisor/src/vcpu.rs
@@ -3,7 +3,10 @@
//! The vCPU contract, and the handle other threads use to kick a vCPU.
-use crate::{Result, VcpuExit};
+#[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]
+use std::io;
+
+use crate::{IoCompletion, Result, VcpuExit};
/// A vCPU, bound to the thread that created it.
///
@@ -19,11 +22,13 @@ pub trait Vcpu {
/// Completes a handled MMIO or port access without executing another
/// guest instruction, before stopping the vCPU or saving its state.
///
- /// The caller first supplies any read response and releases the exit's
- /// borrowed buffer. With no pending access this succeeds without entering
- /// the guest. Successful completion consumes the pending access, so a
- /// subsequent call does not complete it twice.
- fn complete_pending_io(&mut self) -> Result<()>;
+ /// Supply any read response and release the exit's borrowed buffer before
+ /// calling. `Ok(IoCompletion::Exit(exit))` reports another exit from the
+ /// same instruction, such as a split MMIO fragment, a read-modify-write
+ /// phase, or a terminal exit. Handle it and release its borrow before
+ /// calling again. `Ok(IoCompletion::Done)` means no I/O remains and
+ /// repeat calls are no-ops.
+ fn complete_pending_io(&mut self) -> Result<IoCompletion<'_>>;
/// Notifies the guest that its clock was interrupted, while stopped on
/// the owning thread. An unused guest clock is a successful no-op; backends
@@ -44,6 +49,37 @@ pub trait Vcpu {
fn handle(&self) -> Self::Handle;
}
+#[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]
+#[derive(Debug, Default)]
+pub(crate) struct PendingIo(pub(crate) bool);
+
+#[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) enum PendingIoStep {
+ Done,
+ Exit,
+}
+
+#[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]
+impl PendingIo {
+ pub(crate) fn complete(
+ &mut self,
+ enter: impl FnOnce() -> io::Result<()>,
+ ) -> io::Result<PendingIoStep> {
+ if !self.0 {
+ return Ok(PendingIoStep::Done);
+ }
+ match enter() {
+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {
+ self.0 = false;
+ Ok(PendingIoStep::Done)
+ }
+ Err(error) => Err(error),
+ Ok(()) => Ok(PendingIoStep::Exit),
+ }
+ }
+}
+
#[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]
pub(crate) fn kvmclock_ctrl_result(result: std::io::Result<()>) -> std::io::Result<()> {
match result {
@@ -62,10 +98,13 @@ pub trait VcpuHandle: Clone + Send + Sync {
fn kick(&self) -> Result<()>;
}
+#[cfg(test)]
+#[path = "../tests/vcpu/mod.rs"]
+mod pending_io_tests;
+
#[cfg(test)]
mod tests {
use super::*;
- use std::io;
#[test]
fn kvmclock_inactive_pvclock_is_a_noop() {
@@ -93,7 +132,7 @@ mod tests {
unreachable!()
}
- fn complete_pending_io(&mut self) -> Result<()> {
+ fn complete_pending_io(&mut self) -> Result<IoCompletion<'_>> {
unreachable!()
}
diff --git a/src/hypervisor/tests/hvf/mod.rs b/src/hypervisor/tests/hvf/mod.rs
index 138ed99ba..2ca67b8ea 100644
--- a/src/hypervisor/tests/hvf/mod.rs
+++ b/src/hypervisor/tests/hvf/mod.rs
@@ -698,9 +698,9 @@ fn completing_a_read_without_entry_writes_it_once_and_moves_past_it() {
code.extend(a64::psci(PSCI_SYSTEM_OFF));
let mut vcpu = guest.vcpu(&code);
answer_read(&mut vcpu, 0, 8, 0x55);
- vcpu.complete_pending_io().unwrap();
+ assert!(vcpu.complete_pending_io().unwrap().is_done());
// A second completion has nothing left to do.
- vcpu.complete_pending_io().unwrap();
+ assert!(vcpu.complete_pending_io().unwrap().is_done());
assert_eq!(next_write(&mut vcpu), (8, 0x55));
}
@@ -773,7 +773,7 @@ fn completing_mmio_at_the_last_virtual_instruction_wraps_pc() {
check(unsafe { ffi::hv_vcpu_get_reg(vcpu.vcpu, ffi::HV_REG_PC, &mut pc) }).unwrap();
assert_eq!(pc, u64::MAX - 3, "the guest reached the boundary itself");
eprintln!("MMIO exit at PC {pc:#018x}");
- vcpu.complete_pending_io().unwrap();
+ assert!(vcpu.complete_pending_io().unwrap().is_done());
// SAFETY: completion keeps the vCPU alive on this thread without guest entry.
check(unsafe { ffi::hv_vcpu_get_reg(vcpu.vcpu, ffi::HV_REG_PC, &mut pc) }).unwrap();
assert_eq!(pc, 0, "completion wraps the 64-bit PC");
diff --git a/src/hypervisor/tests/snapshot/mod.rs b/src/hypervisor/tests/snapshot/mod.rs
index 3f0f5197c..d0fef69d9 100644
--- a/src/hypervisor/tests/snapshot/mod.rs
+++ b/src/hypervisor/tests/snapshot/mod.rs
@@ -272,7 +272,7 @@ fn fpu_postcard_rejects_non_abi_lengths() {
#[test]
fn snapshot_defaults_fail_closed_for_an_unsnapshotable_backend() {
- use crate::{MemoryRegion, Vcpu, VcpuExit, VcpuHandle, Vm, X86Vcpu, X86Vm};
+ use crate::{IoCompletion, MemoryRegion, Vcpu, VcpuExit, VcpuHandle, Vm, X86Vcpu, X86Vm};
struct Backend;
struct Cpu;
#[derive(Clone)]
@@ -287,7 +287,7 @@ fn snapshot_defaults_fail_closed_for_an_unsnapshotable_backend() {
fn run(&mut self) -> crate::Result<VcpuExit<'_>> {
panic!("unexpected guest entry")
}
- fn complete_pending_io(&mut self) -> crate::Result<()> {
+ fn complete_pending_io(&mut self) -> crate::Result<IoCompletion<'_>> {
panic!("unexpected I/O completion")
}
fn handle(&self) -> Handle {
diff --git a/src/hypervisor/tests/vcpu/mod.rs b/src/hypervisor/tests/vcpu/mod.rs
new file mode 100644
index 000000000..e0d7603e7
--- /dev/null
+++ b/src/hypervisor/tests/vcpu/mod.rs
@@ -0,0 +1,55 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+use std::io;
+
+use super::{PendingIo, PendingIoStep};
+
+#[test]
+fn completion_without_pending_io_skips_entry() {
+ let mut pending = PendingIo::default();
+ assert_eq!(
+ pending.complete(|| panic!("no pending I/O")).unwrap(),
+ PendingIoStep::Done
+ );
+}
+
+#[test]
+fn interrupted_entry_consumes_pending_io() {
+ let errors = [
+ io::Error::from(io::ErrorKind::Interrupted),
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ io::Error::from_raw_os_error(libc::EINTR),
+ ];
+ for error in errors {
+ let mut pending = PendingIo(true);
+ assert_eq!(
+ pending.complete(|| Err(error)).unwrap(),
+ PendingIoStep::Done
+ );
+ assert!(!pending.0);
+ assert_eq!(
+ pending
+ .complete(|| panic!("I/O already completed"))
+ .unwrap(),
+ PendingIoStep::Done
+ );
+ }
+}
+
+#[test]
+fn failed_entry_preserves_pending_io() {
+ let mut pending = PendingIo(true);
+ let error = pending
+ .complete(|| Err(io::Error::other("test I/O error")))
+ .unwrap_err();
+ assert_eq!(error.to_string(), "test I/O error");
+ assert!(pending.0);
+}
+
+#[test]
+fn successful_kvm_reentry_can_return_a_follow_up_exit() {
+ let mut pending = PendingIo(true);
+ assert_eq!(pending.complete(|| Ok(())).unwrap(), PendingIoStep::Exit);
+ assert!(pending.0);
+}
diff --git a/src/vmm/README.md b/src/vmm/README.md
index a0b531ca6..c283a7e9e 100644
--- a/src/vmm/README.md
+++ b/src/vmm/README.md
@@ -35,15 +35,15 @@ boxlite-vmm
| Module | Responsibility |
| --- | --- |
| `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, stop requests, and disk resize by configured ID |
-| `lifecycle` | `Lifecycle` coordinates the one-shot run with the shared stop latch |
+| `control` | `VmControl` provides runtime controls for VM status, pause, resume, stop, and disk resize by configured ID |
+| `lifecycle` | `Lifecycle` coordinates the one-shot run, pause epochs, and the shared stop latch |
| `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 |
| `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, run the guest and dispatch its exits until the VM ends |
+| `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 |
| `bus` | `Bus`, `BusRange` and `BusDevice`, and `Buses::dispatch`, which serves the MMIO and port exits of a vCPU |
| `virtio` | The virtio common infrastructure: the synchronous device contract (`VirtioDevice`, `DeviceSpec`, `DeviceEvent`, `ActivationContext`, `EventRegistrar`, `Waker`, `WorkerControl`), the `VirtQueues` facade (dense preparation and validation, EVENT_IDX, exactly-once deferred completion, notification drain, the stored guest-memory view and negotiated indirect flag, and `save`/`restore` stubs that report snapshots unsupported until M8), the 4 KiB virtio-mmio transport (register file, feature negotiation, queue configuration and activation, Status=0 reset, post-activation queue-write rejection), `mmio::add_device`, which attaches any device through that transport, the MMIO interrupt handle, the default snapshot methods, and the virtio workers (`VirtioWorkers` over a `WorkerRuntime`; `SharedRuntime` runs every device's events on one thread) |
@@ -51,7 +51,7 @@ boxlite-vmm
| `devices` | `devices::add_all`, the one composition helper (add a device type as one `add_slot_device` line), the console queue, internal virtio-net device, output-only virtio console device, and on x86_64 the 8250 UART at COM1, the CMOS RTC and the i8042 reset, with `add_legacy_devices` |
| `devices::balloon` | Reporting-only `VirtioBalloon`: configuration, negotiation, whole-chain prevalidation and a `ReclaimPolicy` chosen when the device is constructed; `devices::add_all` composes it after the disks, so it never renumbers them |
| `virtio::worker` | One lazy shared poller/thread, coalesced generation-bound queue kicks, backend readiness, stop barriers and VM shutdown |
-| `events` | `Event`, which ends the VM, `EventSender`, which also latches the stop, and `EventLoop`, the poller that waits for the first event |
+| `events` | `Event`, which ends the VM, `EventSender`, which queues terminal events or wakes the driver for control work, and `EventLoop`, which polls for both |
The Linux x86_64 native engine composes disks, reporting balloon, aggregate
virtio-fs, Unix-backed vsock, gvproxy stream networking and virtio-console.
@@ -647,18 +647,41 @@ socket and guest-memory tests; real-guest qualification remains separate.
`Vm::run(&mut self)` blocks on the thread that owns the VM. Call
`vm.control()` before the run and pass clones of the `VmControl` to threads
-that need to read `status()`, request `stop()`, or call
-[`resize_disk()`](#virtio-block-device). Dropping the clones has no effect
-on execution. A VM created with the device-less test helper returns
+that observe or control execution or call [`resize_disk()`](#virtio-block-device).
+Dropping the clones has no effect on execution. A VM created with the
+device-less test helper returns
`InvalidInput` for disk resize because its registry is empty.
| `VmStatus` | Meaning |
| --- | --- |
-| `Created` | The VM is ready for its first run. |
+| `Created` | The VM is ready for its first run, with or without an initial pause reservation. |
| `Running` | The driver has started the run, including vCPU setup. |
+| `Pausing` | Guest entry is closing and the driver is collecting vCPU acknowledgements. |
+| `Paused` | Every vCPU is parked outside the guest. |
| `Stopping` | A stop was requested or the driver is handling a terminal event. |
| `Exited` | The run finished teardown, or the owner dropped the VM. |
+`request_pause()` requires an empty userspace chipset. If the VM has devices,
+it returns `Error::Control` with `ControlReason::UnsupportedDevice`. In
+`Created`, the first `request_pause()` reserves the initial pause and returns immediately.
+The driver enters `Pausing` before releasing the vCPU start gate, so every
+vCPU parks before its first guest entry. The VM reports `Created` until `run`
+starts. A second reservation or a `resume()` in `Created` returns `InvalidState`.
+
+In `Running`, `request_pause()` enqueues `Running → Pausing → Paused`, wakes the
+driver, and returns immediately without waiting. `wait_paused(timeout)` waits
+for the reserved, queued, or active pause epoch and leaves the pause in place on
+`DeadlineTimeout`. A zero timeout checks the current state immediately. With no
+reserved, queued, or active pause, the operation returns `InvalidState`.
+
+`resume()` returns once the driver reopens the guest entry gate and the VM
+returns to `Running`. It requires `Paused`. Pause and resume share a
+single-slot mailbox, so a pending request blocks other clones from submitting
+another request. Stop and terminal events release parked vCPUs. Pending
+resume calls and `wait_paused` return `TerminalOutcome` when the VM is
+stopping or has exited. New `request_pause()` and `resume()` calls in those states return
+`InvalidState`.
+
`Vm::run` runs on x86_64, against any backend that implements
`boxlite_hypervisor::X86Vm`; unit tests drive it on the mock backend. Before
it registers any RAM, `Vm::with_backend` builds the `Chipset` from the
@@ -671,18 +694,27 @@ nothing mapped.
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.
-2. Each worker then loops: check the stop latch, run, and hand the exit to
- `Chipset::dispatch`. `Shutdown` sends `GuestShutdown` and `Reset` sends
- `GuestReset`; a run error, any other exit, such as `Halted`, which KVM never
- returns with its in-kernel irqchip, or a panic caught around the worker
- sends `VcpuFailed`. A worker that sees the latch completes the pending
- access and returns without sending.
+2. Before each guest entry, the worker calls `checkpoint` and checks the stop
+ latch. To park, it calls `complete_pending_io` and dispatches each
+ `Ok(IoCompletion::Exit(exit))` until completion returns `Ok(IoCompletion::Done)`.
+ It then calls `notify_guest_stopped` and acknowledges the pause epoch if the
+ VM is still live. A terminal exit, error, or concurrent stop skips the
+ acknowledgement.
+ During normal entry and I/O completion, the worker uses `Chipset::dispatch`
+ to serve device accesses. `Shutdown` sends `GuestShutdown` and `Reset` sends
+ `GuestReset`. An error, unexpected exit such as `Halted`, or a panic caught
+ around the worker sends `VcpuFailed`. A worker that sees the stop latch
+ drains pending I/O and preserves the latched outcome.
3. `EventSender::send` sets the stop latch before it queues, so the vCPU
that sends, such as the one whose `0xFE` reached the i8042, never enters
- the guest again. `run` takes the first event from the `EventLoop`, kicks
- every vCPU, and joins them all before it returns: `StopRequested`,
- `GuestShutdown` and `GuestReset` become `VmExit`, and `VcpuFailed` or
- `DeviceFailed` its error. Later events are dropped.
+ the guest again. `run` takes the first event from the `EventLoop`, opens
+ the start gate for teardown, releases and kicks the vCPUs, and joins them
+ all before it returns. Before joining, shutdown retries kicks that fail
+ with `WouldBlock` or `Interrupted`, including when the terminal event
+ interrupts a pause. Kicking an exited vCPU is a successful no-op; other
+ kick errors and panics are logged without retrying that kick.
+ `StopRequested`, `GuestShutdown` and `GuestReset` become `VmExit`, and
+ `VcpuFailed` or `DeviceFailed` its error. Later events are dropped.
4. Once every vCPU joins, `run` shuts down the [virtio workers](#virtio-workers),
which join dispatch and quiesce every device: console drains published TX,
@@ -789,11 +821,11 @@ are built from. `Vm` owns the chipset they form.
- **Events.** A device ends the VM by sending `Event::GuestReset` or
`Event::DeviceFailed` through an `EventSender`, which never blocks or
panics, latches the stop for every vCPU, and wakes the `EventLoop`'s `mio`
- poller. vCPU workers and lifecycle controls send the other events. An event sent
- after the loop is gone is logged at debug level and discarded. `EventLoop::wait` returns
- the oldest event, or `None` at its timeout, and rechecks the queue every
- second in case a wake-up was lost. Every event ends the VM; the VMM never
- restarts a guest.
+ poller. vCPU workers and lifecycle controls send the other events. An event
+ sent after the loop is gone is logged at debug level and discarded.
+ `EventLoop::wait` returns the oldest terminal event or `None` after a
+ control wake or timeout. The driver uses `RECHECK` to revisit the mailbox
+ and terminal queue every second while idle in case a wake-up was lost.
## Virtio-mmio transport
@@ -1347,6 +1379,10 @@ sparse anonymous `mmap`: the host needs virtual address space for the full
mapping, and accessed pages still depend on available memory and host memory
pressure.
+The `lifecycle::tests::kvm` tests exercise pause, resume, and stop on device-less
+guests. The split MMIO case pauses after the first read or write fragment and
+checks that the second fragment is handled before the vCPU parks.
+
The [bus](#buses-lines-and-events) and [chipset](#chipset) tests in `tests::kvm`
modules need 2 MiB: a flat 32-bit guest writes and reads a test device on the
port bus at its register offset, and an `IrqLine` sets GSI 4 and 5 through
diff --git a/src/vmm/src/chipset.rs b/src/vmm/src/chipset.rs
index a8e2fa1d5..fc0607ebf 100644
--- a/src/vmm/src/chipset.rs
+++ b/src/vmm/src/chipset.rs
@@ -327,7 +327,7 @@ pub(crate) struct Chipset {
impl Chipset {
/// Whether the chipset contains any userspace devices.
- #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub(crate) fn is_empty(&self) -> bool {
self._devices.is_empty()
}
diff --git a/src/vmm/src/control.rs b/src/vmm/src/control.rs
index 0aa9210ef..9c11ce33d 100644
--- a/src/vmm/src/control.rs
+++ b/src/vmm/src/control.rs
@@ -7,6 +7,7 @@ use std::{collections::HashMap, io, sync::Arc, time::Duration};
use crate::{
MemoryStatus,
+ error::Result,
lifecycle::{Lifecycle, VmStatus},
virtio::blk::control::{self, Controls, DiskSender},
};
@@ -34,6 +35,28 @@ impl VmControl {
self.lifecycle.stop();
}
+ /// Reserves an initial pause in `Created`, or posts a pause request for a
+ /// running device-less VM and wakes the run driver without waiting. Callers
+ /// can observe completion with [`Self::wait_paused`].
+ pub fn request_pause(&self) -> Result<()> {
+ self.lifecycle.request_pause()
+ }
+
+ /// Reopens guest entry for a paused VM after the run driver accepts it.
+ pub fn resume(&self) -> Result<()> {
+ self.lifecycle.resume()
+ }
+
+ /// Waits for the current pause epoch, including a reserved or queued pause.
+ /// A zero timeout checks the current condition while holding the lock.
+ ///
+ /// `Ok(())` confirms that the target pause epoch completed; callers that
+ /// need the VM to stay quiescent must serialize against concurrent
+ /// [`Self::resume`] calls on cloned handles.
+ pub fn wait_paused(&self, timeout: Duration) -> Result<()> {
+ self.lifecycle.wait_paused(timeout)
+ }
+
/// Grows the named writable disk to `bytes`, returning its capacity.
/// The target must be sector aligned and no smaller than its current
/// capacity. Actual growth notifies the guest; the current size is a no-op.
diff --git a/src/vmm/src/events.rs b/src/vmm/src/events.rs
index bdfeff1c8..cf12ca5d9 100644
--- a/src/vmm/src/events.rs
+++ b/src/vmm/src/events.rs
@@ -70,8 +70,15 @@ impl EventSender {
self.stopping.store(true, Ordering::SeqCst);
if let Err(mpsc::SendError(event)) = self.events.send(event) {
tracing::debug!(?event, "event sent after the VM ended; discarded");
- } else if let Err(error) = self.waker.wake() {
- tracing::warn!(%error, "event loop wake-up failed; the event waits for the next recheck");
+ } else {
+ self.wake();
+ }
+ }
+
+ /// Prompts the driver to check its mailbox without latching a stop.
+ pub(crate) fn wake(&self) {
+ if let Err(error) = self.waker.wake() {
+ tracing::warn!(%error, "event loop wake-up failed; waiting for the next recheck");
}
}
@@ -87,6 +94,8 @@ pub(crate) struct EventLoop {
readiness: Events,
events: mpsc::Receiver<Event>,
sender: EventSender,
+ #[cfg(test)]
+ before_poll: Option<tests::PollGate>,
}
impl EventLoop {
@@ -105,6 +114,8 @@ impl EventLoop {
waker,
stopping: Arc::new(AtomicBool::new(false)),
},
+ #[cfg(test)]
+ before_poll: None,
})
}
@@ -112,10 +123,10 @@ impl EventLoop {
self.sender.clone()
}
- /// The oldest queued event, waiting up to `timeout`, or forever with
- /// `None`. Returns `Ok(None)` once the timeout passes; a zero timeout
- /// never enters the poller. The poller is re-entered every [`RECHECK`],
- /// so an event whose wake-up failed is still found.
+ /// The oldest queued event, waiting up to `timeout`, or indefinitely
+ /// with `None`. Returns `Ok(None)` on a control wake or timeout. A zero
+ /// timeout checks the queue without polling. The queue is rechecked
+ /// every [`RECHECK`] even when a wake fails.
pub(crate) fn wait(&mut self, timeout: Option<Duration>) -> io::Result<Option<Event>> {
// A timeout too long to add counts as forever.
let deadline = timeout.and_then(|timeout| Instant::now().checked_add(timeout));
@@ -130,8 +141,16 @@ impl EventLoop {
},
None => RECHECK,
};
+ #[cfg(test)]
+ if let Some(gate) = self.before_poll.take() {
+ gate.enter();
+ }
match self.poll.poll(&mut self.readiness, Some(slice)) {
- Ok(()) => {}
+ Ok(()) => {
+ if self.readiness.iter().any(|event| event.token() == WAKE) {
+ return Ok(self.events.try_recv().ok());
+ }
+ }
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error),
}
diff --git a/src/vmm/src/lib.rs b/src/vmm/src/lib.rs
index 16dd7dfc4..dcc7f3299 100644
--- a/src/vmm/src/lib.rs
+++ b/src/vmm/src/lib.rs
@@ -56,7 +56,7 @@ mod hotplug;
mod irq;
pub(crate) mod lifecycle;
mod memory;
-#[cfg(target_arch = "x86_64")]
+#[cfg(any(test, target_arch = "x86_64"))]
mod vcpu;
#[cfg_attr(
not(test),
diff --git a/src/vmm/src/lifecycle.rs b/src/vmm/src/lifecycle.rs
index fd658f0a1..a107020cb 100644
--- a/src/vmm/src/lifecycle.rs
+++ b/src/vmm/src/lifecycle.rs
@@ -1,48 +1,105 @@
// Copyright 2026 BoxLite Contributors
// SPDX-License-Identifier: Apache-2.0
-use std::sync::{Mutex, MutexGuard, PoisonError};
+use std::{
+ sync::{Condvar, Mutex, MutexGuard, PoisonError},
+ time::Duration,
+};
-#[cfg(target_arch = "x86_64")]
-use crate::error::{Error, Result};
-use crate::events::{Event, EventSender};
+use crate::{
+ config::MAX_VCPUS,
+ error::{ControlReason, Error, Result},
+ events::{Event, EventSender},
+};
+
+const _: () = assert!(MAX_VCPUS as u32 <= u64::BITS);
/// The execution state observed through [`VmControl`](crate::VmControl).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum VmStatus {
- /// The VM is ready to run.
+ /// The VM is ready to run, possibly with an initial pause reserved.
Created,
- /// The run has started.
+ /// The run has started and vCPUs may enter the guest.
Running,
+ /// Guest entry is closing while the driver collects vCPU acknowledgements.
+ Pausing,
+ /// Every vCPU is parked outside the guest.
+ Paused,
/// Termination has been requested or the run is tearing down.
Stopping,
/// Execution has finished or the VM has been dropped.
Exited,
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Command {
+ Park(u64),
+ Resume(u64),
+}
+
#[derive(Debug)]
struct LifecycleState {
status: VmStatus,
#[cfg(any(test, target_arch = "x86_64"))]
run_claimed: bool,
sender: Option<EventSender>,
+ /// Exclusive slot for a control operation awaiting the driver.
+ command: Option<Command>,
+ epoch: u64,
+ completed_epoch: u64,
+ #[cfg(any(test, target_arch = "x86_64"))]
+ acknowledgements: u64,
+}
+
+impl LifecycleState {
+ fn is_terminal(&self) -> bool {
+ matches!(self.status, VmStatus::Stopping | VmStatus::Exited)
+ || self.sender.as_ref().is_some_and(EventSender::is_stopping)
+ }
+
+ fn sender(&self) -> &EventSender {
+ self.sender.as_ref().expect("live lifecycle has a sender")
+ }
+
+ #[cfg(any(test, target_arch = "x86_64"))]
+ fn start_pause(&mut self, epoch: u64) {
+ self.epoch = epoch;
+ self.status = VmStatus::Pausing;
+ self.acknowledgements = 0;
+ }
+
+ #[cfg(any(test, target_arch = "x86_64"))]
+ fn acknowledge(&mut self, epoch: u64, id: u8) {
+ if self.status == VmStatus::Pausing && self.epoch == epoch && u32::from(id) < u64::BITS {
+ self.acknowledgements |= 1u64 << id;
+ }
+ }
}
#[derive(Debug)]
pub(crate) struct Lifecycle {
+ device_less: bool,
state: Mutex<LifecycleState>,
+ changed: Condvar,
}
impl Lifecycle {
- pub(crate) fn new(sender: EventSender) -> Self {
+ pub(crate) fn new(sender: EventSender, device_less: bool) -> Self {
Self {
+ device_less,
state: Mutex::new(LifecycleState {
status: VmStatus::Created,
#[cfg(any(test, target_arch = "x86_64"))]
run_claimed: false,
sender: Some(sender),
+ command: None,
+ epoch: 0,
+ completed_epoch: 0,
+ #[cfg(any(test, target_arch = "x86_64"))]
+ acknowledgements: 0,
}),
+ changed: Condvar::new(),
}
}
@@ -56,19 +113,100 @@ impl Lifecycle {
pub(crate) fn stop(&self) {
let mut state = self.state();
- if !matches!(state.status, VmStatus::Created | VmStatus::Running) {
+ if matches!(state.status, VmStatus::Stopping | VmStatus::Exited) {
return;
}
- let Some(sender) = &state.sender else {
- return;
- };
// Serialize setting the vCPU stop latch with admitting the first run.
- sender.send(Event::StopRequested);
+ state.sender().send(Event::StopRequested);
state.status = VmStatus::Stopping;
+ state.command = None;
+ self.changed.notify_all();
}
- /// Claims the run and returns whether to start the vCPUs.
- #[cfg(target_arch = "x86_64")]
+ pub(crate) fn request_pause(&self) -> Result<()> {
+ let mut state = self.state();
+ let invalid = || control_error("request_pause", ControlReason::InvalidState);
+ if state.is_terminal() {
+ return Err(invalid());
+ }
+ if !self.device_less {
+ return Err(control_error(
+ "request_pause",
+ ControlReason::UnsupportedDevice,
+ ));
+ }
+ if state.command.is_some() || !matches!(state.status, VmStatus::Created | VmStatus::Running)
+ {
+ return Err(invalid());
+ }
+ let epoch = state.epoch.checked_add(1).ok_or_else(invalid)?;
+ state.command = Some(Command::Park(epoch));
+ if state.status == VmStatus::Running {
+ state.sender().wake();
+ }
+ Ok(())
+ }
+
+ pub(crate) fn resume(&self) -> Result<()> {
+ let mut state = self.state();
+ if state.is_terminal() || state.status != VmStatus::Paused || state.command.is_some() {
+ return Err(control_error("resume", ControlReason::InvalidState));
+ }
+ let epoch = state.epoch;
+ state.command = Some(Command::Resume(epoch));
+ state.sender().wake();
+ let state = self
+ .changed
+ .wait_while(state, |state| {
+ !state.is_terminal() && state.status == VmStatus::Paused && state.epoch == epoch
+ })
+ .unwrap_or_else(PoisonError::into_inner);
+ if state.is_terminal() {
+ return Err(control_error("resume", ControlReason::TerminalOutcome));
+ }
+ Ok(())
+ }
+
+ pub(crate) fn wait_paused(&self, timeout: Duration) -> Result<()> {
+ let state = self.state();
+ if state.is_terminal() {
+ return Err(control_error("wait_paused", ControlReason::TerminalOutcome));
+ }
+ let epoch = match (state.status, state.command) {
+ (VmStatus::Created | VmStatus::Running, Some(Command::Park(epoch))) => epoch,
+ (VmStatus::Pausing | VmStatus::Paused, _) => state.epoch,
+ _ => return Err(control_error("wait_paused", ControlReason::InvalidState)),
+ };
+ self.await_pause(state, epoch, timeout)
+ .map_err(|reason| control_error("wait_paused", reason))
+ }
+
+ fn await_pause(
+ &self,
+ mut state: MutexGuard<'_, LifecycleState>,
+ epoch: u64,
+ timeout: Duration,
+ ) -> std::result::Result<(), ControlReason> {
+ if !timeout.is_zero() {
+ state = self
+ .changed
+ .wait_timeout_while(state, timeout, |state| {
+ !state.is_terminal() && state.completed_epoch < epoch
+ })
+ .unwrap_or_else(PoisonError::into_inner)
+ .0;
+ }
+ if state.is_terminal() {
+ Err(ControlReason::TerminalOutcome)
+ } else if state.completed_epoch >= epoch {
+ Ok(())
+ } else {
+ Err(ControlReason::DeadlineTimeout)
+ }
+ }
+
+ /// Claims the run and closes guest entry if the first pause was reserved.
+ #[cfg(any(test, target_arch = "x86_64"))]
pub(crate) fn begin_run(&self) -> Result<bool> {
let mut state = self.state();
if state.run_claimed || state.status == VmStatus::Exited {
@@ -78,22 +216,99 @@ impl Lifecycle {
if state.status == VmStatus::Stopping {
return Ok(false);
}
- state.status = VmStatus::Running;
+ if let Some(Command::Park(epoch)) = state.command.take() {
+ state.start_pause(epoch);
+ } else {
+ state.status = VmStatus::Running;
+ }
Ok(true)
}
- #[cfg(target_arch = "x86_64")]
+ /// Handles commands and acknowledgements on the run thread. Returns
+ /// whether to kick workers that may still be inside the guest.
+ #[cfg(any(test, target_arch = "x86_64"))]
+ pub(crate) fn drive(&self, count: u8) -> bool {
+ let mut state = self.state();
+ if state.is_terminal() {
+ return false;
+ }
+ match state.command.take() {
+ Some(Command::Park(epoch)) => {
+ state.start_pause(epoch);
+ return true;
+ }
+ Some(Command::Resume(epoch)) if state.epoch == epoch => {
+ state.status = VmStatus::Running;
+ self.changed.notify_all();
+ }
+ _ => {}
+ }
+ let all = u64::MAX >> (u64::BITS - u32::from(count));
+ if state.status == VmStatus::Pausing && state.acknowledgements & all == all {
+ state.completed_epoch = state.epoch;
+ state.status = VmStatus::Paused;
+ self.changed.notify_all();
+ }
+ false
+ }
+
+ #[cfg(any(test, target_arch = "x86_64"))]
+ pub(crate) fn checkpoint(
+ &self,
+ id: u8,
+ mut park: impl FnMut() -> Result<Option<Event>>,
+ ) -> Result<Option<Event>> {
+ if !self.device_less {
+ return Ok(None);
+ }
+ let mut state = self.state();
+ while matches!(state.status, VmStatus::Pausing | VmStatus::Paused) && !state.is_terminal() {
+ let epoch = state.epoch;
+ drop(state);
+ if let Some(event) = park()? {
+ return Ok(Some(event));
+ }
+ state = self.state();
+ if !state.is_terminal() {
+ state.acknowledge(epoch, id);
+ state.sender().wake();
+ }
+ state = self
+ .changed
+ .wait_while(state, |state| {
+ state.epoch == epoch
+ && matches!(state.status, VmStatus::Pausing | VmStatus::Paused)
+ && !state.is_terminal()
+ })
+ .unwrap_or_else(PoisonError::into_inner);
+ }
+ Ok(None)
+ }
+
+ #[cfg(any(test, target_arch = "x86_64"))]
pub(crate) fn mark_stopping(&self) {
- self.state().status = VmStatus::Stopping;
+ let mut state = self.state();
+ if !state.is_terminal() {
+ state.sender().send(Event::StopRequested);
+ }
+ state.status = VmStatus::Stopping;
+ state.command = None;
+ self.changed.notify_all();
}
pub(crate) fn mark_exited(&self) {
let mut state = self.state();
state.status = VmStatus::Exited;
+ state.command = None;
drop(state.sender.take());
+ self.changed.notify_all();
}
}
+fn control_error(operation: &'static str, reason: ControlReason) -> Error {
+ Error::Control { operation, reason }
+}
+
#[cfg(test)]
#[path = "../tests/lifecycle/mod.rs"]
mod tests;
diff --git a/src/vmm/src/vcpu.rs b/src/vmm/src/vcpu.rs
index 9675ddfd4..5533a93d4 100644
--- a/src/vmm/src/vcpu.rs
+++ b/src/vmm/src/vcpu.rs
@@ -6,30 +6,40 @@
//! 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.
+#[cfg(target_arch = "x86_64")]
use std::{
panic::{self, AssertUnwindSafe},
sync::{Condvar, Mutex, PoisonError},
};
-use boxlite_hypervisor::{Vcpu, VcpuExit, X86BootRegisters, X86Vcpu, X86Vm};
+use boxlite_hypervisor::{IoCompletion, Vcpu, VcpuExit};
+#[cfg(target_arch = "x86_64")]
+use boxlite_hypervisor::{X86BootRegisters, X86Vcpu, X86Vm};
use crate::{
chipset::Chipset,
- cpu_features::{BOOT_MSRS, vcpu_cpuid},
error::{Error, Result},
- events::{Event, EventSender},
+ events::Event,
+};
+#[cfg(target_arch = "x86_64")]
+use crate::{
+ cpu_features::{BOOT_MSRS, vcpu_cpuid},
+ events::EventSender,
+ 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.
#[derive(Default)]
+#[cfg(target_arch = "x86_64")]
pub(crate) struct StartGate {
/// Workers that arrived, and whether the gate was aborted.
state: Mutex<(u8, bool)>,
changed: Condvar,
}
+#[cfg(target_arch = "x86_64")]
impl StartGate {
fn arrive_and_wait(&self, count: u8) {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
@@ -49,17 +59,20 @@ impl StartGate {
}
/// 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) chipset: &'a Chipset,
pub(crate) sender: &'a EventSender,
- /// The kick handle of every configured vCPU, for the thread that stops them.
+ pub(crate) lifecycle: &'a Lifecycle,
+ /// The configured vCPUs' kick handles, used for pause and stop.
pub(crate) kicks: &'a Mutex<Vec<<H::Vcpu as Vcpu>::Handle>>,
pub(crate) gate: &'a StartGate,
}
+#[cfg(target_arch = "x86_64")]
impl<H: X86Vm> Workers<'_, H> {
/// The body of the thread of vCPU `id`. A panic in it, such as a device
/// whose lock an earlier panic poisoned, ends the VM with
@@ -103,31 +116,67 @@ impl<H: X86Vm> Workers<'_, H> {
/// Runs the guest until it asks to end, which returns the event, or until
/// another sender ends the VM, which returns `None` after completing the
- /// pending access.
+ /// pending I/O.
fn run_guest(&self, vcpu: &mut H::Vcpu, id: u8) -> Result<Option<Event>> {
loop {
- // Checked before every entry: a stop that lands earlier still
- // returns from the next entry at once, since its kick is pending.
+ if let Some(event) = self
+ .lifecycle
+ .checkpoint(id, || park_vcpu(self.chipset, vcpu, id))?
+ {
+ return Ok(Some(event));
+ }
+ // A stop may have released this worker from its checkpoint.
if self.sender.is_stopping() {
- vcpu.complete_pending_io()?;
+ let _ = complete_pending_io(self.chipset, vcpu, id)?;
return Ok(None);
}
- match self.chipset.dispatch(vcpu.run()?) {
- None | Some(VcpuExit::Interrupted) => {}
- Some(VcpuExit::Shutdown) => return Ok(Some(Event::GuestShutdown)),
- Some(VcpuExit::Reset) => return Ok(Some(Event::GuestReset)),
- Some(exit) => {
- return Err(Error::UnexpectedExit {
- vcpu: id.into(),
- exit: format!("{exit:?}"),
- });
- }
+ let exit = vcpu.run()?;
+ if let Some(event) = handle_exit(self.chipset, id, exit)? {
+ return Ok(Some(event));
}
}
}
}
+#[cfg(target_arch = "x86_64")]
fn catch_panic<T>(id: u8, f: impl FnOnce() -> Result<T>) -> Result<T> {
panic::catch_unwind(AssertUnwindSafe(f))
.unwrap_or_else(|_| Err(Error::VcpuPanicked { vcpu: id.into() }))
}
+
+pub(crate) fn handle_exit(chipset: &Chipset, id: u8, exit: VcpuExit<'_>) -> Result<Option<Event>> {
+ match chipset.dispatch(exit) {
+ None | Some(VcpuExit::Interrupted) => Ok(None),
+ Some(VcpuExit::Shutdown) => Ok(Some(Event::GuestShutdown)),
+ Some(VcpuExit::Reset) => Ok(Some(Event::GuestReset)),
+ Some(exit) => Err(Error::UnexpectedExit {
+ vcpu: id.into(),
+ exit: format!("{exit:?}"),
+ }),
+ }
+}
+
+pub(crate) fn complete_pending_io(
+ chipset: &Chipset,
+ vcpu: &mut impl Vcpu,
+ id: u8,
+) -> Result<Option<Event>> {
+ while let IoCompletion::Exit(exit) = vcpu.complete_pending_io()? {
+ if let Some(event) = handle_exit(chipset, id, exit)? {
+ return Ok(Some(event));
+ }
+ }
+ Ok(None)
+}
+
+pub(crate) fn park_vcpu(chipset: &Chipset, vcpu: &mut impl Vcpu, id: u8) -> Result<Option<Event>> {
+ if let Some(event) = complete_pending_io(chipset, vcpu, id)? {
+ return Ok(Some(event));
+ }
+ match vcpu.notify_guest_stopped() {
+ Err(boxlite_hypervisor::Error::ConfigureVcpu { source, .. })
+ if source.kind() == std::io::ErrorKind::Unsupported => {}
+ result => result?,
+ }
+ Ok(None)
+}
diff --git a/src/vmm/src/vm.rs b/src/vmm/src/vm.rs
index 0aa7d788f..1db26a7b8 100644
--- a/src/vmm/src/vm.rs
+++ b/src/vmm/src/vm.rs
@@ -231,6 +231,11 @@ impl<H: HostVm> Vm<H> {
&host_vm,
)?;
let chipset = chipset.build()?;
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ let device_less = chipset.is_empty();
+ // Public VM constructors and chipset inspection are Linux x86_64-only.
+ #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
+ let device_less = false;
if let Err(error) = ram.map(&*host_vm) {
drop(chipset);
drop(workers);
@@ -243,7 +248,7 @@ impl<H: HostVm> Vm<H> {
return Err(error);
}
- let lifecycle = Arc::new(Lifecycle::new(sender.clone()));
+ let lifecycle = Arc::new(Lifecycle::new(sender.clone(), device_less));
let mut vm = Self {
chipset: Some(chipset),
workers: Some(workers),
@@ -272,20 +277,38 @@ impl<H: HostVm> Vm<H> {
pub fn control(&self) -> VmControl {
self.control.clone()
}
+
+ #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
+ pub(crate) fn lifecycle(&self) -> &Arc<Lifecycle> {
+ &self.lifecycle
+ }
}
#[cfg(target_arch = "x86_64")]
impl<H: boxlite_hypervisor::X86Vm> Vm<H> {
fn run_vcpus(&mut self) -> Result<VmExit> {
- use std::thread;
+ use std::{
+ io::ErrorKind,
+ panic::{self, AssertUnwindSafe},
+ thread,
+ time::Duration,
+ };
- use boxlite_hypervisor::VcpuHandle as _;
+ use boxlite_hypervisor::VcpuHandle;
use crate::{
- events::Event,
+ events::{Event, RECHECK},
+ lifecycle::VmStatus,
vcpu::{StartGate, Workers},
};
+ const KICK_RETRY: Duration = Duration::from_millis(10);
+
+ fn retryable_kick(error: &boxlite_hypervisor::Error) -> bool {
+ matches!(error, boxlite_hypervisor::Error::KickVcpu { source, .. }
+ if matches!(source.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted))
+ }
+
self.fresh_vm = false;
let gate = StartGate::default();
let kicks = Mutex::new(Vec::new());
@@ -295,6 +318,7 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {
boot_regs: &self.boot_regs,
chipset: self.chipset.as_ref().expect("live VM has a chipset"),
sender: &self.sender,
+ lifecycle: &self.lifecycle,
kicks: &kicks,
gate: &gate,
};
@@ -303,6 +327,43 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {
.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> {
+ lifecycle: &'a Lifecycle,
+ gate: &'a StartGate,
+ kicks: &'a Mutex<Vec<H>>,
+ }
+
+ impl<H: VcpuHandle> Drop for StopVcpus<'_, H> {
+ fn drop(&mut self) {
+ self.lifecycle.mark_stopping();
+ self.gate.abort();
+ // 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),
+ );
+ while !pending.is_empty() {
+ pending.retain(|kick| {
+ match panic::catch_unwind(AssertUnwindSafe(|| kick.kick())) {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) if retryable_kick(&error) => return true,
+ Ok(Err(error)) => tracing::warn!(%error, "failed to kick a vCPU"),
+ Err(_) => tracing::warn!("vCPU kick panicked during shutdown"),
+ }
+ false
+ });
+ if !pending.is_empty() {
+ thread::sleep(KICK_RETRY);
+ }
+ }
+ }
+ }
+
+ let _stop = StopVcpus {
+ lifecycle: &self.lifecycle,
+ gate: &gate,
+ kicks: &kicks,
+ };
for id in 0..vcpus.vcpu_count {
let vcpus = &vcpus;
let spawned = thread::Builder::new()
@@ -317,28 +378,51 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {
break;
}
}
- let event = events.wait(None);
- self.lifecycle.mark_stopping();
- if event.is_err() {
- // Without an event the stop latch is still open; close it so
- // the vCPUs stop and the scope can join them.
- vcpus.sender.send(Event::StopRequested);
- }
- // Wake every vCPU still in the guest; a vCPU still being
- // configured sees the latch before its first entry.
- for kick in kicks.lock().unwrap_or_else(PoisonError::into_inner).iter() {
- if let Err(error) = kick.kick() {
- tracing::warn!(%error, "failed to kick a vCPU");
+ let mut pending_kicks = 0u64;
+ loop {
+ let wait = if pending_kicks != 0 {
+ KICK_RETRY
+ } else {
+ RECHECK
+ };
+ match events.wait(Some(wait)) {
+ Ok(Some(event)) => break Ok(event),
+ Err(error) => break Err(error),
+ Ok(None) => {}
+ }
+ let kick_all = self.lifecycle.drive(self.vcpu_count);
+ if !kick_all && pending_kicks == 0 {
+ continue;
+ }
+ if self.lifecycle.status() != VmStatus::Pausing || vcpus.sender.is_stopping() {
+ pending_kicks = 0;
+ continue;
+ }
+ let kicks = kicks.lock().unwrap_or_else(PoisonError::into_inner);
+ // Startup only appends handles, so their indices stay stable.
+ for (index, kick) in kicks.iter().enumerate() {
+ let bit = 1u64 << index;
+ if !kick_all && pending_kicks & bit == 0 {
+ continue;
+ }
+ match kick.kick() {
+ Ok(()) => pending_kicks &= !bit,
+ Err(error) if retryable_kick(&error) => {
+ pending_kicks |= bit;
+ }
+ Err(error) => {
+ vcpus.sender.send(Event::VcpuFailed(error.into()));
+ break;
+ }
+ }
}
}
- event
});
match event {
- Ok(Some(Event::StopRequested)) => Ok(VmExit::StopRequested),
- Ok(Some(Event::GuestShutdown)) => Ok(VmExit::GuestShutdown),
- Ok(Some(Event::GuestReset)) => Ok(VmExit::GuestReset),
- Ok(Some(Event::VcpuFailed(error) | Event::DeviceFailed(error))) => Err(error),
- Ok(None) => unreachable!("a wait without a timeout returns an 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)),
}
}
diff --git a/src/vmm/tests/elf/mod.rs b/src/vmm/tests/elf/mod.rs
index eeb7f4080..2b12cec4e 100644
--- a/src/vmm/tests/elf/mod.rs
+++ b/src/vmm/tests/elf/mod.rs
@@ -342,7 +342,11 @@ fn native_vmlinux_bytes_are_visible_to_a_kvm_vcpu() {
"guest checksum of the loaded kernel"
);
// Finish the OUT without executing HLT, which would wait in the kernel.
- vcpu.complete_pending_io().expect("complete pending I/O");
+ assert!(
+ vcpu.complete_pending_io()
+ .expect("complete pending I/O")
+ .is_done()
+ );
fn parse_hex(field: &str) -> u64 {
u64::from_str_radix(field.trim_start_matches("0x"), 16).expect("hex field")
diff --git a/src/vmm/tests/events/mod.rs b/src/vmm/tests/events/mod.rs
index a628f65ea..3715fd3a6 100644
--- a/src/vmm/tests/events/mod.rs
+++ b/src/vmm/tests/events/mod.rs
@@ -13,6 +13,66 @@ use std::{
use super::{Event, EventLoop};
use crate::error::Error;
+pub(super) struct PollGate(mpsc::Sender<()>, mpsc::Receiver<()>);
+
+impl PollGate {
+ pub(super) fn enter(self) {
+ self.0.send(()).unwrap();
+ self.1.recv_timeout(Duration::from_secs(5)).unwrap();
+ }
+}
+
+#[test]
+fn coalesced_control_wakes_return_none_without_latching_stop() {
+ let mut events = EventLoop::new().unwrap();
+ let sender = events.sender();
+ for _ in 0..3 {
+ sender.wake();
+ }
+ assert!(events.wait(Some(Duration::ZERO)).unwrap().is_none());
+ let (returned, result) = mpsc::channel();
+ let waiter = thread::spawn(move || {
+ returned.send(events.wait(None)).unwrap();
+ events
+ });
+ let wake = result.recv_timeout(Duration::from_secs(5));
+ // Release the waiter if a regression swallowed the pure wake.
+ if wake.is_err() {
+ sender.send(Event::StopRequested);
+ }
+ let mut events = waiter.join().unwrap();
+ assert!(wake.unwrap().unwrap().is_none());
+ assert!(!sender.is_stopping());
+
+ let timeout = Duration::from_millis(20);
+ let started = Instant::now();
+ assert!(events.wait(Some(timeout)).unwrap().is_none());
+ assert!(started.elapsed() >= timeout);
+}
+
+#[test]
+fn terminal_event_takes_priority_over_control_wake_in_the_poller() {
+ let mut events = EventLoop::new().unwrap();
+ let sender = events.sender();
+ let (reached, ready) = mpsc::channel();
+ let (release, gate) = mpsc::channel();
+ events.before_poll = Some(PollGate(reached, gate));
+
+ thread::scope(|scope| {
+ let waiter = scope.spawn(|| events.wait(Some(Duration::from_secs(5))));
+ ready.recv_timeout(Duration::from_secs(5)).unwrap();
+ sender.wake();
+ assert!(!sender.is_stopping());
+ sender.send(Event::GuestShutdown);
+ release.send(()).unwrap();
+ assert!(matches!(
+ waiter.join().unwrap(),
+ Ok(Some(Event::GuestShutdown))
+ ));
+ });
+ assert!(sender.is_stopping());
+}
+
#[test]
fn returns_queued_events_in_order() {
let mut events = EventLoop::new().unwrap();
diff --git a/src/vmm/tests/flat_guest/mod.rs b/src/vmm/tests/flat_guest/mod.rs
index 0ad6a1f00..518f5f0e8 100644
--- a/src/vmm/tests/flat_guest/mod.rs
+++ b/src/vmm/tests/flat_guest/mod.rs
@@ -12,7 +12,9 @@ use std::{
};
use vm_memory::GuestAddressSpace as _;
-use boxlite_hypervisor::{KvmVcpu, KvmVm, VcpuExit, VcpuHandle as _, X86BootRegisters, X86Segment};
+use boxlite_hypervisor::{
+ IoCompletion, KvmVcpu, KvmVm, Vcpu, VcpuExit, VcpuHandle as _, X86BootRegisters, X86Segment,
+};
use vm_memory::{Bytes, GuestAddress};
use crate::memory::{GuestMemoryMmap, GuestRam, ram_ranges};
@@ -49,10 +51,10 @@ impl FlatGuest {
&self.vm
}
- /// Runs the guest, handing each exit to `serve`, until `serve` returns
- /// `false`; the guest then runs no further instruction. Returns how many
- /// exits it made. A guest that stops exiting fails the test.
- pub(crate) fn run(&mut self, mut serve: impl FnMut(VcpuExit<'_>) -> bool) -> usize {
+ /// Runs the guest until `serve` returns `false`, then serves any remaining
+ /// exits from the current instruction without starting another. Returns the
+ /// total number of exits served. A guest that stops exiting fails the test.
+ pub(crate) fn run(&mut self, serve: impl FnMut(VcpuExit<'_>) -> bool) -> usize {
let (finished, deadline) = mpsc::channel::<()>();
let kick = self.vcpu.handle();
let watchdog = thread::spawn(move || {
@@ -63,19 +65,7 @@ impl FlatGuest {
kick.kick().unwrap();
}
});
- let mut exits = 0;
- loop {
- match self.vcpu.run().expect("run vCPU") {
- VcpuExit::Interrupted => panic!("the guest stopped exiting after {exits} exits"),
- exit => {
- exits += 1;
- if !serve(exit) {
- break;
- }
- }
- }
- }
- self.vcpu.complete_pending_io().unwrap();
+ let exits = drive_vcpu(&mut self.vcpu, serve);
drop(finished);
watchdog.join().unwrap();
exits
@@ -91,6 +81,32 @@ impl FlatGuest {
}
}
+fn drive_vcpu(vcpu: &mut impl Vcpu, mut serve: impl FnMut(VcpuExit<'_>) -> bool) -> usize {
+ let mut exits = 0;
+ loop {
+ match vcpu.run().expect("run vCPU") {
+ VcpuExit::Interrupted => panic!("the guest stopped exiting after {exits} exits"),
+ exit => {
+ exits += 1;
+ if !serve(exit) {
+ break;
+ }
+ }
+ }
+ }
+ while let IoCompletion::Exit(exit) = vcpu.complete_pending_io().expect("complete pending I/O") {
+ match exit {
+ VcpuExit::Interrupted => panic!("the guest stopped exiting after {exits} exits"),
+ exit => {
+ exits += 1;
+ // The stop request is already latched; finish this instruction.
+ serve(exit);
+ }
+ }
+ }
+ exits
+}
+
/// Writes `program` at [`CODE`] and the flat GDT into `memory`, and returns
/// the registers that enter the program in 32-bit protected mode.
pub(crate) fn load(memory: &GuestMemoryMmap, program: &[u8]) -> X86BootRegisters {
@@ -131,3 +147,63 @@ impl Drop for FlatGuest {
let _ = self.ram.unmap(&*self.vm);
}
}
+
+#[cfg(test)]
+mod tests {
+ use boxlite_hypervisor::Result;
+
+ use super::*;
+ use crate::mock_vm::MockHandle;
+
+ #[derive(Default)]
+ struct SplitIoCpu {
+ entered: bool,
+ completions: usize,
+ }
+
+ impl Vcpu for SplitIoCpu {
+ type Handle = MockHandle;
+
+ fn run(&mut self) -> Result<VcpuExit<'_>> {
+ assert!(!self.entered, "the guest must not re-enter after stop");
+ self.entered = true;
+ Ok(VcpuExit::MmioWrite {
+ guest_addr: 0x1fff,
+ bytes: b"A",
+ })
+ }
+
+ fn complete_pending_io(&mut self) -> Result<IoCompletion<'_>> {
+ self.completions += 1;
+ match self.completions {
+ 1 => Ok(IoCompletion::Exit(VcpuExit::MmioWrite {
+ guest_addr: 0x2000,
+ bytes: b"B",
+ })),
+ 2 => Ok(IoCompletion::Done),
+ _ => panic!("the drain must stop at Done"),
+ }
+ }
+
+ fn handle(&self) -> Self::Handle {
+ unreachable!("driving the mock does not use a watchdog")
+ }
+ }
+
+ #[test]
+ fn serves_follow_up_mmio_before_stopping() {
+ let mut cpu = SplitIoCpu::default();
+ let mut writes = Vec::new();
+ let exits = drive_vcpu(&mut cpu, |exit| {
+ let VcpuExit::MmioWrite { guest_addr, bytes } = exit else {
+ panic!("expected an MMIO write, got {exit:?}");
+ };
+ writes.push((guest_addr, bytes[0]));
+ false
+ });
+
+ assert_eq!((exits, writes.len()), (2, 2), "count and serve both exits");
+ assert_eq!(writes, [(0x1fff, b'A'), (0x2000, b'B')]);
+ assert_eq!(cpu.completions, 2);
+ }
+}
diff --git a/src/vmm/tests/lifecycle/execution.rs b/src/vmm/tests/lifecycle/execution.rs
new file mode 100644
index 000000000..92295592f
--- /dev/null
+++ b/src/vmm/tests/lifecycle/execution.rs
@@ -0,0 +1,953 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+use std::{
+ io,
+ panic::{self, AssertUnwindSafe},
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, AtomicUsize, Ordering},
+ mpsc,
+ },
+ thread,
+ time::{Duration, Instant},
+};
+
+use boxlite_hypervisor::{
+ IoCompletion, MemoryRegion, Vcpu, VcpuExit, VcpuHandle, X86BootRegisters, X86Vcpu, X86Vm,
+};
+
+use super::{CompletionEnd, FragmentCpu, StopOnDrop, WAIT, assert_error};
+use crate::{
+ ControlReason, Error, Vm, VmConfig, VmControl, VmExit, VmStatus,
+ bus::BusDevice,
+ mock_vm::{Call, MockHandle, MockVcpu, MockVm, Step},
+};
+
+pub(super) fn config(vcpu_count: u8) -> VmConfig {
+ VmConfig {
+ vcpu_count,
+ memory_mib: 1,
+ kernel: "unused".into(),
+ cmdline: String::new(),
+ initramfs: None,
+ disks: vec![],
+ filesystem: None,
+ vsock: None,
+ network: None,
+ virtio_console: false,
+ hotplug_mib: 0,
+ }
+}
+
+fn bare(backend: MockVm, count: u8) -> Vm<MockVm> {
+ Vm::with_backend(
+ config(count),
+ || Ok(backend),
+ |_, _| Ok(X86BootRegisters::default()),
+ |_, _| Ok(()),
+ )
+ .unwrap()
+}
+
+pub(super) fn wait_until(mut ready: impl FnMut() -> bool) {
+ let start = Instant::now();
+ while !ready() {
+ assert!(
+ start.elapsed() < WAIT,
+ "VM did not reach the expected condition"
+ );
+ thread::sleep(Duration::from_millis(1));
+ }
+}
+
+pub(super) fn run_with_control<H: X86Vm>(
+ vm: &mut Vm<H>,
+ control_vm: impl FnOnce(&VmControl) + Send,
+) -> crate::Result<VmExit> {
+ let control = vm.control();
+ thread::scope(|scope| {
+ let operator = scope.spawn(|| {
+ // Stop even if a test assertion fails while the driver is blocked.
+ let stop = StopOnDrop(&control);
+ control_vm(stop.0);
+ });
+ let exit = vm.run();
+ operator.join().unwrap();
+ exit
+ })
+}
+
+pub(super) struct ExitGate {
+ arrived: mpsc::Sender<()>,
+ release: Mutex<mpsc::Receiver<()>>,
+}
+
+impl ExitGate {
+ pub(super) fn new() -> (Arc<Self>, mpsc::Receiver<()>, mpsc::Sender<()>) {
+ let (arrived, ready) = mpsc::channel();
+ let (release, resume) = mpsc::channel();
+ (
+ Arc::new(Self {
+ arrived,
+ release: Mutex::new(resume),
+ }),
+ ready,
+ release,
+ )
+ }
+
+ pub(super) fn wait(&self) {
+ self.arrived.send(()).unwrap();
+ self.release.lock().unwrap().recv_timeout(WAIT).unwrap();
+ }
+}
+
+pub(super) fn pause_at_exit(control: &VmControl, release: mpsc::Sender<()>) -> crate::Result<()> {
+ control.request_pause()?;
+ wait_until(|| control.status() == VmStatus::Pausing);
+ release.send(()).unwrap();
+ control.wait_paused(WAIT)
+}
+
+#[test]
+fn initial_pause_prevents_guest_entry_and_running_pauses_are_reversible() {
+ for count in [1, 64] {
+ let backend = MockVm::new();
+ let log = backend.log();
+ let entries = backend.entries();
+ let mut vm = bare(backend, count);
+ let control = vm.control();
+ control.request_pause().unwrap();
+ assert_eq!(control.status(), VmStatus::Created);
+
+ let exit = run_with_control(&mut vm, |control| {
+ control.wait_paused(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ assert!(entries.lock().unwrap().is_empty());
+
+ for _ in 0..3 {
+ let previous = entries.lock().unwrap().len();
+ control.resume().unwrap();
+ assert_eq!(control.status(), VmStatus::Running);
+ wait_until(|| entries.lock().unwrap().len() > previous);
+ control.request_pause().unwrap();
+ control.wait_paused(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ control.wait_paused(Duration::ZERO).unwrap();
+ }
+ // Stop while the vCPUs are parked.
+ });
+
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+ assert_eq!(control.status(), VmStatus::Exited);
+ assert_error(
+ control.wait_paused(Duration::ZERO),
+ "wait_paused",
+ ControlReason::TerminalOutcome,
+ );
+ assert!(matches!(vm.run(), Err(Error::AlreadyRan)));
+ {
+ let calls = log.lock().unwrap();
+ assert_eq!(
+ calls
+ .iter()
+ .filter(|call| matches!(call, Call::DropVcpu { .. }))
+ .count(),
+ usize::from(count)
+ );
+ assert!(!calls.iter().any(|call| matches!(call, Call::Unmap { .. })));
+ }
+ drop(vm);
+ assert!(matches!(
+ log.lock().unwrap().last(),
+ Some(Call::Unmap { .. })
+ ));
+ }
+}
+
+#[test]
+fn stop_or_drop_before_run_ends_an_initial_pause_without_guest_entry() {
+ for run in [true, false] {
+ let backend = MockVm::new();
+ let entries = backend.entries();
+ let log = backend.log();
+ let mut vm = bare(backend, 2);
+ let control = vm.control();
+ control.request_pause().unwrap();
+ thread::scope(|scope| {
+ let waiter = scope.spawn(|| control.wait_paused(WAIT));
+ if run {
+ control.stop();
+ assert_eq!(vm.run().unwrap(), VmExit::StopRequested);
+ }
+ drop(vm);
+ assert_error(
+ waiter.join().unwrap(),
+ "wait_paused",
+ ControlReason::TerminalOutcome,
+ );
+ });
+ assert_eq!(control.status(), VmStatus::Exited);
+ assert!(entries.lock().unwrap().is_empty());
+ assert!(
+ !log.lock().unwrap().iter().any(|call| {
+ matches!(call, Call::SetCpuFeatures { .. } | Call::DropVcpu { .. })
+ })
+ );
+ }
+}
+
+#[test]
+fn guest_shutdown_after_resume_is_the_run_outcome() {
+ let mut vm = bare(MockVm::with_scripts(vec![vec![Step::Shutdown]]), 1);
+ vm.control().request_pause().unwrap();
+ let exit = run_with_control(&mut vm, |control| {
+ control.wait_paused(WAIT).unwrap();
+ let resumed = control.resume();
+ // The guest can shut down before the resume caller reacquires the lock.
+ if resumed.is_err() {
+ assert_error(resumed, "resume", ControlReason::TerminalOutcome);
+ }
+ wait_until(|| control.status() == VmStatus::Exited);
+ });
+ assert_eq!(exit.unwrap(), VmExit::GuestShutdown);
+}
+
+#[test]
+fn pause_capability_uses_the_composed_chipset() {
+ struct Idle;
+ impl BusDevice for Idle {
+ fn read(&mut self, _: u64, _: &mut [u8]) {}
+ fn write(&mut self, _: u64, _: &[u8]) {}
+ }
+
+ let mut vm = Vm::with_backend(
+ config(1),
+ || Ok(MockVm::new()),
+ |_, _| Ok(X86BootRegisters::default()),
+ |chipset, _| chipset.add("idle", |_| Ok(Idle)),
+ )
+ .unwrap();
+ assert_error(
+ vm.control().request_pause(),
+ "request_pause",
+ ControlReason::UnsupportedDevice,
+ );
+ let exit = run_with_control(&mut vm, |control| {
+ wait_until(|| control.status() == VmStatus::Running);
+ assert_error(
+ control.request_pause(),
+ "request_pause",
+ ControlReason::UnsupportedDevice,
+ );
+ });
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+}
+
+struct KickAttempts {
+ failures_left: usize,
+ ids: Vec<u32>,
+}
+
+impl KickAttempts {
+ fn new(failures_left: usize) -> Self {
+ Self {
+ failures_left,
+ ids: Vec::new(),
+ }
+ }
+}
+
+#[derive(Clone)]
+enum PauseFault {
+ CompleteIo(mpsc::Sender<()>),
+ SplitIo {
+ gate: Arc<ExitGate>,
+ end: CompletionEnd,
+ completions: Arc<AtomicUsize>,
+ },
+ Kick(Arc<AtomicUsize>),
+ KickError {
+ kind: io::ErrorKind,
+ attempts: Arc<Mutex<KickAttempts>>,
+ },
+ TerminalKick {
+ first_kick: Arc<ExitGate>,
+ shutdown: Option<Arc<ExitGate>>,
+ attempts: Arc<AtomicUsize>,
+ handle_ready: mpsc::Sender<MockHandle>,
+ },
+ Startup {
+ gate: Arc<ExitGate>,
+ handle_ready: mpsc::Sender<()>,
+ release: mpsc::Sender<()>,
+ },
+ NotifyStopped {
+ peer_parked: Arc<AtomicBool>,
+ kicks: Arc<AtomicUsize>,
+ },
+ GatedKickError {
+ gate: Arc<ExitGate>,
+ kind: io::ErrorKind,
+ fail_kicks: Arc<AtomicBool>,
+ attempts: Arc<AtomicUsize>,
+ kicked: mpsc::Sender<()>,
+ },
+}
+
+struct FaultyVm(MockVm, PauseFault);
+
+fn faulty_vm(backend: MockVm, count: u8, fault: PauseFault) -> Vm<FaultyVm> {
+ Vm::with_backend(
+ config(count),
+ || Ok(FaultyVm(backend, fault)),
+ |_, _| Ok(X86BootRegisters::default()),
+ |_, _| Ok(()),
+ )
+ .unwrap()
+}
+
+impl boxlite_hypervisor::Vm for FaultyVm {
+ type Vcpu = FailingCpu;
+
+ unsafe fn map_memory(&self, region: &MemoryRegion) -> boxlite_hypervisor::Result<()> {
+ // SAFETY: The delegate receives the same mapping and lifetime contract.
+ unsafe { self.0.map_memory(region) }
+ }
+
+ fn unmap_memory(&self, region: &MemoryRegion) -> boxlite_hypervisor::Result<()> {
+ self.0.unmap_memory(region)
+ }
+
+ fn create_vcpu(&self, id: u32) -> boxlite_hypervisor::Result<Self::Vcpu> {
+ if id == 1
+ && let PauseFault::Startup { gate, .. } = &self.1
+ {
+ gate.wait();
+ }
+ Ok(FailingCpu {
+ vcpu: self.0.create_vcpu(id)?,
+ id,
+ fault: self.1.clone(),
+ fragments: match &self.1 {
+ PauseFault::SplitIo { end, .. } => Some(FragmentCpu::new(*end)),
+ _ => None,
+ },
+ })
+ }
+
+ fn set_irq_line(&self, line: u32, level: bool) -> boxlite_hypervisor::Result<()> {
+ self.0.set_irq_line(line, level)
+ }
+}
+
+impl X86Vm for FaultyVm {
+ fn supported_cpuid(&self) -> &[boxlite_hypervisor::X86CpuidEntry] {
+ &[]
+ }
+}
+
+struct FailingCpu {
+ vcpu: MockVcpu,
+ id: u32,
+ fault: PauseFault,
+ fragments: Option<FragmentCpu>,
+}
+
+#[derive(Clone)]
+struct FaultyKick {
+ handle: MockHandle,
+ id: u32,
+ fault: PauseFault,
+}
+
+impl VcpuHandle for FaultyKick {
+ fn kick(&self) -> boxlite_hypervisor::Result<()> {
+ match &self.fault {
+ PauseFault::Kick(kicks) | PauseFault::NotifyStopped { kicks, .. } => {
+ assert_ne!(kicks.fetch_add(1, Ordering::Relaxed), 0, "test kick panic");
+ }
+ PauseFault::KickError { kind, attempts } => {
+ let mut attempts = attempts.lock().unwrap();
+ attempts.ids.push(self.id);
+ if attempts.failures_left != 0 {
+ attempts.failures_left -= 1;
+ return Err(boxlite_hypervisor::Error::KickVcpu {
+ id: self.id,
+ source: (*kind).into(),
+ });
+ }
+ }
+ PauseFault::TerminalKick {
+ first_kick,
+ attempts,
+ ..
+ } if self.id == 0 => {
+ let attempt = attempts.fetch_add(1, Ordering::Relaxed);
+ if attempt == 0 {
+ first_kick.wait();
+ }
+ if attempt < 2 {
+ return Err(boxlite_hypervisor::Error::KickVcpu {
+ id: self.id,
+ source: io::ErrorKind::WouldBlock.into(),
+ });
+ }
+ }
+ PauseFault::Startup { release, .. } => {
+ let _ = release.send(());
+ }
+ PauseFault::GatedKickError {
+ kind,
+ fail_kicks,
+ attempts,
+ kicked,
+ ..
+ } if fail_kicks.load(Ordering::Acquire) => {
+ attempts.fetch_add(1, Ordering::Release);
+ let _ = kicked.send(());
+ return Err(boxlite_hypervisor::Error::KickVcpu {
+ id: self.id,
+ source: (*kind).into(),
+ });
+ }
+ PauseFault::CompleteIo(_)
+ | PauseFault::SplitIo { .. }
+ | PauseFault::TerminalKick { .. }
+ | PauseFault::GatedKickError { .. } => {}
+ }
+ self.handle.kick()
+ }
+}
+
+impl Vcpu for FailingCpu {
+ type Handle = FaultyKick;
+
+ fn run(&mut self) -> boxlite_hypervisor::Result<VcpuExit<'_>> {
+ if let PauseFault::CompleteIo(entered) = &self.fault {
+ entered.send(()).unwrap();
+ }
+ if let PauseFault::SplitIo { gate, .. } = &self.fault
+ && let Some(fragments) = &mut self.fragments
+ && fragments.completions == 0
+ {
+ let exit = fragments.run()?;
+ gate.wait();
+ return Ok(exit);
+ }
+ if self.id == 1
+ && let PauseFault::TerminalKick {
+ shutdown: Some(shutdown),
+ ..
+ } = &self.fault
+ {
+ shutdown.wait();
+ }
+ if let PauseFault::GatedKickError { gate, .. } = &self.fault {
+ gate.wait();
+ return Ok(VcpuExit::Interrupted);
+ }
+ self.vcpu.run()
+ }
+
+ fn complete_pending_io(&mut self) -> boxlite_hypervisor::Result<IoCompletion<'_>> {
+ if matches!(self.fault, PauseFault::CompleteIo(_)) {
+ return Err(boxlite_hypervisor::Error::CompletePendingIo {
+ id: self.id,
+ source: io::Error::other("test I/O completion failure"),
+ });
+ }
+ if let PauseFault::SplitIo { completions, .. } = &self.fault
+ && let Some(fragments) = &mut self.fragments
+ && fragments.completions < 2
+ {
+ let completion = fragments.complete_pending_io()?;
+ completions.fetch_add(1, Ordering::Relaxed);
+ return Ok(completion);
+ }
+ self.vcpu.complete_pending_io()
+ }
+
+ fn notify_guest_stopped(&mut self) -> boxlite_hypervisor::Result<()> {
+ if self.id == 1
+ && let PauseFault::NotifyStopped { peer_parked, .. } = &self.fault
+ {
+ wait_until(|| peer_parked.load(Ordering::Acquire));
+ return Err(boxlite_hypervisor::Error::ConfigureVcpu {
+ id: self.id,
+ operation: "notify guest stopped",
+ source: io::Error::other("test guest clock notification failure"),
+ });
+ }
+ Ok(())
+ }
+
+ fn handle(&self) -> Self::Handle {
+ if self.id == 0
+ && let PauseFault::Startup { handle_ready, .. } = &self.fault
+ {
+ handle_ready.send(()).unwrap();
+ }
+ let handle = self.vcpu.handle();
+ if self.id == 0
+ && let PauseFault::TerminalKick { handle_ready, .. } = &self.fault
+ {
+ handle_ready.send(handle.clone()).unwrap();
+ }
+ FaultyKick {
+ handle,
+ id: self.id,
+ fault: self.fault.clone(),
+ }
+ }
+}
+
+impl X86Vcpu for FailingCpu {
+ fn set_cpu_features(
+ &mut self,
+ cpuid: &[boxlite_hypervisor::X86CpuidEntry],
+ msrs: &[boxlite_hypervisor::X86Msr],
+ ) -> boxlite_hypervisor::Result<()> {
+ self.vcpu.set_cpu_features(cpuid, msrs)
+ }
+
+ fn set_boot_registers(&mut self, regs: &X86BootRegisters) -> boxlite_hypervisor::Result<()> {
+ self.vcpu.set_boot_registers(regs)
+ }
+}
+
+#[test]
+fn failed_io_completion_ends_the_vm_and_rejects_the_in_flight_pause() {
+ let (entered, ready) = mpsc::channel();
+ let mut vm = faulty_vm(MockVm::new(), 1, PauseFault::CompleteIo(entered));
+
+ let exit = run_with_control(&mut vm, move |control| {
+ ready.recv_timeout(WAIT).unwrap();
+ control.request_pause().unwrap();
+ assert_error(
+ control.wait_paused(WAIT),
+ "wait_paused",
+ ControlReason::TerminalOutcome,
+ );
+ });
+ assert!(matches!(
+ exit,
+ Err(Error::Hypervisor(
+ boxlite_hypervisor::Error::CompletePendingIo { .. }
+ ))
+ ));
+ assert_eq!(vm.control().status(), VmStatus::Exited);
+}
+
+#[test]
+fn failed_stop_notification_releases_a_parked_peer_despite_a_kick_panic() {
+ let peer_parked = Arc::new(AtomicBool::new(false));
+ let kicks = Arc::new(AtomicUsize::new(0));
+ let mut vm = faulty_vm(
+ MockVm::new(),
+ 2,
+ PauseFault::NotifyStopped {
+ peer_parked: Arc::clone(&peer_parked),
+ kicks: Arc::clone(&kicks),
+ },
+ );
+ let lifecycle = Arc::clone(vm.lifecycle());
+ vm.control().request_pause().unwrap();
+ let (finished, result) = mpsc::channel();
+ let runner = thread::spawn(move || finished.send(vm.run()).unwrap());
+
+ wait_until(|| lifecycle.state().acknowledgements == 1);
+ peer_parked.store(true, Ordering::Release);
+ assert!(matches!(
+ result.recv_timeout(WAIT).expect("VM run did not return"),
+ Err(Error::Hypervisor(
+ boxlite_hypervisor::Error::ConfigureVcpu {
+ id: 1,
+ operation: "notify guest stopped",
+ ..
+ }
+ ))
+ ));
+ runner.join().unwrap();
+ assert_eq!(kicks.load(Ordering::Relaxed), 2);
+}
+
+#[test]
+fn pause_kick_panic_releases_vcpus_before_unwinding() {
+ let backend = MockVm::new();
+ let entries = backend.entries();
+ let kicks = Arc::new(AtomicUsize::new(0));
+ let mut vm = faulty_vm(backend, 2, PauseFault::Kick(Arc::clone(&kicks)));
+ let control = vm.control();
+ let (finished, result) = mpsc::channel();
+ let runner = thread::spawn(move || {
+ let outcome = panic::catch_unwind(AssertUnwindSafe(|| vm.run()));
+ finished.send(outcome).unwrap();
+ });
+
+ wait_until(|| entries.lock().unwrap().len() == 2);
+ control.request_pause().unwrap();
+ let wait = control.wait_paused(WAIT);
+ assert!(
+ result
+ .recv_timeout(WAIT)
+ .expect("VM run did not unwind")
+ .is_err()
+ );
+ assert_error(wait, "wait_paused", ControlReason::TerminalOutcome);
+ runner.join().unwrap();
+ assert_eq!(kicks.load(Ordering::Relaxed), 3);
+}
+
+#[test]
+fn transient_pause_kick_retries_and_allows_resume() {
+ let backend = MockVm::new();
+ let entries = backend.entries();
+ let attempts = Arc::new(Mutex::new(KickAttempts::new(1)));
+ let mut vm = faulty_vm(
+ backend,
+ 2,
+ PauseFault::KickError {
+ kind: io::ErrorKind::WouldBlock,
+ attempts: Arc::clone(&attempts),
+ },
+ );
+
+ let exit = run_with_control(&mut vm, |control| {
+ wait_until(|| entries.lock().unwrap().len() == 2);
+ control.request_pause().unwrap();
+ control
+ .wait_paused(WAIT)
+ .expect("transient kick should still allow the VM to pause");
+ assert_eq!(control.status(), VmStatus::Paused);
+ {
+ let kicks = &attempts.lock().unwrap().ids;
+ assert!(
+ matches!(kicks.as_slice(), [first, peer, retry] if first != peer && first == retry),
+ "expected a kick for each vCPU followed by a retry, got {kicks:?}"
+ );
+ }
+
+ control.resume().unwrap();
+ wait_until(|| entries.lock().unwrap().len() == 4);
+ });
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+}
+
+#[test]
+fn terminal_during_pause_retries_shutdown_kick_after_host_stop() {
+ assert_terminal_during_pause_retries_shutdown_kick(VmExit::StopRequested);
+}
+
+#[test]
+fn terminal_during_pause_retries_shutdown_kick_after_guest_shutdown() {
+ assert_terminal_during_pause_retries_shutdown_kick(VmExit::GuestShutdown);
+}
+
+fn assert_terminal_during_pause_retries_shutdown_kick(expected: VmExit) {
+ let guest_shutdown = expected == VmExit::GuestShutdown;
+ let (first_kick, pause_kick_started, finish_pause_kick) = ExitGate::new();
+ let (shutdown, guest_entered, release_guest) = ExitGate::new();
+ let (handle_ready, handle) = mpsc::channel();
+ let backend = MockVm::with_scripts(vec![vec![], vec![Step::Shutdown]]);
+ let entries = backend.entries();
+ let mut vm = faulty_vm(
+ backend,
+ if guest_shutdown { 2 } else { 1 },
+ PauseFault::TerminalKick {
+ first_kick,
+ shutdown: guest_shutdown.then_some(shutdown),
+ attempts: Arc::default(),
+ handle_ready,
+ },
+ );
+ let control = vm.control();
+ let lifecycle = Arc::clone(vm.lifecycle());
+ let (finished, result) = mpsc::channel();
+ let runner = thread::spawn(move || finished.send(vm.run()).unwrap());
+ let rescue = handle.recv_timeout(WAIT).unwrap();
+ wait_until(|| entries.lock().unwrap().contains(&0));
+ if guest_shutdown {
+ guest_entered.recv_timeout(WAIT).unwrap();
+ }
+
+ let wait = thread::scope(|scope| {
+ control.request_pause().unwrap();
+ let waiter = scope.spawn(|| control.wait_paused(WAIT));
+ pause_kick_started.recv_timeout(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Pausing);
+ if guest_shutdown {
+ release_guest.send(()).unwrap();
+ wait_until(|| lifecycle.state().is_terminal());
+ } else {
+ control.stop();
+ }
+ // Latch the terminal event before the first kick fails, so the next
+ // attempt is from shutdown, not the pause retry loop.
+ finish_pause_kick.send(()).unwrap();
+ waiter.join().unwrap()
+ });
+
+ let outcome = result.recv_timeout(WAIT);
+ if matches!(outcome, Err(mpsc::RecvTimeoutError::Timeout)) {
+ // Unblock the mock only after the hang is observed, then fail on the
+ // original timeout rather than letting the test strand a worker.
+ rescue.kick().unwrap();
+ let _ = result
+ .recv_timeout(WAIT)
+ .expect("rescue kick did not unblock Vm::run()");
+ }
+ runner.join().unwrap();
+ assert_error(wait, "wait_paused", ControlReason::TerminalOutcome);
+ assert_eq!(
+ outcome
+ .expect("Vm::run() did not return before WAIT")
+ .unwrap(),
+ expected
+ );
+}
+
+#[test]
+fn single_vcpu_pause_distinguishes_interrupted_and_fatal_kicks() {
+ for (kind, failures) in [
+ (io::ErrorKind::Interrupted, 6),
+ (io::ErrorKind::PermissionDenied, 1),
+ ] {
+ let backend = MockVm::new();
+ let entries = backend.entries();
+ let attempts = Arc::new(Mutex::new(KickAttempts::new(failures)));
+ let mut vm = faulty_vm(
+ backend,
+ 1,
+ PauseFault::KickError {
+ kind,
+ attempts: Arc::clone(&attempts),
+ },
+ );
+
+ let exit = run_with_control(&mut vm, |control| {
+ wait_until(|| entries.lock().unwrap().len() == 1);
+ control.request_pause().unwrap();
+ let paused = control.wait_paused(Duration::from_secs(5));
+ if kind == io::ErrorKind::Interrupted {
+ let kicks = {
+ let mut attempts = attempts.lock().unwrap();
+ // Let the shutdown kick succeed even if pause timed out with retries left.
+ attempts.failures_left = 0;
+ attempts.ids.clone()
+ };
+ // No peer wakes the driver, so six 1-second waits would exceed
+ // the wait_paused deadline.
+ paused.expect("interrupted kicks should be retried before the pause deadline");
+ assert_eq!(control.status(), VmStatus::Paused);
+ assert_eq!(kicks, [0; 7]);
+ control.resume().unwrap();
+ assert_eq!(control.status(), VmStatus::Running);
+ } else {
+ assert_error(paused, "wait_paused", ControlReason::TerminalOutcome);
+ }
+ });
+ if kind == io::ErrorKind::Interrupted {
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+ } else {
+ assert!(matches!(
+ exit,
+ Err(Error::Hypervisor(boxlite_hypervisor::Error::KickVcpu { id: 0, source }))
+ if source.kind() == kind
+ ));
+ }
+ }
+}
+
+#[test]
+fn pause_during_vcpu_startup_parks_every_worker_before_guest_entry() {
+ let (gate, configuring, release) = ExitGate::new();
+ let (handle_ready, first_handle) = mpsc::channel();
+ let backend = MockVm::new();
+ let entries = backend.entries();
+ let mut vm = faulty_vm(
+ backend,
+ 2,
+ PauseFault::Startup {
+ gate,
+ handle_ready,
+ release,
+ },
+ );
+ let lifecycle = Arc::clone(vm.lifecycle());
+
+ let exit = run_with_control(&mut vm, move |control| {
+ configuring.recv_timeout(WAIT).unwrap();
+ first_handle.recv_timeout(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Running);
+
+ // The kick batch starts with only vCPU 0's handle. Its kick lets
+ // vCPU 1 finish configuring and both workers leave the start gate.
+ control.request_pause().unwrap();
+ control.wait_paused(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ assert_eq!(lifecycle.state().acknowledgements, 0b11);
+ assert!(entries.lock().unwrap().is_empty());
+
+ control.resume().unwrap();
+ wait_until(|| {
+ let entries = entries.lock().unwrap();
+ entries.contains(&0) && entries.contains(&1)
+ });
+ });
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+}
+
+#[test]
+fn split_mmio_pauses_after_dispatching_the_follow_up_fragment_and_resumes() {
+ let (gate, ready, release) = ExitGate::new();
+ let completions = Arc::new(AtomicUsize::new(0));
+ let backend = MockVm::new();
+ let entries = backend.entries();
+ let mut vm = faulty_vm(
+ backend,
+ 1,
+ PauseFault::SplitIo {
+ gate,
+ end: CompletionEnd::Done,
+ completions: Arc::clone(&completions),
+ },
+ );
+ let exit = run_with_control(&mut vm, move |control| {
+ ready.recv_timeout(WAIT).unwrap();
+ pause_at_exit(control, release).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ assert_eq!(completions.load(Ordering::Relaxed), 2);
+ assert!(entries.lock().unwrap().is_empty());
+ control.resume().unwrap();
+ wait_until(|| !entries.lock().unwrap().is_empty());
+ });
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+}
+
+#[test]
+fn terminal_exit_during_split_mmio_completion_ends_the_vm() {
+ let (gate, ready, release) = ExitGate::new();
+ let completions = Arc::new(AtomicUsize::new(0));
+ let mut vm = faulty_vm(
+ MockVm::new(),
+ 1,
+ PauseFault::SplitIo {
+ gate,
+ end: CompletionEnd::Reset,
+ completions: Arc::clone(&completions),
+ },
+ );
+ let exit = run_with_control(&mut vm, move |control| {
+ ready.recv_timeout(WAIT).unwrap();
+ assert_error(
+ pause_at_exit(control, release),
+ "wait_paused",
+ ControlReason::TerminalOutcome,
+ );
+ });
+ assert_eq!(exit.unwrap(), VmExit::GuestReset);
+ assert_eq!(completions.load(Ordering::Relaxed), 2);
+}
+
+#[test]
+fn stop_drains_split_mmio_before_worker_exit() {
+ let (gate, ready, release) = ExitGate::new();
+ let completions = Arc::new(AtomicUsize::new(0));
+ let mut vm = faulty_vm(
+ MockVm::new(),
+ 1,
+ PauseFault::SplitIo {
+ gate,
+ end: CompletionEnd::Done,
+ completions: Arc::clone(&completions),
+ },
+ );
+ let exit = run_with_control(&mut vm, move |control| {
+ ready.recv_timeout(WAIT).unwrap();
+ control.stop();
+ release.send(()).unwrap();
+ });
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+ assert_eq!(completions.load(Ordering::Relaxed), 2);
+}
+
+#[test]
+fn shutdown_non_retryable_kick_error_exits_without_hanging() {
+ let (gate, entered, release) = ExitGate::new();
+ let (kicked_tx, kicked_rx) = mpsc::channel();
+ let fail_kicks = Arc::new(AtomicBool::new(true));
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let mut vm = faulty_vm(
+ MockVm::new(),
+ 1,
+ PauseFault::GatedKickError {
+ gate,
+ kind: io::ErrorKind::PermissionDenied,
+ fail_kicks,
+ attempts: Arc::clone(&attempts),
+ kicked: kicked_tx,
+ },
+ );
+
+ let observed = Arc::clone(&attempts);
+ let exit = run_with_control(&mut vm, move |control| {
+ entered.recv_timeout(WAIT).unwrap();
+ control.stop();
+ kicked_rx.recv_timeout(WAIT).unwrap();
+
+ // Wait >2x KICK_RETRY (10ms) to confirm StopVcpus::drop removed the
+ // handle after the single non-retryable kick error.
+ thread::sleep(Duration::from_millis(25));
+ assert_eq!(observed.load(Ordering::Acquire), 1);
+
+ // Let the vCPU exit guest execution and observe the stop latch.
+ release.send(()).unwrap();
+ });
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+ assert_eq!(attempts.load(Ordering::Acquire), 1);
+}
+
+#[test]
+fn self_exiting_vcpu_clears_pending_kicks_upon_pause_completion() {
+ let (gate, entered, release) = ExitGate::new();
+ let (kicked_tx, kicked_rx) = mpsc::channel();
+ let fail_kicks = Arc::new(AtomicBool::new(true));
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let mut vm = faulty_vm(
+ MockVm::new(),
+ 1,
+ PauseFault::GatedKickError {
+ gate,
+ kind: io::ErrorKind::WouldBlock,
+ fail_kicks: Arc::clone(&fail_kicks),
+ attempts: Arc::clone(&attempts),
+ kicked: kicked_tx,
+ },
+ );
+
+ let exit = run_with_control(&mut vm, move |control| {
+ entered.recv_timeout(WAIT).unwrap();
+ control.request_pause().unwrap();
+ kicked_rx.recv_timeout(WAIT).unwrap();
+
+ // Simulate the vCPU exiting on its own without a successful kick, then
+ // parking and acknowledging the pause at `checkpoint`.
+ release.send(()).unwrap();
+ control.wait_paused(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+
+ let kicks_at_pause = attempts.load(Ordering::Acquire);
+ assert!(kicks_at_pause >= 1);
+
+ // Wait several kick-retry intervals (10ms each) to verify `pending_kicks`
+ // was cleared once the VM reached `Paused`.
+ thread::sleep(Duration::from_millis(50));
+ assert_eq!(attempts.load(Ordering::Acquire), kicks_at_pause);
+
+ // Allow the shutdown kick to succeed when StopOnDrop runs.
+ fail_kicks.store(false, Ordering::Release);
+ });
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+}
diff --git a/src/vmm/tests/lifecycle/kvm.rs b/src/vmm/tests/lifecycle/kvm.rs
new file mode 100644
index 000000000..b682335c1
--- /dev/null
+++ b/src/vmm/tests/lifecycle/kvm.rs
@@ -0,0 +1,255 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+use std::{
+ sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+ },
+ thread,
+ time::Duration,
+};
+
+use boxlite_hypervisor::{
+ IoCompletion, KvmVcpu, KvmVcpuHandle, KvmVm, MemoryRegion, Result, Vcpu, VcpuExit,
+ X86BootRegisters, X86CpuidEntry, X86Msr, X86Vcpu, X86Vm,
+};
+use vm_memory::{Bytes, GuestAddress, GuestAddressSpace};
+
+use super::{
+ WAIT,
+ execution::{ExitGate, config, pause_at_exit, run_with_control, wait_until},
+};
+use crate::{Vm, VmExit, VmStatus, flat_guest};
+
+const COUNTER: GuestAddress = GuestAddress(0x2000);
+const READBACK: GuestAddress = GuestAddress(0x2004);
+const MMIO_SPLIT_ADDR: u64 = 0xd000_0ffe;
+
+#[test]
+#[ignore = "requires Linux x86_64 with access to /dev/kvm"]
+fn kvm_device_less_guest_pauses_resumes_and_stops() {
+ let mut memory = None;
+ let mut vm = Vm::with_backend(
+ config(2),
+ KvmVm::new,
+ |ram, _| {
+ memory = Some(ram.memory().clone());
+ // lock inc dword ptr [0x2000]; jmp back to the increment.
+ let program = [0xf0, 0xff, 0x05, 0x00, 0x20, 0x00, 0x00, 0xeb, 0xf7];
+ Ok(flat_guest::load(&ram.memory().memory(), &program))
+ },
+ |_, _| Ok(()),
+ )
+ .unwrap();
+ let memory = memory.unwrap();
+ let counter = || {
+ memory
+ .memory()
+ .load::<u32>(COUNTER, Ordering::Relaxed)
+ .unwrap()
+ };
+ vm.control().request_pause().unwrap();
+ let exit = run_with_control(&mut vm, |control| {
+ control.wait_paused(WAIT).unwrap();
+ assert_eq!(counter(), 0);
+ for _ in 0..3 {
+ let previous = counter();
+ control.resume().unwrap();
+ assert_eq!(control.status(), VmStatus::Running);
+ wait_until(|| counter() != previous);
+ control.request_pause().unwrap();
+ control.wait_paused(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ let paused = counter();
+ thread::sleep(Duration::from_millis(20));
+ assert_eq!(counter(), paused);
+ }
+ });
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+}
+
+#[derive(Clone, Copy, Debug)]
+enum SplitAccess {
+ Read,
+ Write,
+}
+
+impl SplitAccess {
+ fn is_fragment(self, exit: &VcpuExit<'_>, addr: u64) -> bool {
+ match (self, exit) {
+ (Self::Read, VcpuExit::MmioRead { guest_addr, bytes }) => {
+ *guest_addr == addr && bytes.len() == 2
+ }
+ (Self::Write, VcpuExit::MmioWrite { guest_addr, bytes }) => {
+ *guest_addr == addr && bytes.len() == 2
+ }
+ _ => false,
+ }
+ }
+}
+
+struct GatedKvmVm {
+ vm: KvmVm,
+ gate: Arc<ExitGate>,
+ access: SplitAccess,
+ completed_fragments: Arc<AtomicUsize>,
+}
+
+impl boxlite_hypervisor::Vm for GatedKvmVm {
+ type Vcpu = GatedKvmVcpu;
+
+ unsafe fn map_memory(&self, region: &MemoryRegion) -> Result<()> {
+ // SAFETY: The delegate receives the same mapping and lifetime contract.
+ unsafe { self.vm.map_memory(region) }
+ }
+
+ fn unmap_memory(&self, region: &MemoryRegion) -> Result<()> {
+ self.vm.unmap_memory(region)
+ }
+
+ fn create_vcpu(&self, id: u32) -> Result<Self::Vcpu> {
+ Ok(GatedKvmVcpu {
+ vcpu: self.vm.create_vcpu(id)?,
+ gate: Some(Arc::clone(&self.gate)),
+ access: self.access,
+ check_completion: false,
+ completed_fragments: Arc::clone(&self.completed_fragments),
+ })
+ }
+
+ fn set_irq_line(&self, line: u32, level: bool) -> Result<()> {
+ self.vm.set_irq_line(line, level)
+ }
+}
+
+impl X86Vm for GatedKvmVm {
+ fn supported_cpuid(&self) -> &[X86CpuidEntry] {
+ self.vm.supported_cpuid()
+ }
+}
+
+struct GatedKvmVcpu {
+ vcpu: KvmVcpu,
+ gate: Option<Arc<ExitGate>>,
+ access: SplitAccess,
+ check_completion: bool,
+ completed_fragments: Arc<AtomicUsize>,
+}
+
+impl Vcpu for GatedKvmVcpu {
+ type Handle = KvmVcpuHandle;
+
+ fn run(&mut self) -> Result<VcpuExit<'_>> {
+ let exit = self.vcpu.run()?;
+ if self.access.is_fragment(&exit, MMIO_SPLIT_ADDR)
+ && let Some(gate) = self.gate.take()
+ {
+ self.check_completion = true;
+ gate.wait();
+ }
+ Ok(exit)
+ }
+
+ fn complete_pending_io(&mut self) -> Result<IoCompletion<'_>> {
+ let completion = self.vcpu.complete_pending_io()?;
+ if std::mem::take(&mut self.check_completion) {
+ assert!(
+ matches!(&completion, IoCompletion::Exit(exit)
+ if self.access.is_fragment(exit, MMIO_SPLIT_ADDR + 2)),
+ "expected the second {:?} fragment from completion, got {completion:?}",
+ self.access
+ );
+ self.completed_fragments.fetch_add(1, Ordering::Relaxed);
+ }
+ Ok(completion)
+ }
+
+ fn notify_guest_stopped(&mut self) -> Result<()> {
+ self.vcpu.notify_guest_stopped()
+ }
+
+ fn handle(&self) -> Self::Handle {
+ self.vcpu.handle()
+ }
+}
+
+impl X86Vcpu for GatedKvmVcpu {
+ fn set_cpu_features(&mut self, cpuid: &[X86CpuidEntry], msrs: &[X86Msr]) -> Result<()> {
+ self.vcpu.set_cpu_features(cpuid, msrs)
+ }
+
+ fn set_boot_registers(&mut self, regs: &X86BootRegisters) -> Result<()> {
+ self.vcpu.set_boot_registers(regs)
+ }
+}
+
+#[test]
+#[ignore = "requires Linux x86_64 with access to /dev/kvm"]
+fn kvm_device_less_guest_pauses_and_resumes_across_split_mmio() {
+ #[rustfmt::skip]
+ const PROGRAM: [u8; 29] = [
+ 0xa1, 0xfe, 0x0f, 0x00, 0xd0, // mov eax, [0xd0000ffe]
+ 0xa3, 0x04, 0x20, 0x00, 0x00, // mov [0x2004], eax
+ 0xc7, 0x05, 0xfe, 0x0f, 0x00, 0xd0, 0x78, 0x56, 0x34, 0x12, // mov dword [0xd0000ffe], 0x12345678
+ 0xf0, 0xff, 0x05, 0x00, 0x20, 0x00, 0x00, // lock inc dword [0x2000]
+ 0xeb, 0xe3, // jmp to the start
+ ];
+
+ for access in [SplitAccess::Read, SplitAccess::Write] {
+ let (gate, ready, release) = ExitGate::new();
+ let completed_fragments = Arc::new(AtomicUsize::new(0));
+ let mut memory = None;
+ let mut vm = Vm::with_backend(
+ config(1),
+ || {
+ Ok(GatedKvmVm {
+ vm: KvmVm::new()?,
+ gate,
+ access,
+ completed_fragments: Arc::clone(&completed_fragments),
+ })
+ },
+ |ram, _| {
+ memory = Some(ram.memory().clone());
+ let guest = ram.memory().memory();
+ guest.store(0u32, COUNTER, Ordering::Relaxed).unwrap();
+ guest
+ .store(0xdead_beefu32, READBACK, Ordering::Relaxed)
+ .unwrap();
+ Ok(flat_guest::load(&guest, &PROGRAM))
+ },
+ |_, _| Ok(()),
+ )
+ .unwrap();
+ let memory = memory.unwrap();
+ let load = |addr| {
+ memory
+ .memory()
+ .load::<u32>(addr, Ordering::Relaxed)
+ .unwrap()
+ };
+ let exit = run_with_control(&mut vm, move |control| {
+ ready.recv_timeout(WAIT).unwrap();
+ pause_at_exit(control, release).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ assert_eq!(completed_fragments.load(Ordering::Relaxed), 1);
+ let paused = load(COUNTER);
+ assert_eq!(paused, 0);
+ assert_eq!(
+ load(READBACK),
+ match access {
+ SplitAccess::Read => 0xdead_beef,
+ SplitAccess::Write => u32::MAX,
+ }
+ );
+ thread::sleep(Duration::from_millis(20));
+ assert_eq!(load(COUNTER), paused);
+ control.resume().unwrap();
+ wait_until(|| load(COUNTER) > paused);
+ assert_eq!(load(READBACK), u32::MAX);
+ control.stop();
+ });
+ assert_eq!(exit.unwrap(), VmExit::StopRequested);
+ }
+}
diff --git a/src/vmm/tests/lifecycle/mod.rs b/src/vmm/tests/lifecycle/mod.rs
index 1282f610e..82e8db7c7 100644
--- a/src/vmm/tests/lifecycle/mod.rs
+++ b/src/vmm/tests/lifecycle/mod.rs
@@ -1,16 +1,304 @@
// Copyright 2026 BoxLite Contributors
// SPDX-License-Identifier: Apache-2.0
-use std::{fmt::Debug, sync::Arc, time::Duration};
+use std::{
+ fmt::Debug,
+ io,
+ sync::{Arc, Barrier, mpsc},
+ thread,
+ time::{Duration, Instant},
+};
+
+use boxlite_hypervisor::{IoCompletion, Vcpu, VcpuExit};
-use super::{Lifecycle, VmStatus};
+use super::{Command, Lifecycle, VmStatus};
use crate::{
ControlReason, DiskConfig, DiskFormat, Error, FsConfig, NetConfig, VmConfig, VmControl,
VsockConfig,
+ chipset::{Chipset, ChipsetBuilder},
control::ControlRegistry,
events::{Event, EventLoop},
+ mock_vm::{MockHandle, MockVm},
+ vcpu::{handle_exit, park_vcpu},
};
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+mod execution;
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+mod kvm;
+
+const WAIT: Duration = Duration::from_secs(10);
+
+fn fixture(device_less: bool) -> (EventLoop, Arc<Lifecycle>, VmControl) {
+ let events = EventLoop::new().unwrap();
+ let lifecycle = Arc::new(Lifecycle::new(events.sender(), device_less));
+ let control = ControlRegistry::default().finish(Arc::clone(&lifecycle));
+ (events, lifecycle, control)
+}
+
+fn assert_error(result: crate::Result<()>, operation: &str, reason: ControlReason) {
+ assert!(
+ matches!(&result, Err(Error::Control { operation: op, reason: why })
+ if *op == operation && *why == reason),
+ "{result:?}"
+ );
+}
+
+struct StopOnDrop<'a>(&'a VmControl);
+
+impl Drop for StopOnDrop<'_> {
+ fn drop(&mut self) {
+ self.0.stop();
+ }
+}
+
+#[derive(Clone, Copy)]
+enum CompletionEnd {
+ Done,
+ Shutdown,
+ Reset,
+ Halted,
+ Error,
+}
+
+struct FragmentCpu {
+ responses: [[u8; 2]; 2],
+ completions: usize,
+ notifications: usize,
+ end: CompletionEnd,
+ before_fragment: Option<Box<dyn FnOnce() + Send>>,
+}
+
+impl FragmentCpu {
+ fn new(end: CompletionEnd) -> Self {
+ Self {
+ responses: [[0; 2]; 2],
+ completions: 0,
+ notifications: 0,
+ end,
+ before_fragment: None,
+ }
+ }
+}
+
+impl Vcpu for FragmentCpu {
+ type Handle = MockHandle;
+
+ fn run(&mut self) -> boxlite_hypervisor::Result<VcpuExit<'_>> {
+ Ok(VcpuExit::MmioRead {
+ guest_addr: 0xd000_0ffe,
+ bytes: &mut self.responses[0],
+ })
+ }
+
+ fn complete_pending_io(&mut self) -> boxlite_hypervisor::Result<IoCompletion<'_>> {
+ self.completions += 1;
+ match self.completions {
+ 1 => {
+ assert_eq!(self.responses[0], [0xff; 2]);
+ if let Some(before_fragment) = self.before_fragment.take() {
+ before_fragment();
+ }
+ Ok(IoCompletion::Exit(VcpuExit::MmioRead {
+ guest_addr: 0xd000_1000,
+ bytes: &mut self.responses[1],
+ }))
+ }
+ 2 => {
+ assert_eq!(self.responses[1], [0xff; 2]);
+ match self.end {
+ CompletionEnd::Done => Ok(IoCompletion::Done),
+ CompletionEnd::Shutdown => Ok(IoCompletion::Exit(VcpuExit::Shutdown)),
+ CompletionEnd::Reset => Ok(IoCompletion::Exit(VcpuExit::Reset)),
+ CompletionEnd::Halted => Ok(IoCompletion::Exit(VcpuExit::Halted)),
+ CompletionEnd::Error => Err(boxlite_hypervisor::Error::CompletePendingIo {
+ id: 0,
+ source: io::ErrorKind::PermissionDenied.into(),
+ }),
+ }
+ }
+ _ => Ok(IoCompletion::Done),
+ }
+ }
+
+ fn notify_guest_stopped(&mut self) -> boxlite_hypervisor::Result<()> {
+ self.notifications += 1;
+ Ok(())
+ }
+
+ fn handle(&self) -> Self::Handle {
+ unreachable!("the checkpoint does not kick the vCPU")
+ }
+}
+
+fn start_checkpoint(
+ end: CompletionEnd,
+) -> (EventLoop, Arc<Lifecycle>, VmControl, Chipset, FragmentCpu) {
+ let (events, lifecycle, control) = fixture(true);
+ let chipset = ChipsetBuilder::new(Arc::new(MockVm::default()), events.sender())
+ .build()
+ .unwrap();
+ let mut cpu = FragmentCpu::new(end);
+ assert!(
+ handle_exit(&chipset, 0, cpu.run().unwrap())
+ .unwrap()
+ .is_none()
+ );
+ control.request_pause().unwrap();
+ assert!(lifecycle.begin_run().unwrap());
+ (events, lifecycle, control, chipset, cpu)
+}
+
+#[test]
+fn checkpoint_dispatches_both_split_mmio_fragments_before_pausing() {
+ let (mut events, lifecycle, control, chipset, mut cpu) = start_checkpoint(CompletionEnd::Done);
+ thread::scope(|scope| {
+ let _stop = StopOnDrop(&control);
+ let worker = scope.spawn(|| lifecycle.checkpoint(0, || park_vcpu(&chipset, &mut cpu, 0)));
+
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ assert_eq!(lifecycle.state().acknowledgements, 1);
+ assert!(!lifecycle.drive(1));
+ control.wait_paused(Duration::ZERO).unwrap();
+
+ let resume = scope.spawn(|| control.resume());
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ assert!(!lifecycle.drive(1));
+ resume.join().unwrap().unwrap();
+ assert_eq!(control.status(), VmStatus::Running);
+ assert!(worker.join().unwrap().unwrap().is_none());
+ });
+ assert_eq!(cpu.completions, 2);
+ assert_eq!(cpu.notifications, 1);
+}
+
+#[test]
+fn checkpoint_reparks_when_it_wakes_in_a_new_pause_epoch() {
+ let (mut events, lifecycle, control) = fixture(true);
+ control.request_pause().unwrap();
+ assert!(lifecycle.begin_run().unwrap());
+
+ thread::scope(|scope| {
+ let _stop = StopOnDrop(&control);
+ let worker = scope.spawn(|| {
+ let mut parks = 0;
+ let outcome = lifecycle.checkpoint(0, || {
+ parks += 1;
+ Ok(None)
+ });
+ assert!(outcome.unwrap().is_none());
+ parks
+ });
+
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ assert!(!lifecycle.drive(1));
+ control.wait_paused(Duration::ZERO).unwrap();
+
+ let resume = scope.spawn(|| control.resume());
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ {
+ let mut state = lifecycle.state();
+ assert_eq!((state.status, state.epoch), (VmStatus::Paused, 1));
+ assert_eq!(state.command.take(), Some(Command::Resume(1)));
+ // Apply both driver transitions under one lock: separate drive calls
+ // would let the parked worker observe Running before Pausing(2).
+ state.status = VmStatus::Running;
+ lifecycle.changed.notify_all();
+ state.start_pause(2);
+ }
+ resume.join().unwrap().unwrap();
+
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ {
+ let state = lifecycle.state();
+ assert_eq!((state.status, state.epoch), (VmStatus::Pausing, 2));
+ assert_eq!(
+ state.acknowledgements, 1,
+ "worker did not acknowledge epoch 2"
+ );
+ }
+ assert!(!lifecycle.drive(1));
+ control.wait_paused(Duration::ZERO).unwrap();
+ assert_eq!(lifecycle.state().completed_epoch, 2);
+
+ let resume = scope.spawn(|| control.resume());
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ assert!(!lifecycle.drive(1));
+ resume.join().unwrap().unwrap();
+ assert_eq!(control.status(), VmStatus::Running);
+ assert_eq!(worker.join().unwrap(), 2);
+ });
+}
+
+#[test]
+fn checkpoint_propagates_terminal_exit_or_error_without_acknowledging() {
+ for end in [
+ CompletionEnd::Shutdown,
+ CompletionEnd::Reset,
+ CompletionEnd::Halted,
+ CompletionEnd::Error,
+ ] {
+ let (_, lifecycle, control, chipset, mut cpu) = start_checkpoint(end);
+ let (finished, result) = mpsc::channel();
+ let outcome = thread::scope(|scope| {
+ let _stop = StopOnDrop(&control);
+ let worker = scope.spawn(|| {
+ let outcome = lifecycle.checkpoint(0, || park_vcpu(&chipset, &mut cpu, 0));
+ finished.send(outcome).unwrap();
+ });
+ let outcome = result
+ .recv_timeout(WAIT)
+ .expect("checkpoint did not return");
+ worker.join().unwrap();
+ assert_eq!(lifecycle.status(), VmStatus::Pausing);
+ outcome
+ });
+ match end {
+ CompletionEnd::Shutdown => assert!(matches!(outcome, Ok(Some(Event::GuestShutdown)))),
+ CompletionEnd::Reset => assert!(matches!(outcome, Ok(Some(Event::GuestReset)))),
+ CompletionEnd::Halted => assert!(matches!(
+ outcome,
+ Err(Error::UnexpectedExit { vcpu: 0, exit }) if exit == "Halted"
+ )),
+ CompletionEnd::Error => assert!(matches!(
+ outcome,
+ Err(Error::Hypervisor(boxlite_hypervisor::Error::CompletePendingIo { id: 0, source }))
+ if source.kind() == io::ErrorKind::PermissionDenied
+ )),
+ CompletionEnd::Done => unreachable!(),
+ }
+ assert_eq!(cpu.completions, 2);
+ assert_eq!(cpu.notifications, 0);
+ assert_eq!(lifecycle.state().acknowledgements, 0);
+ }
+}
+
+#[test]
+fn stop_during_fragment_completion_skips_the_pause_acknowledgement() {
+ let (mut events, lifecycle, control, chipset, mut cpu) = start_checkpoint(CompletionEnd::Done);
+ let (completing, fragment) = mpsc::channel();
+ let (stopped, stop) = mpsc::channel();
+ let operator = thread::spawn(move || {
+ fragment.recv_timeout(WAIT).unwrap();
+ control.stop();
+ stopped.send(()).unwrap();
+ });
+ cpu.before_fragment = Some(Box::new(move || {
+ completing.send(()).unwrap();
+ stop.recv_timeout(WAIT).unwrap();
+ }));
+ let outcome = lifecycle.checkpoint(0, || park_vcpu(&chipset, &mut cpu, 0));
+ operator.join().unwrap();
+ assert!(outcome.unwrap().is_none());
+ assert_eq!(cpu.completions, 2);
+ assert_eq!(lifecycle.state().acknowledgements, 0);
+ assert_eq!(lifecycle.status(), VmStatus::Stopping);
+ assert!(matches!(
+ events.wait(Some(Duration::ZERO)).unwrap(),
+ Some(Event::StopRequested)
+ ));
+}
+
#[test]
fn control_is_clone_send_sync_and_debug() {
fn assert_traits<T: Clone + Send + Sync + Debug>() {}
@@ -19,10 +307,8 @@ fn control_is_clone_send_sync_and_debug() {
#[test]
fn stop_latches_one_event_and_is_idempotent_after_exit() {
- let mut events = EventLoop::new().unwrap();
+ let (mut events, lifecycle, control) = fixture(true);
let sender = events.sender();
- let lifecycle = Arc::new(Lifecycle::new(sender.clone()));
- let control = ControlRegistry::default().finish(Arc::clone(&lifecycle));
assert_eq!(control.status(), VmStatus::Created);
control.stop();
@@ -36,18 +322,334 @@ fn stop_latches_one_event_and_is_idempotent_after_exit() {
));
assert!(events.wait(Some(Duration::ZERO)).unwrap().is_none());
- #[cfg(target_arch = "x86_64")]
- {
- assert!(matches!(lifecycle.begin_run(), Ok(false)));
- assert!(matches!(lifecycle.begin_run(), Err(Error::AlreadyRan)));
- }
+ assert!(matches!(lifecycle.begin_run(), Ok(false)));
+ assert!(matches!(lifecycle.begin_run(), Err(Error::AlreadyRan)));
lifecycle.mark_exited();
control.stop();
assert_eq!(control.status(), VmStatus::Exited);
+ assert!(lifecycle.state().sender.is_none());
assert!(events.wait(Some(Duration::ZERO)).unwrap().is_none());
}
+#[test]
+fn created_pause_reservation_survives_wait_timeouts_and_disallows_resume() {
+ let (_, _, control) = fixture(false);
+ assert_error(
+ control.request_pause(),
+ "request_pause",
+ ControlReason::UnsupportedDevice,
+ );
+
+ let (_, lifecycle, control) = fixture(true);
+ assert_error(control.resume(), "resume", ControlReason::InvalidState);
+ assert_error(
+ control.wait_paused(Duration::ZERO),
+ "wait_paused",
+ ControlReason::InvalidState,
+ );
+ control.request_pause().unwrap();
+ assert_eq!(control.status(), VmStatus::Created);
+ assert_error(
+ control.request_pause(),
+ "request_pause",
+ ControlReason::InvalidState,
+ );
+ assert_error(control.resume(), "resume", ControlReason::InvalidState);
+ for timeout in [Duration::ZERO, Duration::from_millis(10), Duration::ZERO] {
+ assert_error(
+ control.wait_paused(timeout),
+ "wait_paused",
+ ControlReason::DeadlineTimeout,
+ );
+ }
+ assert!(lifecycle.state().command.is_some());
+}
+
+#[test]
+fn created_pause_has_one_winner_and_stop_or_exit_releases_waiters() {
+ for stop in [true, false] {
+ let (_, lifecycle, control) = fixture(true);
+ let other = control.clone();
+ let contender = thread::spawn(move || other.request_pause());
+ let first = control.request_pause();
+ let second = contender.join().unwrap();
+ match (first, second) {
+ (Ok(()), rejected) | (rejected, Ok(())) => {
+ assert_error(rejected, "request_pause", ControlReason::InvalidState);
+ }
+ results => panic!("expected one initial pause reservation: {results:?}"),
+ }
+ thread::scope(|scope| {
+ let (ready, waiting) = mpsc::channel();
+ let waiters = [&lifecycle; 2].map(|lifecycle| {
+ let ready = ready.clone();
+ scope.spawn(move || {
+ let state = lifecycle.state();
+ let Some(Command::Park(epoch)) = state.command else {
+ panic!("initial pause was never reserved");
+ };
+ // Signal while holding the lock so teardown cannot run
+ // before this waiter releases it in the condition wait.
+ ready.send(()).unwrap();
+ lifecycle.await_pause(state, epoch, WAIT)
+ })
+ });
+ for _ in 0..waiters.len() {
+ waiting.recv_timeout(WAIT).unwrap();
+ }
+ let terminating = Instant::now();
+ if stop {
+ control.stop();
+ } else {
+ lifecycle.mark_exited();
+ }
+ for waiter in waiters {
+ assert_eq!(waiter.join().unwrap(), Err(ControlReason::TerminalOutcome));
+ }
+ assert!(terminating.elapsed() < WAIT / 2);
+ });
+ assert_error(
+ control.request_pause(),
+ "request_pause",
+ ControlReason::InvalidState,
+ );
+ assert_error(control.resume(), "resume", ControlReason::InvalidState);
+ }
+}
+
+#[test]
+fn driver_requires_a_distinct_ack_from_every_vcpu_in_the_current_epoch() {
+ for count in [1, 64] {
+ let (mut events, lifecycle, control) = fixture(true);
+ control.request_pause().unwrap();
+ assert!(lifecycle.begin_run().unwrap());
+ assert!(matches!(lifecycle.begin_run(), Err(Error::AlreadyRan)));
+ assert_eq!(control.status(), VmStatus::Pausing);
+ assert_error(
+ control.request_pause(),
+ "request_pause",
+ ControlReason::InvalidState,
+ );
+ assert_error(control.resume(), "resume", ControlReason::InvalidState);
+ let epoch = lifecycle.state().epoch;
+ for id in 0..count - 1 {
+ lifecycle.state().acknowledge(epoch, id);
+ }
+ if count > 1 {
+ lifecycle.state().acknowledge(epoch, 0);
+ }
+ lifecycle.state().acknowledge(epoch, count);
+ lifecycle.state().acknowledge(epoch - 1, count - 1);
+ lifecycle.drive(count);
+ assert_error(
+ control.wait_paused(Duration::ZERO),
+ "wait_paused",
+ ControlReason::DeadlineTimeout,
+ );
+ for _ in 0..2 {
+ lifecycle.state().acknowledge(epoch, count - 1);
+ }
+ assert!(!lifecycle.drive(count));
+ assert_eq!(control.status(), VmStatus::Paused);
+ control.wait_paused(Duration::ZERO).unwrap();
+
+ let other = control.clone();
+ let resume = thread::spawn(move || other.resume());
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ assert!(!lifecycle.drive(count));
+ resume.join().unwrap().unwrap();
+ assert_eq!(control.status(), VmStatus::Running);
+ assert_error(
+ control.wait_paused(Duration::ZERO),
+ "wait_paused",
+ ControlReason::InvalidState,
+ );
+ }
+}
+
+#[test]
+fn epoch_overflow_rejects_pause_without_claiming_the_slot() {
+ let (_, lifecycle, control) = fixture(true);
+ lifecycle.begin_run().unwrap();
+ lifecycle.state().epoch = u64::MAX;
+ assert_error(
+ control.request_pause(),
+ "request_pause",
+ ControlReason::InvalidState,
+ );
+ assert_eq!(control.status(), VmStatus::Running);
+ assert!(lifecycle.state().command.is_none());
+}
+
+#[test]
+fn running_pause_posts_without_blocking_and_survives_wait_timeouts() {
+ let (mut events, lifecycle, control) = fixture(true);
+ lifecycle.begin_run().unwrap();
+ control.request_pause().unwrap();
+ assert_eq!(control.status(), VmStatus::Running);
+ assert_error(
+ control.request_pause(),
+ "request_pause",
+ ControlReason::InvalidState,
+ );
+ for timeout in [Duration::ZERO, Duration::from_millis(10)] {
+ assert_error(
+ control.wait_paused(timeout),
+ "wait_paused",
+ ControlReason::DeadlineTimeout,
+ );
+ }
+ let wake_wait = Instant::now();
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ assert!(wake_wait.elapsed() < WAIT / 2);
+ assert_eq!(lifecycle.state().command, Some(Command::Park(1)));
+
+ assert!(lifecycle.drive(1));
+ assert_eq!(control.status(), VmStatus::Pausing);
+ assert_error(
+ control.request_pause(),
+ "request_pause",
+ ControlReason::InvalidState,
+ );
+ assert_error(
+ control.wait_paused(Duration::ZERO),
+ "wait_paused",
+ ControlReason::DeadlineTimeout,
+ );
+ lifecycle.state().acknowledge(1, 0);
+ assert!(!lifecycle.drive(1));
+ control.wait_paused(Duration::ZERO).unwrap();
+}
+
+#[test]
+fn competing_clones_claim_only_one_command_slot() {
+ let (mut events, lifecycle, control) = fixture(true);
+ lifecycle.begin_run().unwrap();
+
+ for (operation, request) in [
+ (
+ "request_pause",
+ VmControl::request_pause as fn(&VmControl) -> crate::Result<()>,
+ ),
+ ("resume", VmControl::resume),
+ ("request_pause", VmControl::request_pause),
+ ] {
+ let start = Arc::new(Barrier::new(2));
+ let (done, result) = mpsc::channel();
+ let callers = [control.clone(), control.clone()].map(|control| {
+ let (start, done) = (start.clone(), done.clone());
+ thread::spawn(move || {
+ start.wait();
+ done.send(request(&control)).unwrap();
+ })
+ });
+ if operation == "request_pause" {
+ let outcomes = [
+ result.recv_timeout(WAIT).unwrap(),
+ result.recv_timeout(WAIT).unwrap(),
+ ];
+ match outcomes {
+ [Ok(()), rejected] | [rejected, Ok(())] => {
+ assert_error(rejected, operation, ControlReason::InvalidState);
+ }
+ results => panic!("expected one pause winner: {results:?}"),
+ }
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ assert!(lifecycle.drive(1));
+ let epoch = lifecycle.state().epoch;
+ if epoch > 1 {
+ lifecycle.state().acknowledge(epoch - 1, 0);
+ lifecycle.drive(1);
+ assert_error(
+ control.wait_paused(Duration::ZERO),
+ "wait_paused",
+ ControlReason::DeadlineTimeout,
+ );
+ }
+ lifecycle.state().acknowledge(epoch, 0);
+ lifecycle.drive(1);
+ control.wait_paused(Duration::ZERO).unwrap();
+ } else {
+ let rejected = result.recv_timeout(WAIT).unwrap();
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ assert!(!lifecycle.drive(1));
+ assert_error(rejected, operation, ControlReason::InvalidState);
+ result.recv_timeout(WAIT).unwrap().unwrap();
+ }
+ for caller in callers {
+ caller.join().unwrap();
+ }
+ }
+}
+
+#[test]
+fn terminal_stop_rejects_queued_and_accepted_operations() {
+ for (operation, accepted) in [
+ ("request_pause", false),
+ ("request_pause", true),
+ ("resume", false),
+ ] {
+ let (mut events, lifecycle, control) = fixture(true);
+ if operation == "resume" {
+ control.request_pause().unwrap();
+ }
+ lifecycle.begin_run().unwrap();
+ if operation == "resume" {
+ lifecycle.state().acknowledge(1, 0);
+ lifecycle.drive(1);
+ }
+
+ let other = control.clone();
+ let (ready, waiting) = mpsc::channel();
+ let (wait_op, request) = if operation == "request_pause" {
+ control.request_pause().unwrap();
+ let lifecycle = Arc::clone(&lifecycle);
+ (
+ "wait_paused",
+ thread::spawn(move || {
+ let state = lifecycle.state();
+ let Some(Command::Park(epoch)) = state.command else {
+ panic!("pause was never queued");
+ };
+ // Signal while holding the lock so teardown cannot run
+ // before this waiter releases it in the condition wait.
+ ready.send(()).unwrap();
+ lifecycle
+ .await_pause(state, epoch, WAIT)
+ .map_err(|reason| super::control_error("wait_paused", reason))
+ }),
+ )
+ } else {
+ ("resume", thread::spawn(move || other.resume()))
+ };
+ if operation == "request_pause" {
+ waiting.recv_timeout(WAIT).unwrap();
+ }
+ assert!(events.wait(Some(WAIT)).unwrap().is_none());
+ if accepted {
+ assert!(lifecycle.drive(1));
+ events.sender().send(Event::GuestShutdown);
+ lifecycle.state().acknowledge(1, 0);
+ assert!(!lifecycle.drive(1));
+ assert_ne!(control.status(), VmStatus::Paused);
+ lifecycle.mark_stopping();
+ } else {
+ control.stop();
+ }
+ assert_error(
+ request.join().unwrap(),
+ wait_op,
+ ControlReason::TerminalOutcome,
+ );
+ assert_error(
+ control.wait_paused(Duration::ZERO),
+ "wait_paused",
+ ControlReason::TerminalOutcome,
+ );
+ }
+}
+
#[test]
fn device_less_validation_rejects_each_userspace_device() {
let empty = VmConfig {
@@ -128,3 +730,71 @@ fn device_less_validation_rejects_each_userspace_device() {
));
}
}
+
+#[test]
+fn paused_state_rejects_request_pause() {
+ let (_, lifecycle, control) = fixture(true);
+ control.request_pause().unwrap();
+ lifecycle.begin_run().unwrap();
+ lifecycle.state().acknowledge(1, 0);
+ assert!(!lifecycle.drive(1));
+ assert_eq!(control.status(), VmStatus::Paused);
+
+ assert_error(
+ control.request_pause(),
+ "request_pause",
+ ControlReason::InvalidState,
+ );
+ assert_eq!(control.status(), VmStatus::Paused);
+ assert!(lifecycle.state().command.is_none());
+}
+
+#[test]
+fn wait_paused_succeeds_for_epoch_1_after_resume_and_epoch_2_request() {
+ let (_, lifecycle, control) = fixture(true);
+ lifecycle.begin_run().unwrap();
+ control.request_pause().unwrap();
+
+ thread::scope(|scope| {
+ let (ready, waiting) = mpsc::channel();
+ let waiter = {
+ let lifecycle = Arc::clone(&lifecycle);
+ scope.spawn(move || {
+ let state = lifecycle.state();
+ let Some(Command::Park(epoch)) = state.command else {
+ panic!("pause was never queued");
+ };
+ assert_eq!(epoch, 1);
+ // Signal while holding the lock so the state transitions below
+ // happen while this waiter is blocked in `await_pause`.
+ ready.send(()).unwrap();
+ lifecycle
+ .await_pause(state, epoch, WAIT)
+ .map_err(|reason| super::control_error("wait_paused", reason))
+ })
+ };
+
+ waiting.recv_timeout(WAIT).unwrap();
+ {
+ let mut state = lifecycle.state();
+ state.command = None;
+ state.start_pause(1);
+ state.acknowledge(1, 0);
+ state.completed_epoch = 1;
+ state.status = VmStatus::Paused;
+ // Advance through resume and a second pause request before waking
+ // the epoch-1 waiter, so it observes epoch 2 in `Pausing`.
+ state.status = VmStatus::Running;
+ state.start_pause(2);
+ lifecycle.changed.notify_all();
+ }
+
+ waiter.join().unwrap().unwrap();
+ assert_eq!(control.status(), VmStatus::Pausing);
+ assert_error(
+ control.wait_paused(Duration::ZERO),
+ "wait_paused",
+ ControlReason::DeadlineTimeout,
+ );
+ });
+}
diff --git a/src/vmm/tests/mem/mod.rs b/src/vmm/tests/mem/mod.rs
index ccc54a152..56f7cc526 100644
--- a/src/vmm/tests/mem/mod.rs
+++ b/src/vmm/tests/mem/mod.rs
@@ -223,6 +223,7 @@ fn a_timed_out_control_command_can_still_publish_its_target() {
let mut mem = VirtioMem::new(memory, registry.register_memory().unwrap());
let control = registry.finish(Arc::new(crate::lifecycle::Lifecycle::new(
crate::events::EventLoop::new().unwrap().sender(),
+ false,
)));
let sources = Arc::new(Sources::default());
let interrupt = Arc::new(Interrupt::default());
diff --git a/src/vmm/tests/mock_vm/mod.rs b/src/vmm/tests/mock_vm/mod.rs
index 651d2b19b..d43dab58c 100644
--- a/src/vmm/tests/mock_vm/mod.rs
+++ b/src/vmm/tests/mock_vm/mod.rs
@@ -11,7 +11,9 @@ use std::{
sync::{Arc, Condvar, Mutex},
};
-use boxlite_hypervisor::{Error, MemoryRegion, Result, Vcpu, VcpuExit, VcpuHandle, Vm};
+use boxlite_hypervisor::{
+ Error, IoCompletion, MemoryRegion, Result, Vcpu, VcpuExit, VcpuHandle, Vm,
+};
/// One recorded call attempt, with the host address as an integer because
/// `MemoryRegion` is not `Send`.
@@ -375,8 +377,8 @@ impl Vcpu for MockVcpu {
})
}
- fn complete_pending_io(&mut self) -> Result<()> {
- Ok(())
+ fn complete_pending_io(&mut self) -> Result<IoCompletion<'_>> {
+ Ok(IoCompletion::Done)
}
fn handle(&self) -> MockHandle {
diff --git a/src/vmm/tests/vm/mod.rs b/src/vmm/tests/vm/mod.rs
index c5cab5d09..7576796ef 100644
--- a/src/vmm/tests/vm/mod.rs
+++ b/src/vmm/tests/vm/mod.rs
@@ -879,7 +879,7 @@ fn a_kvm_guest_reads_the_last_byte_of_the_mapped_layout() {
exit => panic!("unexpected exit: {exit:?}"),
}
// Complete the OUT without reaching HLT, which would wait inside KVM.
- vcpu.complete_pending_io().unwrap();
+ assert!(vcpu.complete_pending_io().unwrap().is_done());
drop(vcpu);
let weak = Arc::downgrade(&memory);
@@ -1002,7 +1002,7 @@ fn a_kvm_guest_runs_64_bit_code_with_the_boot_cpu_state() {
VcpuExit::IoOut { port, bytes } => assert_eq!((port, bytes), (0x3f8, &b"L"[..])),
exit => panic!("unexpected exit: {exit:?}"),
}
- vcpu.complete_pending_io().unwrap();
+ assert!(vcpu.complete_pending_io().unwrap().is_done());
let results: [u64; 7] = memory.read_obj(GuestAddress(RESULTS)).unwrap();
assert_eq!(
results,