The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(vmm): add VmControl lifecycle handle and device-less VM (#2964)
lfld287152b6a7a813e
diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.mdindex 9ffa28088..34c77c622 100644--- a/docs/contributing/architecture/vmm/README.md+++ b/docs/contributing/architecture/vmm/README.md@@ -486,9 +486,9 @@ engine adapter calls it from`VmmInstance::enter`:```rust-let mut vm = Vm::new(config, console)?; // validate, create the host VM, map RAM, load the kernel, build devices-let stop = vm.stop_handle(); // Clone + Send; the shim's SIGTERM path calls stop.stop()-let exit = vm.run()?; // VmExit::GuestShutdown, GuestReset or StopRequested+let mut vm = Vm::new(config, console)?;+let control = vm.control(); // Clone for runtime control.+let exit = vm.run()?; // Blocks on the thread that owns the VM.````run` returns once: a second call fails with `AlreadyRan`, since a VM never@@ -497,6 +497,30 @@ serial output through a bounded queue; `run` waits up to one second for thesink to take the rest, and bytes it never takes are counted as dropped andlogged.+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.+The first terminal event determines the outcome of an active run.++On teardown, the driver joins all scoped vCPUs, shuts down virtio workers,+finishes the console, and publishes `Exited`. A worker join timeout leaves+the VM in `Stopping` until drop. The VM owns the RAM mappings until drop,+which also publishes `Exited` if the VM was never run.++On Linux x86_64, the crate-internal `#[cfg(test)]` helper+`Vm::new_device_less(config)` shares KVM preflight, RAM registration, and+kernel and initramfs loading with `Vm::new`.+It builds an empty chipset and starts no console worker. Configuring disks,+filesystem, vsock, network, virtio console, or `hotplug_mib` (virtio-mem)+returns `Error::Control` with `ControlReason::UnsupportedDevice` before KVM+setup. Its empty disk registry makes `resize_disk()` return `InvalidInput`.+- **`run` reports how the VM ended, not the box's exit code.**- The guest agent writes the box's exit code to `exit.json` on the SHAREDshare, and it keeps travelling that way (`src/guest/src/service/container.rs:406-488`).@@ -531,10 +555,8 @@ logged.- `create_engine` reports an engine missing from the build as`BoxliteError::Unsupported`, so a shim built without the `native` featurefails a native box the same typed way.-- **The stop handle is not wired to SIGTERM yet.** The shim's SIGTERM handler- asks the guest to shut down over gRPC and re-raises the signal, which ends the- process with the VM inside it; `StopHandle::stop` joins that path once the- guest agent can answer.+- **SIGTERM.** The shim asks the guest to shut down over gRPC and re-raises+ the signal to end the process.### Where the engine plugs in (M2)@@ -557,7 +579,7 @@ logged.- **Runtime control.** The host-only `vmm.sock` handles disk resize and[directory delivery](../../../../src/vmm/README.md#host-directory-delivery)through a serial control thread. The shim routes resize requests by `block_id`- through [`VmControl`](../../../../src/vmm/README.md#virtio-block-device).+ through [`VmControl::resize_disk`](../../../../src/vmm/README.md#virtio-block-device).The `box.sock` listener forwards guest RPCs, including Mount and Detach.- **File size limits.** The VMM bounds guest I/O by virtual disk capacity.The host kernel enforces the shim's configured or inheriteddiff --git a/src/vmm/README.md b/src/vmm/README.mdindex a09a32a80..a0c0321b7 100644--- a/src/vmm/README.md+++ b/src/vmm/README.md@@ -2,20 +2,27 @@BoxLite's native VMM. On Linux x86_64, `Vm::new` validates the machineconfiguration, creates the KVM VM with legacy devices and a reporting balloon,-registers guest RAM and loads the kernel and boot data; `Vm::run` runs every vCPU until the guest powers off or resets, or a-`StopHandle` stops it, and returns how the VM ended (see [Lifecycle](#lifecycle)).+registers guest RAM, and loads the kernel and boot data. `Vm::run` runs the+vCPUs until the guest powers off, resets, or a `VmControl` requests a stop.+It returns how the VM ended (see [Lifecycle](#lifecycle)).`Error` wraps `boxlite_hypervisor::Error` with its cause chain intact. The[VMM design](../../docs/contributing/architecture/vmm/README.md) specifies thelifecycle API, memory layout, buses, interrupts, and threads.-`Vm`, `VmConfig`, `ReclaimPolicy`, `VmExit`, `StopHandle`, `VmControl`, `Error`-and `Result` are public, as are `BusKind` and `Conflict`, which `Error::ChipsetConflicts`-carries; M2's engine adapter consumes that API and inspects the error's host-cause.+`Vm`, `VmConfig`, `ReclaimPolicy`, `VmExit`, `VmControl`, `VmStatus`,+`StopHandle`, `ControlReason`, `Error`, and `Result` are public. So are+`BusKind` and `Conflict`, which `Error::ChipsetConflicts` carries.`Vm::new(config, console)` adds COM1, the CMOS RTC, the i8042 and virtio-balloon; COM1output reaches `console` through the[console queue](#legacy-devices-and-the-console).+On Linux x86_64, the crate-internal `#[cfg(test)]` helper+`Vm::new_device_less(config)` loads the kernel and optional initramfs into a+KVM VM with an empty userspace chipset and no console worker. KVM still creates+the in-kernel irqchip and PIT. Configuring disks, filesystem, vsock, network,+virtio console, or `hotplug_mib` (virtio-mem) returns `Error::Control` with+`ControlReason::UnsupportedDevice` before KVM opens.+```textboxlite-vmm├── boxlite-hypervisor@@ -27,7 +34,9 @@ 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; `StopHandle`, `control` and `VmExit` |+| `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 || `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 |@@ -634,6 +643,20 @@ socket and guest-memory tests; real-guest qualification remains separate.## Lifecycle+`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+`InvalidInput` for disk resize because its registry is empty.++| `VmStatus` | Meaning |+| --- | --- |+| `Created` | The VM is ready for its first run. |+| `Running` | The driver has started the run, including vCPU setup. |+| `Stopping` | A stop was requested or the driver is handling a terminal event. |+| `Exited` | The run finished teardown, or the owner dropped the VM. |+`Vm::run` runs on x86_64, against any backend that implements`boxlite_hypervisor::X86Vm`; unit tests drive it on the mock backend. Beforeit registers any RAM, `Vm::with_backend` builds the `Chipset` from the@@ -671,9 +694,16 @@ becomes `Error::VirtioDevice`, while an error that ended the VM stays the result`Drop` retries an incomplete join and keeps RAM registered while workers stillrun; a quiesce failure after joining still permits RAM unmapping.-`Vm::stop_handle` returns a `StopHandle` that sends `StopRequested` from any-thread, even before `run` starts. A VM runs once: a second `run` fails with-`AlreadyRan`, since its latch stays set and its vCPUs already exist.+`VmControl::stop` and `StopHandle::stop` share the stop latch and return+without waiting. A stop requested before the first run skips vCPU creation,+performs cleanup, and returns `Ok(VmExit::StopRequested)` on successful cleanup.+A second run returns `Error::AlreadyRan`.++`run` publishes `Exited` after joining the vCPUs, shutting down the virtio+workers, and finishing the console. A worker join timeout leaves the status at+`Stopping` until the VM is dropped. RAM stays mapped after `run`.+Dropping the VM handles RAM teardown and publishes `Exited` to surviving+controls, including when the VM never ran.## Long-mode entry@@ -757,7 +787,7 @@ 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 orpanics, latches the stop for every vCPU, and wakes the `EventLoop`'s `mio`- poller. vCPU workers and `StopHandle` send the other events. An event sent+ poller. vCPU workers and lifecycle controls send the other events. An event sentafter the loop is gone is logged at debug level and discarded. `EventLoop::wait` returnsthe oldest event, or `None` at its timeout, and rechecks the queue everysecond in case a wake-up was lost. Every event ends the VM; the VMM neverdiff --git a/src/vmm/src/chipset.rs b/src/vmm/src/chipset.rsindex bbdd70363..a8e2fa1d5 100644--- a/src/vmm/src/chipset.rs+++ b/src/vmm/src/chipset.rs@@ -326,6 +326,12 @@ pub(crate) struct Chipset {}impl Chipset {+ /// Whether the chipset contains any userspace devices.+ #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]+ pub(crate) fn is_empty(&self) -> bool {+ self._devices.is_empty()+ }+/// Serves an MMIO or port access and returns `None`; returns every other/// exit to the caller unchanged.pub(crate) fn dispatch<'a>(&self, exit: VcpuExit<'a>) -> Option<VcpuExit<'a>> {diff --git a/src/vmm/src/config.rs b/src/vmm/src/config.rsindex 04e4cacbd..2f20fcfdf 100644--- a/src/vmm/src/config.rs+++ b/src/vmm/src/config.rs@@ -108,6 +108,23 @@ pub struct NetConfig {}impl VmConfig {+ #[cfg(test)]+ pub(crate) fn validate_device_less(&self) -> Result<()> {+ if !self.disks.is_empty()+ || self.filesystem.is_some()+ || self.vsock.is_some()+ || self.network.is_some()+ || self.virtio_console+ || self.hotplug_mib > 0+ {+ return Err(Error::Control {+ operation: "new_device_less",+ reason: crate::ControlReason::UnsupportedDevice,+ });+ }+ self.validate()+ }+/// Checks static configuration without calling the host. VM creation/// checks host and boot address limits before allocating RAM. The budget/// for the `virtio_mmio.device=` arguments that `devices::add_all` prepends isdiff --git a/src/vmm/src/control.rs b/src/vmm/src/control.rsindex 9df239837..0aa9210ef 100644--- a/src/vmm/src/control.rs+++ b/src/vmm/src/control.rs@@ -1,24 +1,39 @@// Copyright 2026 BoxLite Contributors// SPDX-License-Identifier: Apache-2.0-//! Host operations routed to devices by their configured IDs.+//! Runtime controls for a VM.use std::{collections::HashMap, io, sync::Arc, time::Duration};-use crate::MemoryStatus;-use crate::virtio::blk::control::{self, Controls, DiskSender};+use crate::{+ MemoryStatus,+ lifecycle::{Lifecycle, VmStatus},+ virtio::blk::control::{self, Controls, DiskSender},+};mod memory;pub(crate) use memory::{MemoryRequest, MemoryRequests};/// Controls a VM from any thread without exposing its devices.+/// Dropping a control handle has no effect on execution.#[derive(Clone, Debug)]pub struct VmControl {disks: Arc<HashMap<String, DiskSender>>,memory: Option<memory::MemorySender>,+ lifecycle: Arc<Lifecycle>,}impl VmControl {+ /// Returns the current lifecycle state.+ pub fn status(&self) -> VmStatus {+ self.lifecycle.status()+ }++ /// Requests a stop, including before execution starts, without waiting for exit.+ pub fn stop(&self) {+ self.lifecycle.stop();+ }+/// 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.@@ -91,10 +106,11 @@ impl ControlRegistry {Ok(controls)}- pub(crate) fn finish(self) -> VmControl {+ pub(crate) fn finish(self, lifecycle: Arc<Lifecycle>) -> VmControl {VmControl {disks: Arc::new(self.disks),memory: self.memory,+ lifecycle,}}diff --git a/src/vmm/src/error.rs b/src/vmm/src/error.rsindex c29b6cb56..7d398c871 100644--- a/src/vmm/src/error.rs+++ b/src/vmm/src/error.rs@@ -8,13 +8,42 @@ use std::{error, fmt, io, path::PathBuf};/// Result of a VMM operation.pub type Result<T> = std::result::Result<T, Error>;-/// A failure that ends the VM.+/// Why a VM control operation was refused or failed.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ControlReason {+ /// The operation is unavailable in the current lifecycle state.+ InvalidState,+ /// The operation requires a device-less configuration.+ UnsupportedDevice,+ /// The operation did not complete before its deadline.+ DeadlineTimeout,+ /// A terminal event interrupted the operation.+ TerminalOutcome,+}++impl fmt::Display for ControlReason {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.write_str(match self {+ Self::InvalidState => "invalid state",+ Self::UnsupportedDevice => "operation requires a device-less VM",+ Self::DeadlineTimeout => "vCPU acknowledgements are still incomplete",+ Self::TerminalOutcome => "the VM is stopping",+ })+ }+}++/// A VMM construction, execution, or control failure.////// The cause chain stays intact through [`error::Error::source`], so callers/// can tell a host that cannot run VMs from other failures.#[derive(Debug)]#[non_exhaustive]pub enum Error {+ /// A control operation was refused or failed.+ Control {+ operation: &'static str,+ reason: ControlReason,+ },/// The vCPU count is outside `1..=config::MAX_VCPUS`.InvalidVcpuCount(u8),/// Opening or configuring filesystem exports failed.@@ -104,6 +133,7 @@ pub enum Error {impl fmt::Display for Error {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {match self {+ Self::Control { operation, reason } => write!(f, "{operation}: {reason}"),Self::Vsock(_) => f.write_str("failed to configure vsock bridges"),Self::Filesystem(_) => f.write_str("failed to configure virtio-fs exports"),Self::InvalidVcpuCount(count) => write!(f, "invalid vCPU count: {count}"),@@ -188,7 +218,8 @@ impl fmt::Display for Error {impl error::Error for Error {fn source(&self) -> Option<&(dyn error::Error + 'static)> {match self {- Self::InvalidVcpuCount(_)+ Self::Control { .. }+ | Self::InvalidVcpuCount(_)| Self::InvalidMemorySize(_)| Self::GuestMemoryAddressLimit { .. }| Self::InvalidHotplugSize(_)diff --git a/src/vmm/src/lib.rs b/src/vmm/src/lib.rsindex 8ce3cf6a0..16dd7dfc4 100644--- a/src/vmm/src/lib.rs+++ b/src/vmm/src/lib.rs@@ -3,7 +3,7 @@//! BoxLite's native VMM. [`Vm::new`] validates a [`VmConfig`], creates the//! host VM, registers guest RAM and loads the kernel; [`Vm::run`] runs every-//! vCPU until the guest powers off or resets, or a [`StopHandle`] stops it.+//! vCPU until the guest powers off or resets, or a [`VmControl`] stops it.//!//! The VMM owns the guest machine and delegates host operations to//! `boxlite-hypervisor`. BoxLite runtime integration belongs in its engine adapter.@@ -54,6 +54,7 @@ mod hotplug;expect(dead_code, reason = "Only Linux x86_64 adds devices yet."))]mod irq;+pub(crate) mod lifecycle;mod memory;#[cfg(target_arch = "x86_64")]mod vcpu;@@ -85,7 +86,8 @@ pub use config::{};pub use control::VmControl;pub use devices::mem::MemoryStatus;-pub use error::{Error, Result};+pub use error::{ControlReason, Error, Result};+pub use lifecycle::VmStatus;pub use memory::ReclaimPolicy;#[cfg(all(target_os = "linux", target_arch = "x86_64"))]pub use virtio::fs::{AggregateFs, Share, insert_aggregate, lookup_aggregate};diff --git a/src/vmm/src/lifecycle.rs b/src/vmm/src/lifecycle.rsnew file mode 100644index 000000000..fd658f0a1--- /dev/null+++ b/src/vmm/src/lifecycle.rs@@ -0,0 +1,99 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++use std::sync::{Mutex, MutexGuard, PoisonError};++#[cfg(target_arch = "x86_64")]+use crate::error::{Error, Result};+use crate::events::{Event, EventSender};++/// 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.+ Created,+ /// The run has started.+ Running,+ /// Termination has been requested or the run is tearing down.+ Stopping,+ /// Execution has finished or the VM has been dropped.+ Exited,+}++#[derive(Debug)]+struct LifecycleState {+ status: VmStatus,+ #[cfg(any(test, target_arch = "x86_64"))]+ run_claimed: bool,+ sender: Option<EventSender>,+}++#[derive(Debug)]+pub(crate) struct Lifecycle {+ state: Mutex<LifecycleState>,+}++impl Lifecycle {+ pub(crate) fn new(sender: EventSender) -> Self {+ Self {+ state: Mutex::new(LifecycleState {+ status: VmStatus::Created,+ #[cfg(any(test, target_arch = "x86_64"))]+ run_claimed: false,+ sender: Some(sender),+ }),+ }+ }++ fn state(&self) -> MutexGuard<'_, LifecycleState> {+ self.state.lock().unwrap_or_else(PoisonError::into_inner)+ }++ pub(crate) fn status(&self) -> VmStatus {+ self.state().status+ }++ pub(crate) fn stop(&self) {+ let mut state = self.state();+ if !matches!(state.status, VmStatus::Created | VmStatus::Running) {+ return;+ }+ let Some(sender) = &state.sender else {+ return;+ };+ // Serialize setting the vCPU stop latch with admitting the first run.+ sender.send(Event::StopRequested);+ state.status = VmStatus::Stopping;+ }++ /// Claims the run and returns whether to start the vCPUs.+ #[cfg(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 {+ return Err(Error::AlreadyRan);+ }+ state.run_claimed = true;+ if state.status == VmStatus::Stopping {+ return Ok(false);+ }+ state.status = VmStatus::Running;+ Ok(true)+ }++ #[cfg(target_arch = "x86_64")]+ pub(crate) fn mark_stopping(&self) {+ self.state().status = VmStatus::Stopping;+ }++ pub(crate) fn mark_exited(&self) {+ let mut state = self.state();+ state.status = VmStatus::Exited;+ drop(state.sender.take());+ }+}++#[cfg(test)]+#[path = "../tests/lifecycle/mod.rs"]+mod tests;diff --git a/src/vmm/src/vm.rs b/src/vmm/src/vm.rsindex 8c21b6ece..0aa7d788f 100644--- a/src/vmm/src/vm.rs+++ b/src/vmm/src/vm.rs@@ -4,7 +4,7 @@//! The VM facade: configuration, host VM creation, RAM registration, boot//! loading, and running the vCPUs until the VM ends.-use std::sync::{Arc, Mutex};+use std::sync::{Arc, Mutex, PoisonError};use boxlite_hypervisor::Vm as HostVm;@@ -14,7 +14,8 @@ use crate::{control::{ControlRegistry, VmControl},devices::console::ConsoleWorker,error::{Error, Result},- events::{Event, EventLoop, EventSender},+ events::{EventLoop, EventSender},+ lifecycle::Lifecycle,memory::{GuestRam, ram_ranges},virtio::{DeviceContext,@@ -33,7 +34,7 @@ pub(crate) type BootRegisters = ();#[derive(Debug, Clone, Copy, PartialEq, Eq)]#[non_exhaustive]pub enum VmExit {- /// A [`StopHandle`] stopped it.+ /// A control handle stopped it.StopRequested,/// The guest powered off.GuestShutdown,@@ -41,27 +42,18 @@ pub enum VmExit {GuestReset,}-/// Stops a VM from any thread; [`Vm::run`] then returns-/// [`VmExit::StopRequested`] unless the VM had already ended.+/// Requests a stop from any thread. [`Vm::run`] returns+/// [`VmExit::StopRequested`] if the stop request is the first terminal event.#[derive(Clone, Debug)]-pub struct StopHandle(EventSender);+pub struct StopHandle(Arc<Lifecycle>);impl StopHandle {/// Asks the VM to stop and returns without waiting.pub fn stop(&self) {- self.0.send(Event::StopRequested);+ self.0.stop();}}-/// Where a VM is in its life.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum VmState {- /// Built; [`Vm::run`] has not started.- Created,- /// [`Vm::run`] has started. A VM runs once, so it never leaves this state.- Exited,-}-/// The guest machine on host backend `H`.pub struct Vm<H: HostVm> {// Devices drop before the host VM, and the host VM drops before the RAM.@@ -79,7 +71,7 @@ pub struct Vm<H: HostVm> {sender: EventSender,boot_regs: BootRegisters,vcpu_count: u8,- state: VmState,+ lifecycle: Arc<Lifecycle>,fresh_vm: bool,host_vm: Option<Arc<H>>,ram: GuestRam,@@ -87,7 +79,7 @@ pub struct Vm<H: HostVm> {impl<H: HostVm> std::fmt::Debug for Vm<H> {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- let (vcpus, state) = (self.vcpu_count, self.state);+ let (vcpus, state) = (self.vcpu_count, self.lifecycle.status());f.debug_struct("Vm").field("vcpus", &vcpus).field("state", &state)@@ -97,6 +89,27 @@ impl<H: HostVm> std::fmt::Debug for Vm<H> {#[cfg(all(target_os = "linux", target_arch = "x86_64"))]impl Vm<boxlite_hypervisor::KvmVm> {+ /// Builds a KVM VM with an empty chipset and no console worker.+ /// Rejects userspace device configuration before opening KVM.+ #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]+ pub(crate) fn new_device_less(config: VmConfig) -> Result<Self> {+ use crate::boot;++ config.validate_device_less()?;+ let prepared = boxlite_hypervisor::KvmVm::prepare()?;+ let (leaf, _) = boot::preflight(&config, &prepared)?;+ let vm = Self::build(+ config,+ move || boxlite_hypervisor::KvmVm::from_prepared(prepared),+ true,+ VirtioWorkers::new,+ move |ram, config| boot::prepare(ram, config, leaf).map(|setup| setup.boot_regs),+ |_, _, _, _| Ok(()),+ )?;+ debug_assert!(vm.chipset.as_ref().is_some_and(Chipset::is_empty));+ Ok(vm)+ }+/// Validates `config` and preflights the boot layout and any hotplug window/// against KVM before spawning the console worker and building the VM./// `devices::add_all` adds the legacy devices and one virtio-blk device@@ -230,16 +243,17 @@ impl<H: HostVm> Vm<H> {return Err(error);}+ let lifecycle = Arc::new(Lifecycle::new(sender.clone()));let mut vm = Self {chipset: Some(chipset),workers: Some(workers),console: Mutex::new(None),- control: controls.finish(),events: Mutex::new(events),+ control: controls.finish(Arc::clone(&lifecycle)),+ lifecycle,sender,boot_regs: BootRegisters::default(),vcpu_count: config.vcpu_count,- state: VmState::Created,fresh_vm,host_vm: Some(host_vm),ram,@@ -251,7 +265,7 @@ impl<H: HostVm> Vm<H> {/// A handle that stops this VM from another thread, even before/// [`run`](Self::run) starts.pub fn stop_handle(&self) -> StopHandle {- StopHandle(self.sender.clone())+ StopHandle(Arc::clone(&self.lifecycle))}/// Controls the VM from another thread.@@ -262,22 +276,17 @@ impl<H: HostVm> Vm<H> {#[cfg(target_arch = "x86_64")]impl<H: boxlite_hypervisor::X86Vm> Vm<H> {- /// Runs every vCPU on its own thread until the first event ends the VM,- /// stops and joins them all, shuts the virtio workers down, and returns- /// how the VM ended. Workers that do not shut down fail a run that- /// otherwise ended cleanly. A VM runs once; a second call fails with- /// [`Error::AlreadyRan`].- pub fn run(&mut self) -> Result<VmExit> {- use std::{sync::PoisonError, thread};+ fn run_vcpus(&mut self) -> Result<VmExit> {+ use std::thread;use boxlite_hypervisor::VcpuHandle as _;- use crate::vcpu::{StartGate, Workers};+ use crate::{+ events::Event,+ vcpu::{StartGate, Workers},+ };- if self.state != VmState::Created {- return Err(Error::AlreadyRan);- }- self.state = VmState::Exited;+ self.fresh_vm = false;let gate = StartGate::default();let kicks = Mutex::new(Vec::new());let vcpus = Workers {@@ -309,6 +318,7 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {}}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.@@ -323,11 +333,33 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {}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"),+ Err(error) => Err(Error::EventLoop(error)),+ }+ }++ /// Runs every vCPU on its own thread until the first event ends the VM,+ /// stops and joins them all, shuts the virtio workers down, and returns+ /// how the VM ended. Workers that do not shut down fail a run that+ /// otherwise ended cleanly. A VM runs once; a second call fails with+ /// [`Error::AlreadyRan`].+ pub fn run(&mut self) -> Result<VmExit> {+ let ended = if self.lifecycle.begin_run()? {+ self.run_vcpus()+ } else {+ Ok(VmExit::StopRequested)+ };+// No vCPU notifies a queue any more. Stop the virtio devices before the// console finishes, so a device's last output still reaches the sink.self.control.close_memory();let workers = self.workers.as_ref().expect("live VM has virtio workers");- let shutdown = workers.shutdown().map_err(Error::from);+ let shutdown = workers.shutdown();let console = self.console.get_mut()@@ -339,16 +371,11 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {tracing::warn!(dropped, "dropped guest console output");}}- let ended = 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"),- Err(error) => Err(Error::EventLoop(error)),- };+ if !matches!(&shutdown, Err(ShutdownError::Join(_))) {+ self.lifecycle.mark_exited();+ }// The error that ended the VM stays the one the caller sees.- match (ended, shutdown) {+ match (ended, shutdown.map_err(Error::from)) {(ended, Ok(())) => ended,(Ok(exit), Err(error)) => {tracing::warn!(?exit, "the VM ended, but virtio shutdown failed");@@ -368,8 +395,16 @@ impl<H: HostVm> Drop for Vm<H> {// A device event that outlived the shutdown may still touch guest// RAM, so the registrations stay and `GuestRam` leaks the backing.let workers = self.workers.as_ref().expect("live VM has virtio workers");- if let Err(ShutdownError::Join(error)) = workers.shutdown() {+ let shutdown = workers.shutdown();+ drop(+ self.console+ .get_mut()+ .unwrap_or_else(PoisonError::into_inner)+ .take(),+ );+ if let Err(ShutdownError::Join(error)) = shutdown {tracing::warn!(%error, "the virtio workers did not stop; leaking guest RAM");+ self.lifecycle.mark_exited();return;}// Quiesce failure after joining cannot leave a live callback.@@ -381,7 +416,7 @@ impl<H: HostVm> Drop for Vm<H> {"failed to unmap guest RAM");}- if self.fresh_vm && self.state == VmState::Created {+ if self.fresh_vm {drop(self.chipset.take());drop(self.workers.take());let host_vm = self.host_vm.take().expect("live VM has a host VM");@@ -392,6 +427,7 @@ impl<H: HostVm> Drop for Vm<H> {unsafe { self.ram.release_after_vm_close() };}}+ self.lifecycle.mark_exited();}}diff --git a/src/vmm/tests/lifecycle/mod.rs b/src/vmm/tests/lifecycle/mod.rsnew file mode 100644index 000000000..1282f610e--- /dev/null+++ b/src/vmm/tests/lifecycle/mod.rs@@ -0,0 +1,130 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++use std::{fmt::Debug, sync::Arc, time::Duration};++use super::{Lifecycle, VmStatus};+use crate::{+ ControlReason, DiskConfig, DiskFormat, Error, FsConfig, NetConfig, VmConfig, VmControl,+ VsockConfig,+ control::ControlRegistry,+ events::{Event, EventLoop},+};++#[test]+fn control_is_clone_send_sync_and_debug() {+ fn assert_traits<T: Clone + Send + Sync + Debug>() {}+ assert_traits::<VmControl>();+}++#[test]+fn stop_latches_one_event_and_is_idempotent_after_exit() {+ let mut events = EventLoop::new().unwrap();+ 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();+ control.clone().stop();+ assert_eq!(control.status(), VmStatus::Stopping);+ assert!(!lifecycle.state().run_claimed);+ assert!(sender.is_stopping());+ assert!(matches!(+ events.wait(Some(Duration::ZERO)).unwrap(),+ Some(Event::StopRequested)+ ));+ 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)));+ }++ lifecycle.mark_exited();+ control.stop();+ assert_eq!(control.status(), VmStatus::Exited);+ assert!(events.wait(Some(Duration::ZERO)).unwrap().is_none());+}++#[test]+fn device_less_validation_rejects_each_userspace_device() {+ let empty = VmConfig {+ vcpu_count: 1,+ memory_mib: 16,+ kernel: "vmlinux".into(),+ cmdline: String::new(),+ initramfs: None,+ disks: Vec::new(),+ filesystem: None,+ vsock: None,+ network: None,+ virtio_console: false,+ hotplug_mib: 0,+ };+ empty.validate_device_less().unwrap();+ assert!(matches!(+ VmConfig {+ vcpu_count: 0,+ ..empty.clone()+ }+ .validate_device_less(),+ Err(Error::InvalidVcpuCount(0))+ ));++ for config in [+ VmConfig {+ disks: vec![DiskConfig {+ block_id: "data".into(),+ path: "disk.raw".into(),+ format: DiskFormat::Raw,+ read_only: true,+ }],+ ..empty.clone()+ },+ VmConfig {+ filesystem: Some(FsConfig {+ tag: "shared".into(),+ shares: Vec::new(),+ }),+ ..empty.clone()+ },+ VmConfig {+ vsock: Some(VsockConfig {+ cid: 3,+ listen: Vec::new(),+ connect: Vec::new(),+ }),+ ..empty.clone()+ },+ VmConfig {+ network: Some(NetConfig {+ path: "network.sock".into(),+ mac: [2, 0, 0, 0, 0, 1],+ }),+ ..empty.clone()+ },+ VmConfig {+ virtio_console: true,+ ..empty.clone()+ },+ VmConfig {+ hotplug_mib: 128,+ ..empty+ },+ ] {+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ let error = crate::Vm::new_device_less(config).unwrap_err();+ #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]+ let error = config.validate_device_less().unwrap_err();++ assert!(matches!(+ error,+ Error::Control {+ operation: "new_device_less",+ reason: ControlReason::UnsupportedDevice,+ }+ ));+ }+}diff --git a/src/vmm/tests/mem/mod.rs b/src/vmm/tests/mem/mod.rsindex c262d6800..ccc54a152 100644--- a/src/vmm/tests/mem/mod.rs+++ b/src/vmm/tests/mem/mod.rs@@ -221,7 +221,9 @@ fn a_timed_out_control_command_can_still_publish_its_target() {let memory = HotplugMemory::new(Arc::new(MockVm::new()), view.clone(), window);let mut registry = crate::control::ControlRegistry::default();let mut mem = VirtioMem::new(memory, registry.register_memory().unwrap());- let control = registry.finish();+ let control = registry.finish(Arc::new(crate::lifecycle::Lifecycle::new(+ crate::events::EventLoop::new().unwrap().sender(),+ )));let sources = Arc::new(Sources::default());let interrupt = Arc::new(Interrupt::default());let mut context = context(&view, interrupt.clone());diff --git a/src/vmm/tests/vm/mod.rs b/src/vmm/tests/vm/mod.rsindex 640d84f8f..c5cab5d09 100644--- a/src/vmm/tests/vm/mod.rs+++ b/src/vmm/tests/vm/mod.rs@@ -1038,7 +1038,7 @@ mod lifecycle {use std::{sync::mpsc, thread, time::Duration};use super::{config, *};- use crate::{VmExit, bus::BusDevice, mock_vm::Step};+ use crate::{VmExit, VmStatus, bus::BusDevice, mock_vm::Step};/// Runs `vm` on another thread and fails the test instead of hanging when/// the run never returns.@@ -1079,21 +1079,16 @@ mod lifecycle {let call_log = host_vm.call_log();let region = vm.ram.regions().next().expect("one RAM region");let expected_memory = [Call::map(®ion), Call::unmap(®ion)];- drop(vm);- let calls = log.lock().unwrap().clone();- let first_unmap = calls- .iter()- .position(|call| matches!(call, Call::Unmap { .. }))- .unwrap();- let drops: Vec<_> = calls+ let drops = log+ .lock()+ .unwrap().iter()- .enumerate()- .filter(|(_, call)| matches!(call, Call::DropVcpu { .. }))- .map(|(index, _)| index)- .collect();- assert_eq!(drops.len(), 2, "{calls:?}");- assert!(drops.iter().all(|&index| index < first_unmap), "{calls:?}");- assert_eq!(memory_calls(&calls), expected_memory);+ .filter(|call| matches!(call, Call::DropVcpu { .. }))+ .count();+ assert_eq!(drops, 2);+ assert_eq!(memory_calls(&log.lock().unwrap()), expected_memory[..1]);+ drop(vm);+ assert_eq!(memory_calls(&log.lock().unwrap()), expected_memory);assert_eq!(memory_calls(&call_log.ioctl_calls()), expected_memory);}}@@ -1147,29 +1142,106 @@ mod lifecycle {);}- #[test]- fn a_stop_from_another_thread_ends_the_run() {- let vm = mock(2, MockVm::new());- let stop = vm.stop_handle();- let stopping = thread::spawn(move || {- thread::sleep(Duration::from_millis(50));- stop.stop();- });+ /// A guest write that holds a vCPU inside the run until the test releases it.+ struct HeldWrite {+ entered: mpsc::Sender<()>,+ release: mpsc::Receiver<()>,+ }- let (exit, _) = run(vm);+ impl BusDevice for HeldWrite {+ fn read(&mut self, _offset: u64, _data: &mut [u8]) {}- assert_eq!(exit.unwrap(), VmExit::StopRequested);- stopping.join().unwrap();+ fn write(&mut self, _offset: u64, _data: &[u8]) {+ self.entered.send(()).unwrap();+ self.release.recv_timeout(Duration::from_secs(10)).unwrap();+ }+ }++ #[test]+ fn external_control_observes_the_lifecycle_and_can_stop_execution() {+ for stop in [true, false] {+ const DEVICE: u64 = 0xd000_0000;+ let (entered, in_guest_exit) = mpsc::channel();+ let (release, released) = mpsc::channel();+ let backend = MockVm::with_scripts(vec![vec![+ Step::Write {+ addr: DEVICE,+ byte: 1,+ },+ Step::Shutdown,+ ]]);+ let mut vm = Vm::with_backend(+ config(1, 16),+ || Ok(backend),+ |_, _| Ok(BootRegisters::default()),+ |chipset, _| {+ chipset.add("held-write", |resources| {+ resources.mmio(DEVICE, 1);+ Ok(HeldWrite {+ entered,+ release: released,+ })+ })+ },+ )+ .unwrap();+ let control = vm.control();+ assert_eq!(control.status(), VmStatus::Created);+ let (done, finished) = mpsc::channel();+ let driver = thread::spawn(move || done.send((vm.run(), vm)).unwrap());++ in_guest_exit.recv_timeout(Duration::from_secs(10)).unwrap();+ assert_eq!(control.status(), VmStatus::Running);+ let other = control.clone();+ let (expected, observer) = if stop {+ other.stop();+ assert_eq!(control.status(), VmStatus::Stopping);+ (VmExit::StopRequested, Some(control))+ } else {+ drop(control);+ (VmExit::GuestShutdown, None)+ };+ drop(other);+ release.send(()).unwrap();++ let (exit, vm) = finished.recv_timeout(Duration::from_secs(10)).unwrap();+ driver.join().unwrap();+ assert_eq!(exit.unwrap(), expected);+ assert_eq!(+ observer.unwrap_or_else(|| vm.control()).status(),+ VmStatus::Exited+ );+ }}#[test]fn a_stop_before_the_run_ends_it_at_once() {- let vm = mock(2, MockVm::new());- vm.stop_handle().stop();+ for use_control in [true, false] {+ let backend = MockVm::new();+ let entries = backend.entries();+ let log = backend.log();+ let vm = mock(2, backend);+ let control = vm.control();+ if use_control {+ control.stop();+ } else {+ vm.stop_handle().stop();+ }+ assert_eq!(control.status(), VmStatus::Stopping);- let (exit, _) = run(vm);+ let (exit, mut vm) = run(vm);- assert_eq!(exit.unwrap(), VmExit::StopRequested);+ assert_eq!(exit.unwrap(), VmExit::StopRequested);+ 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 { .. }+ ))+ );+ assert!(matches!(vm.run(), Err(Error::AlreadyRan)));+ }}#[test]@@ -1647,8 +1719,9 @@ mod lifecycle {let mut vm = bare(config(1, 16), || Ok(backend)).unwrap();let runtime = Arc::new(StuckRuntime::default());vm.workers = Some(VirtioWorkers::with_runtime(runtime.clone()));+ let control = vm.control();- let (exit, vm) = run(vm);+ let (exit, mut vm) = run(vm);let error = exit.unwrap_err();if clean {@@ -1663,7 +1736,10 @@ mod lifecycle {"{error:?}");}+ assert_eq!(control.status(), super::VmStatus::Stopping);+ assert!(matches!(vm.run(), Err(Error::AlreadyRan)));drop(vm);+ assert_eq!(control.status(), super::VmStatus::Exited);assert_eq!(runtime.shutdowns.load(Ordering::SeqCst), 2);let calls = log.lock().unwrap().clone();assert!(calls.iter().any(|call| matches!(call, Call::Map { .. })));@@ -1676,6 +1752,26 @@ mod lifecycle {}}+#[test]+fn device_less_control_observes_stop_and_drop_and_rejects_disk_resize() {+ for stop_before_drop in [false, true] {+ let vm = bare(config(1, 16), || Ok(MockVm::new())).unwrap();+ let control = vm.control();+ assert_eq!(control.status(), crate::VmStatus::Created);+ let error = control+ .resize_disk("data", 1024, std::time::Duration::ZERO)+ .unwrap_err();+ assert_eq!(error.kind(), io::ErrorKind::InvalidInput);+ assert_eq!(error.to_string(), "no disk \"data\"");+ if stop_before_drop {+ control.stop();+ assert_eq!(control.status(), crate::VmStatus::Stopping);+ }+ drop(vm);+ assert_eq!(control.status(), crate::VmStatus::Exited);+ }+}+#[test]fn lifecycle_errors_describe_themselves() {let io = || io::Error::from(io::ErrorKind::Other);@@ -1724,6 +1820,128 @@ fn debug_shows_the_vm_shape_without_its_internals() {assert!(format!("{:?}", vm.stop_handle()).starts_with("StopHandle("));}+#[test]+#[cfg_attr(+ not(target_arch = "x86_64"),+ expect(clippy::unit_arg, reason = "arm64 has no boot registers yet.")+)]+fn dropping_vm_closes_disk_control_senders_while_stop_handle_remains() {+ use std::time::{Duration, Instant};++ use mio::{Events, Interest, Poll, Token};++ use crate::{+ DiskConfig, DiskFormat, VmStatus,+ events::Event,+ virtio::{+ blk::{device::VirtioBlk, imago::ImagoBackend},+ mmio::{self, Slots},+ },+ };++ fn assert_traits<T: Clone + fmt::Debug + Send + Sync>() {}+ assert_traits::<super::StopHandle>();++ let directory = tempfile::tempdir().unwrap();+ let disks: Vec<_> = ["disk-0", "disk-1"]+ .into_iter()+ .map(|block_id| {+ let path = directory.path().join(format!("{block_id}.raw"));+ std::fs::File::create(&path).unwrap().set_len(4096).unwrap();+ DiskConfig {+ block_id: block_id.into(),+ path,+ format: DiskFormat::Raw,+ read_only: false,+ }+ })+ .collect();+ let mut configuration = config(1, 16);+ configuration.disks = disks;++ let mut poll = Poll::new().unwrap();+ let mut sources = Vec::new();+ let vm = Vm::with_devices(+ configuration,+ || Ok(MockVm::new()),+ |_, _| Ok(BootRegisters::default()),+ |chipset, ctx, config, _| {+ let mut slots = Slots::new();+ for (index, disk) in config.disks.iter().enumerate() {+ let backend = ImagoBackend::open(&disk.path, disk.format, disk.read_only).unwrap();+ let controls = ctx.controls.register_disk(&disk.block_id).unwrap();+ let mut source = controls.event_source().unwrap();+ poll.registry()+ .register(source.as_source(), Token(index), Interest::READABLE)+ .unwrap();+ sources.push(source);+ let device = Arc::new(Mutex::new(VirtioBlk::new(Box::new(backend), controls)));+ mmio::add_device(+ chipset,+ &ctx,+ ["virtio-blk0", "virtio-blk1"][index],+ slots.take()?,+ device,+ )?;+ }+ Ok(())+ },+ )+ .unwrap();++ let stop = vm.stop_handle();+ let stop_clone = stop.clone();+ assert!(format!("{stop:?}").starts_with("StopHandle("));+ let control = vm.control();++ let mut events = Events::with_capacity(4);+ poll.poll(&mut events, Some(Duration::ZERO)).unwrap();+ assert!(+ events.is_empty(),+ "disk control sockets must stay open while the VM is alive"+ );++ // StopHandle::stop shares the same stop latch as VmControl::stop.+ assert_eq!(control.status(), VmStatus::Created);+ stop.stop();+ assert_eq!(control.status(), VmStatus::Stopping);+ assert!(vm.sender.is_stopping());+ control.stop();+ let mut vm_events = vm.events.lock().unwrap();+ assert!(matches!(+ vm_events.wait(Some(Duration::ZERO)).unwrap(),+ Some(Event::StopRequested)+ ));+ assert!(vm_events.wait(Some(Duration::ZERO)).unwrap().is_none());+ drop(vm_events);++ drop(control);+ drop(vm);++ // Every disk control sender must close on `drop(vm)` even while StopHandles survive.+ let mut closed = [false; 2];+ let deadline = Instant::now() + Duration::from_millis(200);+ while closed != [true, true] && Instant::now() < deadline {+ poll.poll(&mut events, Some(Duration::from_millis(20)))+ .unwrap();+ for event in &events {+ if event.is_read_closed() {+ closed[event.token().0] = true;+ }+ }+ }+ assert_eq!(+ closed,+ [true, true],+ "disk control sockets stayed open after drop(vm) while StopHandle was held"+ );++ stop_clone.stop();+ drop(stop);+ drop(stop_clone);+ drop(sources);+}+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]#[test]#[ignore = "requires Linux x86_64 with access to /dev/kvm"]@@ -1736,6 +1954,32 @@ fn new_names_a_kernel_it_cannot_load() {);}+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+#[test]+#[ignore = "requires Linux x86_64 with access to /dev/kvm"]+fn new_device_less_stops_before_run_and_rejects_a_second_run() {+ use crate::{VmExit, VmStatus};++ let directory = tempfile::tempdir().unwrap();+ let kernel = directory.path().join("kernel.elf");+ std::fs::write(&kernel, crate::boot::elf::tests::fixture()).unwrap();+ let mut configuration = config(1, 16);+ configuration.kernel = kernel;++ let mut vm = Vm::new_device_less(configuration).unwrap();+ let control = vm.control();+ assert_eq!(control.status(), VmStatus::Created);++ control.stop();+ assert_eq!(control.status(), VmStatus::Stopping);+ assert_eq!(vm.run().unwrap(), VmExit::StopRequested);+ assert_eq!(control.status(), VmStatus::Exited);+ assert!(matches!(vm.run(), Err(Error::AlreadyRan)));++ drop(vm);+ assert_eq!(control.status(), VmStatus::Exited);+}+/// Two KVM vCPUs through `Vm::run`: vCPU 0 runs a flat guest that pulses the/// i8042 reset, while vCPU 1 waits for an INIT that never comes, so only the/// kick after the reset ends it.