The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(vmm): grow a native disk online through the shim (#2743)
ltstriker5935e2960ac7
diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.mdindex cb51dc495..681e6ca87 100644--- a/docs/contributing/architecture/vmm/README.md+++ b/docs/contributing/architecture/vmm/README.md@@ -554,6 +554,13 @@ logged.attach order (`vda` container, `vdb` guest root), and defaults to `console=hvc0`.The single filesystem device exports logical shares below its aggregate root;matching mount instructions are sent only for the native engine.+- **Runtime control.** The runtime sends `resize_disk` to the native shim over+ the host-only `vmm.sock`, which stays open across transient accept errors.+ The shim routes requests by `block_id` through+ [`VmControl`](../../../../src/vmm/README.md#virtio-block-device).+- **File size limits.** The VMM bounds guest I/O by virtual disk capacity.+ The host kernel enforces the shim's configured or inherited+ [`RLIMIT_FSIZE` soft limit](../../../../src/boxlite/src/jailer/README.md#layer-3-resource-limits).- **libkrun assumptions outside `krun/`.**- The jailer copies libkrunfw into every box(`src/boxlite/src/jailer/shim_copy.rs:103-105`).diff --git a/docs/guides/ai-agent-integration.md b/docs/guides/ai-agent-integration.mdindex 609db5807..69dc8e472 100644--- a/docs/guides/ai-agent-integration.md+++ b/docs/guides/ai-agent-integration.md@@ -176,7 +176,10 @@ options = boxlite.BoxOptions(|--------|--------|---------|-----------------|----------|| `development()` | Off | Off | None | Debugging sandbox issues || `standard()` | On | On (Linux) | None | General workloads |-| `maximum()` | On | On (Linux) | `max_open_files=1024`, `max_file_size=1GiB`, `max_processes=100` | Untrusted AI code |+| `maximum()` | On | On (Linux) | `max_open_files=1024`, `max_processes=100` | Untrusted AI code |++The shim uses the configured file-size limit or inherits it from the host launcher.+See [file-size limits](../../src/boxlite/src/jailer/README.md#layer-3-resource-limits).For AI agents running untrusted code, use `SecurityOptions.maximum()`:@@ -393,7 +396,7 @@ options = boxlite.BoxOptions(| `jailer_enabled` | `bool` | OS-level sandbox (seccomp on Linux, sandbox-exec on macOS) || `seccomp_enabled` | `bool` | Syscall filtering (Linux only) || `max_open_files` | `int \| None` | Limit open file descriptors |-| `max_file_size` | `int \| None` | Maximum file size in bytes |+| `max_file_size` | `int \| None` | Maximum host file size in bytes || `max_processes` | `int \| None` | Maximum number of processes || `max_memory` | `int \| None` | Maximum virtual memory in bytes || `max_cpu_time` | `int \| None` | Maximum CPU time in seconds |diff --git a/docs/reference/rust/README.md b/docs/reference/rust/README.mdindex 5b1bb735b..cc2dbaded 100644--- a/docs/reference/rust/README.md+++ b/docs/reference/rust/README.md@@ -1306,6 +1306,10 @@ pub struct ResourceLimits {}```+When `max_file_size` is `None`, the shim inherits the host launcher's+`RLIMIT_FSIZE` soft and hard limits.+See [resource-limit enforcement](../../../src/boxlite/src/jailer/README.md#layer-3-resource-limits).+---## Metricsdiff --git a/make/coverage.mk b/make/coverage.mkindex 7c8446a8f..1654e8d17 100644--- a/make/coverage.mk+++ b/make/coverage.mk@@ -83,7 +83,7 @@ coverage\:vmm\:kvm: _ensure-kvm# Add the real-kernel boots of VMM_KERNEL to the same profiles, listed the same way.# CI runs it only when the vmm path filter matches.coverage\:vmm\:boot: export VMM_GUEST_MOUNT_INIT := $(PROJECT_ROOT)/target/vmm/guest-mount/x86_64-unknown-linux-musl/release/boxlite-guest-coverage\:vmm\:boot: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT) vmm\:guest-mount-init+coverage\:vmm\:boot: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT) $(VMM_DISK_GROW_INIT) vmm\:guest-mount-init@cargo llvm-cov nextest --no-report --no-tests=fail --profile ci --retries 0 --status-level pass \-p boxlite-vmm --lib --run-ignored only --test-threads=1 -E 'test(boot::tests::)'@cargo llvm-cov report $(COVERAGE_REPORT_ARGS) --lcov --output-path target/coverage/lcov.infodiff --git a/make/test.mk b/make/test.mkindex 31b8a9774..3b4b091f1 100644--- a/make/test.mk+++ b/make/test.mk@@ -319,7 +319,13 @@ export VMM_KERNELVMM_BALLOON_INIT ?= $(CURDIR)/target/vmm/boot/balloon-initexport VMM_BALLOON_INIT+# Freestanding guest that watches its disk grow while it runs.+VMM_DISK_GROW_INIT ?= $(CURDIR)/target/vmm/boot/disk-grow-init+export VMM_DISK_GROW_INIT+$(VMM_BALLOON_INIT): $(PROJECT_ROOT)/src/vmm/tests/boot/balloon_init.c+$(VMM_DISK_GROW_INIT): $(PROJECT_ROOT)/src/vmm/tests/boot/disk_grow_init.c+$(VMM_BALLOON_INIT) $(VMM_DISK_GROW_INIT):@mkdir -p "$(@D)"$(CC) -O2 -nostdlib -static -fno-pie -no-pie -fno-stack-protector -fno-builtin -Wl,--build-id=none "$<" -o "$@"@@ -340,7 +346,7 @@ VMM_BOOT_TESTS_TIMEOUT ?= 900s# Boot the real kernel on KVM and the legacy devices, on one and four vCPUs: up to its root-mount# panic, up to the panic when a generated init exits, and on a ttyS0 console until a generated# init restarts, once through the public Vm::new as the M1 smoke test.-test\:integration\:vmm\:linux: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT)+test\:integration\:vmm\:linux: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT) $(VMM_DISK_GROW_INIT)@cargo test -p boxlite-vmm --lib --no-run@timeout $(VMM_BOOT_TESTS_TIMEOUT) cargo test -p boxlite-vmm --lib boot::tests:: -- --ignored --test-threads=1 --nocapture --skip boot::tests::guest_mounts::@@ -361,7 +367,7 @@ export VMM_GUEST VMM_GUEST_PROBE_guest-boot-probe: $(if $(SETUP_DONE),,runtime\:debug)@bash "$(SCRIPT_DIR)/test/build-guest-boot-probe.sh"-test\:integration\:vmm\:native: _ensure-kvm _ensure-vmm-kernel $(if $(SETUP_DONE),,runtime\:debug) _guest-boot-probe+test\:integration\:vmm\:native: _ensure-kvm _ensure-vmm-kernel $(if $(SETUP_DONE),,runtime\:debug) _guest-boot-probe $(VMM_DISK_GROW_INIT)@cargo test -p boxlite --features native --lib --no-run@timeout 300s cargo test -p boxlite --features native --lib vmm::native::tests:: -- --ignored --test-threads=1@timeout 600s cargo test -p boxlite --features krun,gvproxy,native --test native_vmm -- --ignored --test-threads=1diff --git a/sdks/python/src/advanced_options.rs b/sdks/python/src/advanced_options.rsindex a52b36ba6..580fc52d8 100644--- a/sdks/python/src/advanced_options.rs+++ b/sdks/python/src/advanced_options.rs@@ -215,7 +215,7 @@ impl PySecurityOptions {jailer_enabled: true,seccomp_enabled: cfg!(target_os = "linux"),max_open_files: Some(1024),- max_file_size: Some(1024 * 1024 * 1024), // 1 GiB+ max_file_size: None,max_processes: Some(100),max_memory: None, // Let VM config handle thismax_cpu_time: None, // Let VM config handle thisdiff --git a/src/boxlite/src/disk/constants.rs b/src/boxlite/src/disk/constants.rsindex 3feb520dc..2c42a5a11 100644--- a/src/boxlite/src/disk/constants.rs+++ b/src/boxlite/src/disk/constants.rs@@ -23,14 +23,6 @@ pub mod qcow2 {/// Default disk size in GB (sparse, grows as needed)pub const DEFAULT_DISK_SIZE_GB: u64 = 10;- /// How many times the box's disk size the jailed shim's `RLIMIT_FSIZE` is- /// set to. Not a qcow2 format parameter: the shim is the sole writer of- /// these disks, so its per-file limit has to clear the disk it grows, and- /// this is the slack over it. Deliberately loose — the limit is a- /// runaway-write backstop, not a capacity policy (capacity is the qcow2- /// virtual size, where a full disk gives the guest a clean `ENOSPC`).- pub const FSIZE_DISK_MULTIPLIER: u64 = 2;-/// QCOW2 cluster size in bits (64KB = 2^16)pub const CLUSTER_BITS: usize = 16;diff --git a/src/boxlite/src/jailer/README.md b/src/boxlite/src/jailer/README.mdindex 386a533ae..51d596f37 100644--- a/src/boxlite/src/jailer/README.md+++ b/src/boxlite/src/jailer/README.md@@ -142,11 +142,20 @@ requiring maximum security should use Linux.| Resource | Limit Type | Purpose ||----------|------------|---------|| Open files | RLIMIT_NOFILE | Prevent FD exhaustion |-| File size | RLIMIT_FSIZE | Prevent disk filling |+| File size | RLIMIT_FSIZE | Cap growth of individual host files || Processes | RLIMIT_NPROC | Prevent fork bombs || Memory | RLIMIT_AS | Prevent OOM || CPU time | RLIMIT_CPU | Prevent CPU monopolization |+At startup, the jailer sets both `RLIMIT_FSIZE` limits to the configured+`ResourceLimits.max_file_size` in bytes. If the setting is absent, the shim+inherits both limits from the host launcher.++The VMM checks guest block I/O against the current virtual capacity. The host+kernel enforces the shim's soft limit on individual files. A sparse image can+grow in virtual capacity before later writes extend the host file and reach+that limit.+### Layer 4: Environment Sanitization**Mechanism**: Clear environment variables, close inherited FDsdiff --git a/src/boxlite/src/jailer/common/rlimit.rs b/src/boxlite/src/jailer/common/rlimit.rsindex cdeba6784..29df52a28 100644--- a/src/boxlite/src/jailer/common/rlimit.rs+++ b/src/boxlite/src/jailer/common/rlimit.rs@@ -145,3 +145,7 @@ mod tests {assert!(soft > 0, "Should have some file descriptors available");}}++#[cfg(all(test, target_os = "linux"))]+#[path = "tests/rlimit.rs"]+mod file_size_tests;diff --git a/src/boxlite/src/jailer/common/tests/rlimit.rs b/src/boxlite/src/jailer/common/tests/rlimit.rsnew file mode 100644index 000000000..4734ce404--- /dev/null+++ b/src/boxlite/src/jailer/common/tests/rlimit.rs@@ -0,0 +1,53 @@+use super::*;+use std::os::unix::process::CommandExt;+use std::process::Command;++#[test]+fn file_size_limit_follows_launch_configuration() {+ let before = get_rlimit(libc::RLIMIT_FSIZE).unwrap();+ assert_eq!(launch_file_size_limits(None), (4096, 8192));+ assert_eq!(launch_file_size_limits(Some(1024)), (1024, 1024));+ assert_eq!(get_rlimit(libc::RLIMIT_FSIZE).unwrap(), before);+}++fn launch_file_size_limits(max_file_size: Option<u64>) -> (libc::rlim_t, libc::rlim_t) {+ let mut child = Command::new("/bin/cat");+ child.arg("/proc/self/limits");++ // SAFETY: the test installs finite process limits in the child only.+ unsafe {+ child.pre_exec(|| {+ let inherited = libc::rlimit {+ rlim_cur: 4096,+ rlim_max: 8192,+ };+ if libc::setrlimit(libc::RLIMIT_FSIZE, &inherited) != 0 {+ return Err(io::Error::last_os_error());+ }+ Ok(())+ });+ }+ crate::jailer::pre_exec::add_pre_exec_hook(+ &mut child,+ ResourceLimits {+ max_file_size,+ ..ResourceLimits::default()+ },+ None,+ vec![],+ false,+ );++ let output = child.output().expect("run the launch child");+ assert!(output.status.success());+ let output = String::from_utf8(output.stdout).unwrap();+ let values = output+ .lines()+ .find_map(|line| line.strip_prefix("Max file size"))+ .expect("file-size limit row");+ let mut values = values.split_whitespace().map(str::parse::<libc::rlim_t>);+ (+ values.next().unwrap().unwrap(),+ values.next().unwrap().unwrap(),+ )+}diff --git a/src/boxlite/src/net/socket_path.rs b/src/boxlite/src/net/socket_path.rsindex 48b5f80ea..13ac63e8d 100644--- a/src/boxlite/src/net/socket_path.rs+++ b/src/boxlite/src/net/socket_path.rs@@ -64,6 +64,8 @@ const BOX_SOCK: &str = "box.sock";const READY_SOCK: &str = "ready.sock";/// Network backend (gvproxy) socket filename.const NET_SOCK: &str = "net.sock";+/// The shim's VMM control socket.+const VMM_SOCK: &str = "vmm.sock";/// Base directory for binding symlinks. Deliberately literal — see module docs.const SYMLINK_BASE: &str = "/tmp";@@ -124,6 +126,12 @@ impl BoxSockets {self.binding_dir().join(READY_SOCK)}+ /// Host-only VMM control socket the native shim serves; never bridged+ /// into guest vsock.+ pub fn vmm_sock(&self) -> PathBuf {+ self.binding_dir().join(VMM_SOCK)+ }+/// Network backend socket (gvproxy binds; libkrun derives a sibling/// `net.sock-krun.sock` from this path — the longest path in the dir).pub fn net_backend_sock(&self) -> PathBuf {@@ -334,11 +342,13 @@ mod tests {assert_eq!(s.binding_dir(), expect);assert_eq!(s.box_sock(), expect.join("box.sock"));assert_eq!(s.ready_sock(), expect.join("ready.sock"));+ assert_eq!(s.vmm_sock(), expect.join("vmm.sock"));assert_eq!(s.net_backend_sock(), expect.join("net.sock"));assert_eq!(s.net_backend_peer_sock(), expect.join("net.sock-krun.sock"));for p in [s.box_sock(),s.ready_sock(),+ s.vmm_sock(),s.net_backend_sock(),s.net_backend_peer_sock(),] {diff --git a/src/boxlite/src/runtime/advanced_options.rs b/src/boxlite/src/runtime/advanced_options.rsindex 8e5ecf14b..b0586ed33 100644--- a/src/boxlite/src/runtime/advanced_options.rs+++ b/src/boxlite/src/runtime/advanced_options.rs@@ -232,7 +232,7 @@ impl Default for SecurityOptions {env_allowlist: vec!["RUST_LOG".to_string()],resource_limits: ResourceLimits {max_open_files: Some(1024),- max_file_size: Some(1024 * 1024 * 1024), // 1GB+ max_file_size: None,// Per-box cgroup `pids.max` — the fork-bomb cap for the box's// host-side process tree (bwrap + shim + libkrun/gvproxy// threads), which sits well under this. Deliberately does NOTdiff --git a/src/boxlite/src/runtime/import.rs b/src/boxlite/src/runtime/import.rsindex 246892508..6116b9eb2 100644--- a/src/boxlite/src/runtime/import.rs+++ b/src/boxlite/src/runtime/import.rs@@ -127,15 +127,6 @@ fn options_from_manifest(return Err(rejected_upload("volume mounts"));}options.advanced.security = SecurityOptions::default();- // That reset also restores the default's hardcoded 1 GiB RLIMIT_FSIZE —- // the ceiling #1152 is about — because it replaces the whole struct rather- // than just the isolation fields it means to. The box still boots on a- // disk sized from its own `disk_size_gb`, so re-derive the limit.- // `sanitize` assigns it outright, so running it twice is idempotent.- options.sanitize().map_err(|error| {- BoxliteError::InvalidArgument(format!("invalid archive box_options: {error}"))- })?;-Ok(options)}@@ -275,7 +266,6 @@ pub(crate) fn validate_no_backing_references(disk_path: &Path) -> BoxliteResult<#[cfg(test)]mod tests {use super::*;- use crate::runtime::types::Bytes;use tempfile::TempDir;fn v3_manifest(options: BoxOptions) -> ArchiveManifest {@@ -509,32 +499,7 @@ mod tests {options_from_manifest(&v3_manifest(options), ArchiveImportPolicy::UntrustedRemote).unwrap();- // Everything but the file-size ceiling is the server default; that one- // is derived from the box's own disk (#1152), so it is the default's- // stale 1 GiB that must NOT come back.- let mut expected = SecurityOptions::default();- expected.resource_limits.max_file_size = Some(Bytes::from_gib(20).as_bytes());- assert_eq!(resolved.advanced.security, expected);- }-- /// The server-default reset must not put the 1 GiB ceiling back: an- /// uploaded archive's box boots on a disk sized from its own- /// `disk_size_gb` and needs a limit that covers it.- #[test]- fn untrusted_import_derives_the_fsize_limit_from_the_disk() {- let options = BoxOptions {- disk_size_gb: Some(20),- ..BoxOptions::default()- };-- let resolved =- options_from_manifest(&v3_manifest(options), ArchiveImportPolicy::UntrustedRemote)- .unwrap();-- assert_eq!(- resolved.advanced.security.resource_limits.max_file_size,- Some(Bytes::from_gib(40).as_bytes())- );+ assert_eq!(resolved.advanced.security, SecurityOptions::default());}#[test]@@ -543,6 +508,8 @@ mod tests {advanced.nested_virtualization = true;advanced.privileged = true;advanced.security = SecurityOptions::disabled();+ advanced.security.resource_limits.max_file_size = Some(1 << 30);+ let security = advanced.security.clone();let options = BoxOptions {advanced,..Default::default()@@ -554,12 +521,7 @@ mod tests {assert!(resolved.advanced.nested_virtualization);assert!(resolved.advanced.privileged);- // `sanitize` derives RLIMIT_FSIZE from `disk_size_gb` (#1152), so the- // one security field a trusted import does not carry over verbatim is- // the file-size ceiling. Everything else is preserved.- let mut expected = SecurityOptions::disabled();- expected.resource_limits.max_file_size = Some(Bytes::from_gib(20).as_bytes());- assert_eq!(resolved.advanced.security, expected);+ assert_eq!(resolved.advanced.security, security);}#[test]diff --git a/src/boxlite/src/runtime/options.rs b/src/boxlite/src/runtime/options.rsindex 58fdbe1cb..9da2046b0 100644--- a/src/boxlite/src/runtime/options.rs+++ b/src/boxlite/src/runtime/options.rs@@ -9,10 +9,8 @@ use std::collections::BTreeMap;use std::net::{IpAddr, Ipv4Addr, SocketAddr};use std::path::{Path, PathBuf};-use crate::disk::constants::qcow2::{DEFAULT_DISK_SIZE_GB, FSIZE_DISK_MULTIPLIER};use crate::runtime::advanced_options::AdvancedBoxOptions;use crate::runtime::constants::vm_defaults::MAX_CPUS;-use crate::runtime::types::Bytes;use std::fmt;// ============================================================================@@ -978,27 +976,6 @@ impl BoxOptions {kernel.sanitize()?;}- // The jailed shim is the sole writer of this box's qcow2 disks, so its- // per-file RLIMIT_FSIZE caps their growth: a write past it fails with- // `EFBIG` and takes the guest down. `SecurityOptions::default()` cannot- // pick that number — it runs for a box that does not exist yet and- // cannot see `disk_size_gb` — which is how a fixed 1 GiB ceiling ended- // up contradicting every larger disk (#1152). Derive it here, next to- // the size it comes from.- //- // `FSIZE_DISK_MULTIPLIER` is deliberately loose: this is a- // runaway-write backstop, not a capacity policy. Capacity is the qcow2- // virtual size, where a guest that fills its disk gets a clean `ENOSPC`- // inside the box rather than a host-side `SIGXFSZ` that kills the VM.- self.advanced.security.resource_limits.max_file_size = Some(- Bytes::from_gib(- self.disk_size_gb- .unwrap_or(DEFAULT_DISK_SIZE_GB)- .saturating_mul(FSIZE_DISK_MULTIPLIER),- )- .as_bytes(),- );-Ok(())}@@ -1706,7 +1683,6 @@ mod tests {use crate::runtime::advanced_options::{ContainerCapabilities, NetworkRateLimit, SecurityOptions, SecurityOptionsBuilder,};- use crate::runtime::types::Bytes;/// The type decides whose storage `source` names, so only the two exact/// spellings parse; a near miss is an error naming what is accepted.@@ -3011,6 +2987,27 @@ mod tests {assert_eq!(opts.resource_limits.max_cpu_time, Some(300));}+ #[test]+ fn sanitize_preserves_configured_file_size_limit() {+ let mut options = BoxOptions {+ disk_size_gb: Some(20),+ ..BoxOptions::default()+ };+ options.sanitize().unwrap();+ assert_eq!(+ options.advanced.security.resource_limits.max_file_size,+ None+ );++ let configured_limit = 32 << 30;+ options.advanced.security.resource_limits.max_file_size = Some(configured_limit);+ options.sanitize().unwrap();+ assert_eq!(+ options.advanced.security.resource_limits.max_file_size,+ Some(configured_limit)+ );+ }+#[test]fn test_security_builder_env_allowlist() {let opts = SecurityOptionsBuilder::new()@@ -3354,37 +3351,6 @@ mod tests {assert_eq!(opts2.resource_limits.max_processes, Some(50));}- /// The whole point of #1152: the ceiling has to follow the box's own- /// `--disk-size`, not a constant picked before the box existed.- #[test]- fn sanitize_scales_fsize_with_the_requested_disk() {- let mut options = BoxOptions {- disk_size_gb: Some(20),- ..BoxOptions::default()- };- options.sanitize().unwrap();-- assert_eq!(- options.advanced.security.resource_limits.max_file_size,- Some(Bytes::from_gib(40).as_bytes()),- "a 20 GiB box gets a 40 GiB ceiling"- );- }-- /// No explicit size: the disk is created at `DEFAULT_DISK_SIZE_GB`, so the- /// ceiling tracks that.- #[test]- fn sanitize_falls_back_to_the_default_disk_size() {- let mut options = BoxOptions::default();- options.sanitize().unwrap();-- assert_eq!(- options.advanced.security.resource_limits.max_file_size,- Some(Bytes::from_gib(20).as_bytes()),- "the default 10 GiB disk gets a 20 GiB ceiling"- );- }-#[test]fn required_headers_create_rejects_absent_null_empty() {for suffix in ["", ",\"headers\":null", ",\"headers\":{}"] {diff --git a/src/boxlite/src/vmm/mod.rs b/src/boxlite/src/vmm/mod.rsindex 709b0e0f9..baf8b6eeb 100644--- a/src/boxlite/src/vmm/mod.rs+++ b/src/boxlite/src/vmm/mod.rs@@ -26,6 +26,11 @@ pub mod krun;#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]pub mod native;pub mod registry;+#[cfg(any(+ test,+ all(feature = "native", target_os = "linux", target_arch = "x86_64")+))]+pub(crate) mod vmm_socket;use crate::experimental::custom_kernel::{KernelFormat, KernelOptions};use crate::jailer::SecurityOptions;diff --git a/src/boxlite/src/vmm/native/engine.rs b/src/boxlite/src/vmm/native/engine.rsindex 09336d30d..c548f8052 100644--- a/src/boxlite/src/vmm/native/engine.rs+++ b/src/boxlite/src/vmm/native/engine.rs@@ -3,17 +3,20 @@//! `create` translates the `InstanceSpec` into a `VmConfig`; `enter` builds//! the VM and runs it until the guest resets or powers off.-use std::{fs::File, io, path::PathBuf};+use std::{fs::File, io, path::PathBuf, time::Duration};use crate::experimental::custom_kernel::KernelFormat;use crate::rootfs::guest::Strategy;use crate::runtime::constants::vm_defaults::{DEFAULT_CPUS, DEFAULT_MEMORY_MIB};+use crate::vmm::vmm_socket::{self, ControlError, ControlOp, ControlReply, ControlResponse};use crate::vmm::{DiskFormat, InstanceSpec, Vmm, VmmConfig, VmmInstance, VmmKind, engine::VmmInstanceImpl,guest_args, registry::EngineFactoryRegistration,};use boxlite_shared::errors::{BoxliteError, BoxliteResult};-use boxlite_vmm::{DiskConfig, FsConfig, FsShareConfig, NetConfig, Vm, VmConfig, VsockConfig};+use boxlite_vmm::{+ DiskConfig, FsConfig, FsShareConfig, NetConfig, Vm, VmConfig, VmControl, VsockConfig,+};/// The command line when the box brings no custom one: the virtio console, a/// reset on panic and on `reboot`, as the VMM's own boot tests use.@@ -34,6 +37,8 @@ impl Native {struct NativeVmmInstance {config: VmConfig,console: Option<PathBuf>,+ /// Where the host reaches this VM's control channel.+ vmm_socket_path: PathBuf,}impl VmmInstanceImpl for NativeVmmInstance {@@ -48,12 +53,41 @@ impl VmmInstanceImpl for NativeVmmInstance {None => Box::new(io::sink()),};let mut vm = Vm::new(self.config, sink).map_err(map_vmm_error)?;+ let vm_control = vm.control();+ // Without the channel the box still runs; it only cannot grow online.+ if let Err(error) = vmm_socket::serve(&self.vmm_socket_path, move |op| {+ handle_control_op(&vm_control, op)+ }) {+ tracing::warn!(+ %error,+ path = %self.vmm_socket_path.display(),+ "VMM control socket unavailable"+ );+ }let exit = vm.run().map_err(map_vmm_error)?;tracing::info!(?exit, "native VM ended");Ok(())}}+/// How long a grow may wait for the block device's worker.+const GROW_TIMEOUT: Duration = Duration::from_secs(10);++/// Serves one control operation against the VM's disks.+pub(crate) fn handle_control_op(vm: &VmControl, op: ControlOp) -> ControlResponse {+ match op {+ ControlOp::ResizeDisk { block_id, bytes } => vm+ .resize_disk(&block_id, bytes, GROW_TIMEOUT)+ .map(ControlReply::DiskSize)+ .map_err(|error| match error.kind() {+ io::ErrorKind::InvalidInput | io::ErrorKind::PermissionDenied => {+ ControlError::InvalidInput(error.to_string())+ }+ _ => ControlError::Failed(error.to_string()),+ }),+ }+}+/// Requests the engine cannot serve; any one fails `create` before boot.pub(crate) fn unsupported_requests(spec: &InstanceSpec) -> Vec<&'static str> {let mut requests = Vec::new();@@ -105,6 +139,7 @@ pub(crate) fn build_config(spec: &InstanceSpec) -> BoxliteResult<VmConfig> {.devices().iter().map(|device| DiskConfig {+ block_id: device.block_id.clone(),path: device.disk_path.clone(),format: match device.format {DiskFormat::Raw => boxlite_vmm::DiskFormat::Raw,@@ -267,9 +302,19 @@ impl Vmm for Native {kernel = %vm_config.kernel.display(),"native VM configured");+ let box_dir = config+ .exit_file+ .parent()+ .ok_or_else(|| BoxliteError::Engine("the exit file has no box directory".into()))?;+ let vmm_socket_path = crate::net::socket_path::BoxSockets::new(+ config.box_id.clone(),+ box_dir.join(crate::runtime::layout::dirs::SOCKETS_DIR),+ )+ .vmm_sock();Ok(VmmInstance::new(Box::new(NativeVmmInstance {config: vm_config,console: config.console_output,+ vmm_socket_path,})))}}diff --git a/src/boxlite/src/vmm/native/tests/m1_initramfs.rs b/src/boxlite/src/vmm/native/tests/m1_initramfs.rsindex 6671747ed..36e5133b9 100644--- a/src/boxlite/src/vmm/native/tests/m1_initramfs.rs+++ b/src/boxlite/src/vmm/native/tests/m1_initramfs.rs@@ -75,7 +75,7 @@ fn print_and_restart(line: &str) -> Vec<u8> {/// An uncompressed newc archive holding one executable file, `name`/// (`Documentation/driver-api/early-userspace/buffer-format.rst`).-fn newc_archive(name: &str, data: &[u8]) -> Vec<u8> {+pub(super) fn newc_archive(name: &str, data: &[u8]) -> Vec<u8> {fn entry(archive: &mut Vec<u8>, ino: u32, mode: u32, name: &str, data: &[u8]) {let fields = [ino,diff --git a/src/boxlite/src/vmm/native/tests/mod.rs b/src/boxlite/src/vmm/native/tests/mod.rsindex 96fc7467d..c2d5e32a0 100644--- a/src/boxlite/src/vmm/native/tests/mod.rs+++ b/src/boxlite/src/vmm/native/tests/mod.rs@@ -342,7 +342,7 @@ fn each_environment_entry_stays_one_kernel_parameter() {}#[test]-fn the_vm_config_keeps_the_disks_in_attach_order() {+fn the_vm_config_keeps_disk_ids_and_attach_order() {let test_box = TestBox::new();let kernel = test_box.stage_kernel(&fake_kernel(), Some(b"070701"));let spec = runtime_like_spec(&test_box, Some(kernel.clone()));@@ -356,17 +356,26 @@ fn the_vm_config_keeps_the_disks_in_attach_order() {let disks: Vec<_> = config.disks.iter()- .map(|disk| (disk.path.clone(), disk.format, disk.read_only))+ .map(|disk| {+ (+ disk.block_id.as_str(),+ disk.path.clone(),+ disk.format,+ disk.read_only,+ )+ }).collect();assert_eq!(disks,[(+ "vda",PathBuf::from("/disks/disk.qcow2"),boxlite_vmm::DiskFormat::Qcow2,false),(+ "vdb",PathBuf::from("/bases/guest.ext4"),boxlite_vmm::DiskFormat::Raw,true@@ -476,3 +485,76 @@ async fn reports_a_missing_kernel_through_the_exit_file() {other => panic!("expected an Unsupported exit record, got {other:?}"),}}++#[tokio::test]+#[ignore = "requires Linux x86_64 with /dev/kvm, VMM_KERNEL, VMM_DISK_GROW_INIT and a boxlite-shim built with native"]+async fn grows_a_disk_through_the_shim_control_socket() {+ use crate::vmm::vmm_socket::{ControlOp, ControlReply, ControlRequest, VERSION, request};++ let test_box = TestBox::new();+ let kernel = fs::read(std::env::var_os("VMM_KERNEL").expect("set VMM_KERNEL")).unwrap();+ let init =+ fs::read(std::env::var_os("VMM_DISK_GROW_INIT").expect("set VMM_DISK_GROW_INIT")).unwrap();+ let archive = m1_initramfs::newc_archive("init", &init);+ let prepared = test_box.stage_kernel(&kernel, Some(&archive));+ // The container disk path is one the jail grants read-write; the test+ // serves a raw image there.+ fs::create_dir_all(test_box.layout.disks_dir()).unwrap();+ let disk = test_box.layout.disk_path();+ fs::File::create(&disk).unwrap().set_len(1 << 20).unwrap();+ let mut spec = test_box.spec(Some(prepared));+ spec.block_devices.add(BlockDevice {+ block_id: "vda".to_string(),+ disk_path: disk.clone(),+ read_only: false,+ format: DiskFormat::Raw,+ });++ let mut controller = ShimController::new(+ find_binary("boxlite-shim").unwrap(),+ VmmKind::Native,+ test_box.box_id.clone(),+ BoxOptions::default(),+ test_box.layout.clone(),+ )+ .unwrap();+ let handler = controller.start(&spec).await.unwrap();+ let started = std::time::Instant::now();+ while !test_box.console().contains("GROW_BEFORE") {+ assert!(+ started.elapsed() < SHIM_TIMEOUT && handler.is_running(),+ "console:\n{}\nexit: {:?}",+ test_box.console(),+ fs::read_to_string(test_box.layout.exit_file_path())+ );+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ let path = test_box.layout.sockets().vmm_sock();+ let grow = ControlRequest {+ version: VERSION,+ op: ControlOp::ResizeDisk {+ block_id: "vda".into(),+ bytes: 2 << 20,+ },+ };+ let reply = tokio::task::spawn_blocking(move || request(&path, &grow, Duration::from_secs(15)))+ .await+ .unwrap()+ .unwrap();+ let exit = tokio::time::timeout(+ SHIM_TIMEOUT,+ ProcessMonitor::new(handler.pid()).wait_for_exit(),+ )+ .await+ .expect("the shim exits within the timeout");++ let console = test_box.console();+ assert_eq!(+ reply,+ Ok(ControlReply::DiskSize(2 << 20)),+ "console:\n{console}"+ );+ assert_eq!(exit, ProcessExit::Code(0), "console:\n{console}");+ assert!(console.contains("GROW_AFTER 4096"), "console:\n{console}");+ assert_eq!(fs::metadata(&disk).unwrap().len(), 2 << 20);+}diff --git a/src/boxlite/src/vmm/tests/vmm_socket.rs b/src/boxlite/src/vmm/tests/vmm_socket.rsnew file mode 100644index 000000000..e4ee9d85a--- /dev/null+++ b/src/boxlite/src/vmm/tests/vmm_socket.rs@@ -0,0 +1,162 @@+use super::*;+use std::os::unix::fs::PermissionsExt;++fn grow_to(block_id: &str, bytes: u64) -> ControlRequest {+ ControlRequest {+ version: VERSION,+ op: ControlOp::ResizeDisk {+ block_id: block_id.into(),+ bytes,+ },+ }+}++#[test]+fn a_request_reaches_the_handler_and_its_answer_returns() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ serve(&path, |op| match op {+ ControlOp::ResizeDisk { block_id, bytes } if block_id == "container" => {+ Ok(ControlReply::DiskSize(bytes))+ }+ ControlOp::ResizeDisk { block_id, .. } => {+ Err(ControlError::InvalidInput(format!("no disk {block_id}")))+ }+ })+ .unwrap();+ let mode = std::fs::metadata(&path).unwrap().permissions().mode();+ assert_eq!(mode & 0o777, 0o600, "the socket is owner-only");++ let timeout = Duration::from_secs(5);+ assert_eq!(+ request(&path, &grow_to("container", 4096), timeout).unwrap(),+ Ok(ControlReply::DiskSize(4096))+ );+ assert_eq!(+ request(&path, &grow_to("missing", 4096), timeout).unwrap(),+ Err(ControlError::InvalidInput("no disk missing".into()))+ );+}++#[test]+fn accept_recovers_from_temporary_errors_with_bounded_backoff() {+ let (mut client, stream) = UnixStream::pair().unwrap();+ client+ .set_read_timeout(Some(Duration::from_secs(1)))+ .unwrap();+ write_frame(+ &mut client,+ &serde_json::to_vec(&grow_to("container", 4096)).unwrap(),+ )+ .unwrap();++ let accept_error = |errno| Err(io::Error::from_raw_os_error(errno));+ let incoming = [+ accept_error(libc::EMFILE),+ accept_error(libc::ENFILE),+ accept_error(libc::ECONNABORTED),+ accept_error(libc::EINTR),+ accept_error(libc::EMFILE),+ accept_error(libc::ENFILE),+ accept_error(libc::EMFILE),+ accept_error(libc::ENFILE),+ Ok(stream),+ accept_error(libc::EMFILE),+ accept_error(libc::EBADF),+ ];+ let incoming = incoming.into_iter().chain(std::iter::once_with(|| {+ panic!("the listener must stop accepting after EBADF")+ }));+ let mut waits = Vec::new();+ serve_connections(+ incoming,+ |ControlOp::ResizeDisk { bytes, .. }| Ok(ControlReply::DiskSize(bytes)),+ |delay| waits.push(delay),+ );++ let reply = read_frame(&mut client).expect("request after EMFILE must receive a reply");+ let reply: ControlResponse = serde_json::from_slice(&reply).unwrap();+ assert_eq!(reply, Ok(ControlReply::DiskSize(4096)));+ assert_eq!(waits, [5, 10, 20, 40, 50, 50, 5].map(Duration::from_millis));+}++#[test]+fn another_version_is_unsupported_and_the_shim_keeps_serving() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ serve(&path, |_| Ok(ControlReply::DiskSize(1))).unwrap();+ let timeout = Duration::from_secs(5);+ let mut future = grow_to("container", 512);+ future.version = VERSION + 1;+ assert!(matches!(+ request(&path, &future, timeout).unwrap(),+ Err(ControlError::Unsupported(_))+ ));+ assert_eq!(+ request(&path, &grow_to("container", 512), timeout).unwrap(),+ Ok(ControlReply::DiskSize(1))+ );+}++#[test]+fn an_oversized_or_unknown_request_is_bounded() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ serve(&path, |_| Ok(ControlReply::DiskSize(1))).unwrap();++ // An oversized frame ends the connection without a reply.+ let mut stream = UnixStream::connect(&path).unwrap();+ stream.write_all(&(MAX_FRAME + 1).to_le_bytes()).unwrap();+ let mut reply = Vec::new();+ stream.read_to_end(&mut reply).unwrap();+ assert!(reply.is_empty());++ // An operation this protocol does not name is refused as invalid.+ let mut stream = UnixStream::connect(&path).unwrap();+ write_frame(&mut stream, br#"{"version":1,"op":"reboot"}"#).unwrap();+ let response: ControlResponse =+ serde_json::from_slice(&read_frame(&mut stream).unwrap()).unwrap();+ assert!(matches!(response, Err(ControlError::InvalidInput(_))));++ // A client that never sends is dropped after the timeout; serving goes on.+ let _silent = UnixStream::connect(&path).unwrap();+ assert_eq!(+ request(&path, &grow_to("container", 512), Duration::from_secs(5)).unwrap(),+ Ok(ControlReply::DiskSize(1))+ );+}++#[test]+fn serving_replaces_a_stale_socket() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ drop(UnixListener::bind(&path).unwrap());+ serve(&path, |_| Ok(ControlReply::DiskSize(7))).unwrap();+ assert_eq!(+ request(&path, &grow_to("container", 7), Duration::from_secs(5)).unwrap(),+ Ok(ControlReply::DiskSize(7))+ );+}++#[test]+fn resize_requires_a_block_id_and_rejects_index_only_requests() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ serve(&path, |_| {+ panic!("invalid requests must not reach the handler")+ })+ .unwrap();+ for body in [+ br#"{"version":1,"op":"resize_disk","bytes":4096}"#.as_slice(),+ br#"{"version":1,"op":"resize_disk","index":0,"bytes":4096}"#.as_slice(),+ ] {+ let mut stream = UnixStream::connect(&path).unwrap();+ stream+ .set_read_timeout(Some(Duration::from_secs(5)))+ .unwrap();+ write_frame(&mut stream, body).unwrap();+ let response: ControlResponse =+ serde_json::from_slice(&read_frame(&mut stream).unwrap()).unwrap();+ assert!(matches!(response, Err(ControlError::InvalidInput(_))));+ }+}diff --git a/src/boxlite/src/vmm/vmm_socket.rs b/src/boxlite/src/vmm/vmm_socket.rsnew file mode 100644index 000000000..5d2b12870--- /dev/null+++ b/src/boxlite/src/vmm/vmm_socket.rs@@ -0,0 +1,193 @@+//! The host's control channel to a running shim.+//!+//! The shim serves one Unix socket, `vmm.sock` in the box's socket+//! directory, for runtime operations on the VMM it hosts. The socket is+//! host-only (mode 0600, never bridged into guest vsock) and at a fixed path,+//! so a runtime that restarts can still reach a running box. Each connection+//! carries one request and one response: a 4-byte little-endian length, then+//! a JSON object of at most [`MAX_FRAME`] bytes. Requests name [`VERSION`];+//! a shim answers any other version, or an operation its engine lacks, with+//! [`ControlError::Unsupported`].++use std::io::{self, Read, Write};+use std::os::unix::net::{UnixListener, UnixStream};+use std::path::Path;+use std::time::Duration;++use serde::{Deserialize, Serialize};++/// The protocol version a request names.+pub(crate) const VERSION: u32 = 1;+/// The largest frame either side accepts.+const MAX_FRAME: u32 = 4096;+/// How long the shim waits for a request or a reply write.+const IO_TIMEOUT: Duration = Duration::from_secs(2);+const ACCEPT_RETRY_INITIAL: Duration = Duration::from_millis(5);+const ACCEPT_RETRY_MAX: Duration = Duration::from_millis(50);++/// One versioned request. Its operation sits beside `version`, tagged by+/// `op`; an unknown operation fails to parse.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub(crate) struct ControlRequest {+ pub(crate) version: u32,+ #[serde(flatten)]+ pub(crate) op: ControlOp,+}++/// The operations a shim may serve.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "op", rename_all = "snake_case")]+pub(crate) enum ControlOp {+ /// Grows the disk with the configured `block_id` to `bytes`.+ ResizeDisk { block_id: String, bytes: u64 },+}++/// The shim's answer.+pub(crate) type ControlResponse = Result<ControlReply, ControlError>;++/// What a successful operation reports.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub(crate) enum ControlReply {+ /// The disk's size in bytes after the operation.+ DiskSize(u64),+}++/// Why an operation failed.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, thiserror::Error)]+#[serde(rename_all = "snake_case")]+pub(crate) enum ControlError {+ #[error("unsupported: {0}")]+ Unsupported(String),+ #[error("invalid request: {0}")]+ InvalidInput(String),+ #[error("{0}")]+ Failed(String),+}++/// Binds `path` (replacing a stale socket), makes it owner-only, and serves+/// each connection on a `vmm-control` thread with `handle`.+pub(crate) fn serve(+ path: &Path,+ handle: impl Fn(ControlOp) -> ControlResponse + Send + 'static,+) -> io::Result<()> {+ if std::fs::symlink_metadata(path).is_ok() {+ std::fs::remove_file(path)?;+ }+ let listener = UnixListener::bind(path)?;+ restrict_to_owner(path)?;+ std::thread::Builder::new()+ .name("vmm-control".into())+ .spawn(move || serve_connections(listener.incoming(), handle, std::thread::sleep))?;+ Ok(())+}++fn serve_connections(+ incoming: impl Iterator<Item = io::Result<UnixStream>>,+ handle: impl Fn(ControlOp) -> ControlResponse,+ mut sleep: impl FnMut(Duration),+) {+ use io::ErrorKind::{ConnectionAborted, Interrupted};++ let mut retry_delay = ACCEPT_RETRY_INITIAL;+ for connection in incoming {+ let stream = match connection {+ Ok(stream) => {+ retry_delay = ACCEPT_RETRY_INITIAL;+ stream+ }+ Err(error) if matches!(error.kind(), Interrupted | ConnectionAborted) => continue,+ Err(error)+ if matches!(+ error.raw_os_error(),+ Some(libc::EBADF | libc::ENOTSOCK | libc::EINVAL)+ ) =>+ {+ tracing::error!(%error, "VMM control listener stopped");+ break;+ }+ Err(error) => {+ if retry_delay == ACCEPT_RETRY_INITIAL {+ tracing::warn!(%error, "VMM control accept failed, retrying");+ }+ sleep(retry_delay);+ retry_delay = (retry_delay * 2).min(ACCEPT_RETRY_MAX);+ continue;+ }+ };+ if let Err(error) = answer(stream, &handle) {+ tracing::debug!(%error, "control connection ended");+ }+ }+}++fn answer(+ mut stream: UnixStream,+ handle: &impl Fn(ControlOp) -> ControlResponse,+) -> io::Result<()> {+ stream.set_read_timeout(Some(IO_TIMEOUT))?;+ stream.set_write_timeout(Some(IO_TIMEOUT))?;+ let response = match serde_json::from_slice::<ControlRequest>(&read_frame(&mut stream)?) {+ Ok(request) if request.version == VERSION => handle(request.op),+ Ok(request) => Err(ControlError::Unsupported(format!(+ "protocol version {}",+ request.version+ ))),+ Err(error) => Err(ControlError::InvalidInput(error.to_string())),+ };+ write_frame(&mut stream, &serde_json::to_vec(&response)?)+}++/// Sends `request` to the shim at `path` and waits up to `timeout` for the+/// answer, as the host side of one exchange.+#[cfg(test)]+pub(crate) fn request(+ path: &Path,+ request: &ControlRequest,+ timeout: Duration,+) -> io::Result<ControlResponse> {+ let mut stream = UnixStream::connect(path)?;+ stream.set_read_timeout(Some(timeout))?;+ stream.set_write_timeout(Some(timeout))?;+ write_frame(&mut stream, &serde_json::to_vec(request)?)?;+ Ok(serde_json::from_slice(&read_frame(&mut stream)?)?)+}++fn read_frame(stream: &mut UnixStream) -> io::Result<Vec<u8>> {+ let mut length = [0u8; 4];+ stream.read_exact(&mut length)?;+ let length = u32::from_le_bytes(length);+ if length > MAX_FRAME {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ format!("control frame of {length} bytes exceeds {MAX_FRAME}"),+ ));+ }+ let mut frame = vec![0u8; length as usize];+ stream.read_exact(&mut frame)?;+ Ok(frame)+}++fn write_frame(stream: &mut UnixStream, frame: &[u8]) -> io::Result<()> {+ let length = u32::try_from(frame.len())+ .ok()+ .filter(|length| *length <= MAX_FRAME)+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "control frame too large"))?;+ stream.write_all(&length.to_le_bytes())?;+ stream.write_all(frame)+}++/// `fchmodat`, which the shim's seccomp profile allows, rather than `chmod`.+fn restrict_to_owner(path: &Path) -> io::Result<()> {+ use std::os::unix::ffi::OsStrExt;+ let path = std::ffi::CString::new(path.as_os_str().as_bytes())?;+ // SAFETY: `path` is a valid NUL-terminated string for the call.+ if unsafe { libc::fchmodat(libc::AT_FDCWD, path.as_ptr(), 0o600, 0) } != 0 {+ return Err(io::Error::last_os_error());+ }+ Ok(())+}++#[cfg(test)]+#[path = "tests/vmm_socket.rs"]+mod tests;diff --git a/src/boxlite/tests/import_export_benchmark.rs b/src/boxlite/tests/import_export_benchmark.rsindex 1ee092cc9..dc230ead8 100644--- a/src/boxlite/tests/import_export_benchmark.rs+++ b/src/boxlite/tests/import_export_benchmark.rs@@ -24,7 +24,6 @@ use tracing_subscriber::fmt::writer::TestWriter;const BYTES_PER_MIB: f64 = 1024.0 * 1024.0;const GIB: u64 = 1024 * 1024 * 1024;const PAYLOAD_BYTES: u64 = GIB;-const MAX_FILE_SIZE_BYTES: u64 = 2 * GIB;const DISK_SIZE_GB: u64 = 4;const WARMUP_RUNS: usize = 1;const SAMPLE_RUNS: usize = 3;@@ -166,7 +165,6 @@ async fn test_import_export_1gib_benchmark() {async fn create_benchmark_source(runtime: &BoxliteRuntime) -> LiteBox {let mut options = common::alpine_opts();options.disk_size_gb = Some(DISK_SIZE_GB);- options.advanced.security.resource_limits.max_file_size = Some(MAX_FILE_SIZE_BYTES);let source = runtime.create(options, Some("import-export-perf-source".to_string()))diff --git a/src/vmm/README.md b/src/vmm/README.mdindex a029b7cf2..09b6f1ac4 100644--- a/src/vmm/README.md+++ b/src/vmm/README.md@@ -8,8 +8,8 @@ registers guest RAM and loads the kernel and boot data; `Vm::run` runs every vCP[VMM design](../../docs/contributing/architecture/vmm/README.md) specifies thelifecycle API, memory layout, buses, interrupts, and threads.-`Vm`, `VmConfig`, `ReclaimPolicy`, `VmExit`, `StopHandle`, `Error` and `Result`-are public, as are `BusKind` and `Conflict`, which `Error::ChipsetConflicts`+`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 hostcause.`Vm::new(config, console)` adds COM1, the i8042 and virtio-balloon; COM1@@ -27,7 +27,7 @@ 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` 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; `StopHandle`, `control` and `VmExit` || `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 |@@ -739,7 +739,7 @@ took, and then announces that slot on the kernel command line.chipset claim and the kernel's view come from the same value. Disks takeslots in `VmConfig::disks` order, so disk 0 is `/dev/vda`, disk 1 is`/dev/vdb`, and so on.-- **Configuration.** `DiskConfig { path, format: Raw | Qcow2, read_only }`;+- **Configuration.** `DiskConfig { block_id, path, format: Raw | Qcow2, read_only }`;the format is stated, never probed from the file. A qcow2 image opens thebacking chain its header names. At most 8 disks; `blk::add_disk` fails with`Error::OpenDisk` for an image it cannot open and `add_all` fails with@@ -753,7 +753,8 @@ took, and then announces that slot on the kernel command line.at most 128 MiB, and a read past the end returns zeros, while writes arerefused.- **Backend contract.** `blk::backend::DiskBackend` is the seam a disk- engine implements: `disk_info` once after open; `event_source` at every+ engine implements: `disk_info` once after open; `resize_grow` to a larger+ aligned size between requests, returning the new information; `event_source` at everyactivation, registered with the worker generation when it is `Some`;`submit(token, Request)` per parsed chain, answering `Done(CompletedRequest)`inline or `Pending`; `completions` on each `BackendReady` edge, drained@@ -779,8 +780,26 @@ took, and then announces that slot on the kernel command line.and at most 128 MiB, so a conforming guest splits a larger range; imagozeroes what the format cannot discard, and a qcow2 image frees theclusters without punching the host file.+- **Disk identity.** `block_id` is a nonempty host control ID, unique within+ the VM. The native adapter preserves the ID assigned by BoxLite. IDs do not+ affect attachment order or Linux device names. Invalid IDs fail VM creation+ before host resources or images are opened.+- **Online grow.** `vm.control().resize_disk("data", 2 << 30, timeout)`+ grows the writable disk with `block_id: "data"` to 2 GiB. Targets must be+ sector-aligned and at least the current capacity. A same-size request is a no-op.++ After growth succeeds, the device worker updates guest capacity and raises a+ configuration interrupt. A timeout ends the wait and the request can still complete.++ On Linux, preflight rejects a Raw target or qcow2 estimate above the shim's+ `RLIMIT_FSIZE` soft limit. The temporary qcow2 estimate adds 1 MiB per+ started GiB of target capacity.++ Fresh standalone samples from QEMU 8.2.2 (`preallocation=metadata`,+ 64 KiB clusters, 16-bit refcounts) added 384 KiB to file length at 1 GiB+ and 10.25 MiB at 64 GiB. Existing image layouts can require more space.- **Reset.** `Status=0` stops the worker slot, then `reset` deregisters the- backend source, fails the device with `Fatal` if a request is still in+ backend and control sources, fails the device with `Fatal` if a request is still inflight (no completion can arrive any more, and the guest may alreadyreuse that memory), flushes, and forgets the activation. The imagobackend finishes every request inline, so its table is always empty; adiff --git a/src/vmm/src/config.rs b/src/vmm/src/config.rsindex 201a59966..551f88b96 100644--- a/src/vmm/src/config.rs+++ b/src/vmm/src/config.rs@@ -31,6 +31,8 @@ pub enum DiskFormat {/// A disk image the guest sees as a virtio-blk device.#[derive(Clone, Debug, PartialEq, Eq)]pub struct DiskConfig {+ /// Nonempty, unique host control ID; independent of guest enumeration.+ pub block_id: String,/// The image file.pub path: PathBuf,/// The image format, stated rather than probed: the runtime always knows@@ -116,6 +118,15 @@ impl VmConfig {if self.disks.len() > MAX_DISKS {return Err(Error::InvalidDiskCount(self.disks.len()));}+ for (index, disk) in self.disks.iter().enumerate() {+ if disk.block_id.is_empty()+ || self.disks[..index]+ .iter()+ .any(|other| other.block_id == disk.block_id)+ {+ return Err(Error::InvalidDiskId(disk.block_id.clone()));+ }+ }if self.cmdline.len() >= MAX_CMDLINE_BYTES {return Err(Error::InvalidCommandLine("2048 bytes or longer"));}@@ -157,12 +168,18 @@ mod tests {#[test]fn rejects_more_disks_than_the_slots_and_names_can_take() {let disk = DiskConfig {+ block_id: "container".into(),path: "disk.raw".into(),format: DiskFormat::Raw,read_only: false,};VmConfig {- disks: vec![disk.clone(); MAX_DISKS],+ disks: (0..MAX_DISKS)+ .map(|index| DiskConfig {+ block_id: format!("disk-{index}"),+ ..disk.clone()+ })+ .collect(),..config(1, 1)}.validate()diff --git a/src/vmm/src/control.rs b/src/vmm/src/control.rsnew file mode 100644index 000000000..001360d3d--- /dev/null+++ b/src/vmm/src/control.rs@@ -0,0 +1,61 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++//! Host operations routed to devices by their configured IDs.++use std::{collections::HashMap, io, sync::Arc, time::Duration};++use crate::virtio::blk::control::{self, Controls, DiskSender};++/// Controls a VM from any thread without exposing its devices.+#[derive(Clone, Debug)]+pub struct VmControl {+ disks: Arc<HashMap<String, DiskSender>>,+}++impl VmControl {+ /// 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.+ ///+ /// Unknown IDs return `InvalidInput`. A request before device activation+ /// waits for activation. A timeout does not cancel an enqueued request;+ /// retrying the same absolute target is safe. A dropped device returns+ /// `BrokenPipe`.+ pub fn resize_disk(&self, block_id: &str, bytes: u64, timeout: Duration) -> io::Result<u64> {+ self.disks+ .get(block_id)+ .ok_or_else(|| {+ io::Error::new(io::ErrorKind::InvalidInput, format!("no disk {block_id:?}"))+ })?+ .grow(bytes, timeout)+ }+}++/// Mutable only while the VM's devices are being built.+#[derive(Default)]+pub(crate) struct ControlRegistry {+ disks: HashMap<String, DiskSender>,+}++impl ControlRegistry {+ pub(crate) fn register_disk(&mut self, block_id: &str) -> io::Result<Controls> {+ use std::collections::hash_map::Entry;++ let Entry::Vacant(entry) = self.disks.entry(block_id.to_owned()) else {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("duplicate disk ID {block_id:?}"),+ ));+ };+ let (sender, controls) = control::channel()?;+ entry.insert(sender);+ Ok(controls)+ }++ pub(crate) fn finish(self) -> VmControl {+ VmControl {+ disks: Arc::new(self.disks),+ }+ }+}diff --git a/src/vmm/src/devices/mod.rs b/src/vmm/src/devices/mod.rsindex f3c4688e1..91409f85e 100644--- a/src/vmm/src/devices/mod.rs+++ b/src/vmm/src/devices/mod.rs@@ -38,7 +38,7 @@ use crate::{#[cfg(all(target_os = "linux", target_arch = "x86_64"))]pub(crate) fn add_all(chipset: &mut ChipsetBuilder,- ctx: DeviceContext<'_>,+ mut ctx: DeviceContext<'_>,config: &mut VmConfig,console: ConsoleWriter,) -> Result<()> {@@ -48,7 +48,7 @@ pub(crate) fn add_all(let mut used = Vec::new();for (index, disk) in config.disks.iter().enumerate() {add_slot_device(&mut slots, &mut used, |slot| {- blk::add_disk(chipset, &ctx, disk, index, slot)+ blk::add_disk(chipset, &mut ctx, disk, index, slot)})?;}// The balloon follows the disks so it never renumbers them: the guestdiff --git a/src/vmm/src/error.rs b/src/vmm/src/error.rsindex 3a6c7ef07..ac4e60fa5 100644--- a/src/vmm/src/error.rs+++ b/src/vmm/src/error.rs@@ -40,8 +40,12 @@ pub enum Error {InvalidCommandLine(&'static str),/// More disks than `config::MAX_DISKS`.InvalidDiskCount(usize),+ /// A disk control ID is empty or duplicated.+ InvalidDiskId(String),/// Opening a disk image failed.OpenDisk { path: PathBuf, source: io::Error },+ /// Creating the channel that grows a disk failed.+ DiskControl(io::Error),/// Every virtio-mmio window and interrupt line is taken.VirtioSlotsExhausted,/// Devices claimed resources the chipset cannot give them.@@ -112,6 +116,8 @@ impl fmt::Display for Error {write!(f, "invalid kernel command line: {reason}")}Self::InvalidDiskCount(count) => write!(f, "too many disks: {count}"),+ Self::InvalidDiskId(id) => write!(f, "empty or duplicate disk ID: {id:?}"),+ Self::DiskControl(_) => f.write_str("failed to create a disk grow channel"),Self::OpenDisk { path, .. } => {write!(f, "failed to open the disk image {}", path.display())}@@ -163,6 +169,7 @@ impl error::Error for Error {| Self::GuestMemoryAddressLimit { .. }| Self::InvalidCommandLine(_)| Self::InvalidDiskCount(_)+ | Self::InvalidDiskId(_)| Self::VirtioSlotsExhausted| Self::ChipsetConflicts(_)| Self::LineNotArmed(_)@@ -175,6 +182,7 @@ impl error::Error for Error {| Self::HostMemoryCapability(source)| Self::AllocateMemory { source, .. }| Self::OpenDisk { source, .. }+ | Self::DiskControl(source)| Self::LoadKernel { source, .. }| Self::LoadInitramfs { source, .. }| Self::WriteBootData { source, .. }diff --git a/src/vmm/src/lib.rs b/src/vmm/src/lib.rsindex 3b8e8a96d..d8b7a0219 100644--- a/src/vmm/src/lib.rs+++ b/src/vmm/src/lib.rs@@ -27,6 +27,7 @@ mod bus;)]mod chipset;mod config;+mod control;#[cfg(target_arch = "x86_64")]mod cpu_features;#[cfg_attr(@@ -80,6 +81,7 @@ pub use chipset::{BusKind, Conflict};pub use config::{DiskConfig, DiskFormat, FsConfig, FsShareConfig, NetConfig, VmConfig, VsockConfig,};+pub use control::VmControl;pub use error::{Error, Result};pub use memory::ReclaimPolicy;pub use vm::{StopHandle, Vm, VmExit};diff --git a/src/vmm/src/virtio/blk/backend.rs b/src/vmm/src/virtio/blk/backend.rsindex cf557774d..38c77bdf9 100644--- a/src/vmm/src/virtio/blk/backend.rs+++ b/src/vmm/src/virtio/blk/backend.rs@@ -15,7 +15,7 @@ use std::io;use crate::virtio::EventSource;-/// What the device reports about a disk, fixed once the disk is open.+/// What the device reports about a disk; only a grow changes it.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) struct DiskInfo {/// The disk size in 512-byte sectors.@@ -76,9 +76,14 @@ pub(crate) enum SubmitOutcome {/// A disk behind the block device. The device serializes every call, so a/// backend adds no lock of its own.pub(crate) trait DiskBackend: Send {- /// The disk's fixed information.+ /// The disk's current information.fn disk_info(&self) -> DiskInfo;+ /// Grows the disk to `bytes`, a multiple of the sector size no smaller+ /// than the current capacity, and returns the new information. The device+ /// calls it between requests, never with one in flight.+ fn resize_grow(&mut self, bytes: u64) -> io::Result<DiskInfo>;+/// Submits `request` under `token`, which is unique among the requests/// in flight. A synchronous backend runs the request inline and returns/// [`SubmitOutcome::Done`]; an asynchronous one queues it and returnsdiff --git a/src/vmm/src/virtio/blk/control.rs b/src/vmm/src/virtio/blk/control.rsnew file mode 100644index 000000000..ad7d8d631--- /dev/null+++ b/src/vmm/src/virtio/blk/control.rs@@ -0,0 +1,140 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++//! Typed control requests for one disk while the VM runs.+//!+//! A [`DiskSender`] queues the request and rings a doorbell socket. The block+//! device registers the doorbell's other end with the workers at each+//! activation and applies queued requests on the worker thread, between+//! guest requests, so the handle never touches the device. A request sent+//! before the driver activates the device waits for that activation.++use std::{+ fmt,+ io::{self, Read, Write},+ os::unix::net::UnixStream,+ sync::{+ Arc,+ mpsc::{self, Receiver, RecvTimeoutError, Sender, SyncSender, TryRecvError},+ },+ time::Duration,+};++use crate::virtio::EventSource;++/// Sends control requests to one disk of a running VM from any thread.+#[derive(Clone)]+pub(crate) struct DiskSender {+ requests: Sender<BlockControlRequest>,+ bell: Arc<UnixStream>,+}++impl fmt::Debug for DiskSender {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("DiskSender").finish_non_exhaustive()+ }+}++impl DiskSender {+ /// Grows the disk to `bytes` and notifies the guest when capacity increases.+ /// `bytes` must be a multiple of 512 and no smaller than the current size;+ /// the current size succeeds without changing capacity or notifying, so+ /// a retry after a timeout is safe. A timeout leaves the request queued:+ /// the device still applies it when the guest activates it.+ pub(crate) fn grow(&self, bytes: u64, timeout: Duration) -> io::Result<u64> {+ self.request(timeout, |reply| BlockControlRequest::Resize {+ bytes,+ reply,+ })+ }++ /// The constructor pairs each operation with its own reply type; only the+ /// request travels to the worker. A timeout leaves that request queued.+ fn request<T>(+ &self,+ timeout: Duration,+ build: impl FnOnce(SyncSender<io::Result<T>>) -> BlockControlRequest,+ ) -> io::Result<T> {+ let (reply, done) = mpsc::sync_channel(1);+ self.requests.send(build(reply)).map_err(|_| gone())?;+ match (&*self.bell).write(&[1]) {+ // A full doorbell is already ringing.+ Err(error) if error.kind() != io::ErrorKind::WouldBlock => return Err(error),+ _ => {}+ }+ done.recv_timeout(timeout).map_err(|error| match error {+ RecvTimeoutError::Timeout => io::Error::new(+ io::ErrorKind::TimedOut,+ "the disk has not applied the control request yet",+ ),+ RecvTimeoutError::Disconnected => gone(),+ })?+ }+}++fn gone() -> io::Error {+ io::Error::new(io::ErrorKind::BrokenPipe, "the disk is gone")+}++/// Each operation carries the reply type its caller expects.+pub(crate) enum BlockControlRequest {+ Resize {+ bytes: u64,+ reply: SyncSender<io::Result<u64>>,+ },+}++/// The device's end: the queue and the doorbell it registers.+pub(crate) struct Controls {+ requests: Receiver<BlockControlRequest>,+ bell: UnixStream,+}++impl Controls {+ /// A source the workers poll for this activation; it reads ready once a+ /// handle rings, including a ring from before the registration.+ pub(crate) fn event_source(&self) -> io::Result<Box<dyn EventSource>> {+ let bell = self.bell.try_clone()?;+ Ok(Box::new(Bell(mio::net::UnixStream::from_std(bell))))+ }++ /// Silences the doorbell, then returns every queued request. Reading the+ /// doorbell first keeps a request queued after this call ringing again.+ pub(crate) fn take(&mut self) -> Vec<BlockControlRequest> {+ let mut buf = [0u8; 64];+ while matches!((&self.bell).read(&mut buf), Ok(read) if read > 0) {}+ let mut taken = Vec::new();+ loop {+ match self.requests.try_recv() {+ Ok(request) => taken.push(request),+ Err(TryRecvError::Empty | TryRecvError::Disconnected) => return taken,+ }+ }+ }+}++/// Creates one disk's handle and the device's end.+pub(crate) fn channel() -> io::Result<(DiskSender, Controls)> {+ let (ring, bell) = UnixStream::pair()?;+ ring.set_nonblocking(true)?;+ bell.set_nonblocking(true)?;+ let (requests, queue) = mpsc::channel();+ Ok((+ DiskSender {+ requests,+ bell: Arc::new(ring),+ },+ Controls {+ requests: queue,+ bell,+ },+ ))+}++struct Bell(mio::net::UnixStream);++impl EventSource for Bell {+ fn as_source(&mut self) -> &mut dyn mio::event::Source {+ &mut self.0+ }+}diff --git a/src/vmm/src/virtio/blk/device.rs b/src/vmm/src/virtio/blk/device.rsindex 67d2f44f2..63fb10fbd 100644--- a/src/vmm/src/virtio/blk/device.rs+++ b/src/vmm/src/virtio/blk/device.rs@@ -4,11 +4,14 @@//! The virtio block device: the [`VirtioDevice`] contract over one request//! queue and a [`DiskBackend`].+use std::io;+use super::{- DEVICE_ID, QUEUE_MAXIMUM, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_RO,- VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_S_OK,+ DEVICE_ID, QUEUE_MAXIMUM, SECTOR_SIZE, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_FLUSH,+ VIRTIO_BLK_F_RO, VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_S_OK,backend::{CompletedRequest, DiskBackend, DiskInfo, RequestKind, SubmitOutcome},config::BlkConfig,+ control::{BlockControlRequest, Controls},inflight::Inflight,request::{self, Decoded, WriteTargets},};@@ -29,6 +32,7 @@ pub(crate) struct VirtioBlk {config: BlkConfig,disk_info: DiskInfo,backend: Box<dyn DiskBackend>,+ controls: Controls,active: Option<ActiveState>,}@@ -37,18 +41,21 @@ struct ActiveState {ctx: ActivationContext,/// The backend's registered source, when it has one.source: Option<SourceId>,+ /// The registered doorbell of [`Controls`].+ control: SourceId,inflight: Inflight,/// Scratch for `completions`, kept so no event allocates.completed: Vec<CompletedRequest>,}impl VirtioBlk {- /// Builds the device over an open backend.+ /// Builds the device over an open backend; `controls` brings its grow+ /// requests.////// A synchronous backend runs every request inside `on_event`, so one/// kick does at most the queue size times `MAX_REQUEST_BYTES` of I/O on/// the shared worker thread before another device runs.- pub(crate) fn new(backend: Box<dyn DiskBackend>) -> Self {+ pub(crate) fn new(backend: Box<dyn DiskBackend>, controls: Controls) -> Self {let disk_info = backend.disk_info();let mut features = VIRTIO_F_VERSION_1 | VIRTIO_BLK_F_SEG_MAX | VIRTIO_F_INDIRECT_DESC;if disk_info.read_only {@@ -69,10 +76,51 @@ impl VirtioBlk {config: BlkConfig::new(&disk_info),disk_info,backend,+ controls,active: None,}}+ /// Applies queued device control requests on the worker thread.+ fn apply_controls(&mut self) {+ for request in self.controls.take() {+ match request {+ BlockControlRequest::Resize { bytes, reply } => {+ let result = self.grow(bytes);+ // A caller may have timed out; the admitted operation still completes.+ let _ = reply.try_send(result);+ }+ }+ }+ }++ /// Actual growth updates configuration space before raising the config+ /// interrupt and advancing its generation. The current size is a no-op.+ fn grow(&mut self, bytes: u64) -> io::Result<u64> {+ let current = self.disk_info.capacity_sectors * SECTOR_SIZE;+ if self.disk_info.read_only {+ return Err(io::Error::new(+ io::ErrorKind::PermissionDenied,+ "the disk is read-only",+ ));+ }+ if !bytes.is_multiple_of(SECTOR_SIZE) || bytes < current {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("a disk of {current} bytes grows only to a larger multiple of 512"),+ ));+ }+ if bytes == current {+ return Ok(current);+ }+ self.disk_info = self.backend.resize_grow(bytes)?;+ self.config = BlkConfig::new(&self.disk_info);+ if let Some(active) = &self.active {+ active.ctx.interrupt.raise_config();+ }+ Ok(self.disk_info.capacity_sectors * SECTOR_SIZE)+ }+/// Drains the request queue: every chain is parsed and submitted, and a/// chain the backend keeps is deferred until its completion arrives.fn process_queue(&mut self) -> Result<(), DeviceError> {@@ -199,9 +247,24 @@ impl VirtioDevice for VirtioBlk {})?),None => None,};+ let control = self+ .controls+ .event_source()+ .and_then(|bell| ctx.events.register(bell).map_err(io::Error::other));+ let control = match control {+ Ok(id) => id,+ Err(error) => {+ tracing::warn!(%error, "the block control source was not registered");+ if let Some(id) = source {+ ctx.events.deregister(id);+ }+ return Err(DeviceError::NeedsReset("block control source"));+ }+ };self.active = Some(ActiveState {ctx,source,+ control,inflight: Inflight::default(),completed: Vec::new(),});@@ -214,6 +277,7 @@ impl VirtioDevice for VirtioBlk {if let Some(id) = active.source {active.ctx.events.deregister(id);}+ active.ctx.events.deregister(active.control);// The worker is stopped, so no completion can arrive, and the// guest may reuse the memory a request in flight would write: a// backend that still holds one cannot continue. A bounded wait@@ -231,6 +295,15 @@ impl VirtioDevice for VirtioBlk {match event {DeviceEvent::QueueKick(0) => self.process_queue(),DeviceEvent::QueueKick(_) => Err(DeviceError::Unsupported("block queue index")),+ DeviceEvent::BackendReady(id)+ if self+ .active+ .as_ref()+ .is_some_and(|active| active.control == id) =>+ {+ self.apply_controls();+ Ok(())+ }DeviceEvent::BackendReady(id) => self.backend_ready(id),}}diff --git a/src/vmm/src/virtio/blk/imago.rs b/src/vmm/src/virtio/blk/imago.rsindex 22f12f12f..d202eec94 100644--- a/src/vmm/src/virtio/blk/imago.rs+++ b/src/vmm/src/virtio/blk/imago.rs@@ -7,8 +7,8 @@use std::{io, path::Path};use imago::{- DynStorage, FormatAccess, FormatDriverBuilder, PermissiveImplicitOpenGate, qcow2::Qcow2,- raw::Raw,+ DynStorage, FormatAccess, FormatDriverBuilder, PermissiveImplicitOpenGate,+ format::PreallocateMode, qcow2::Qcow2, raw::Raw,};use super::{@@ -85,6 +85,27 @@ impl DiskBackend for ImagoBackend {})}+ fn resize_grow(&mut self, bytes: u64) -> io::Result<DiskInfo> {+ #[cfg(target_os = "linux")]+ match self.image.inner().format() {+ imago::format::Format::Qcow2 => {+ // Temporary allowance based on measurements of fresh qcow2+ // images. Existing cluster layouts can require more space.+ const GIB: u64 = 1 << 30;+ const METADATA_BYTES_PER_GIB: u64 = 1 << 20;+ let metadata_reserve = bytes.div_ceil(GIB) * METADATA_BYTES_PER_GIB;+ check_file_size_limit(bytes, metadata_reserve)?;+ }+ imago::format::Format::Raw => check_file_size_limit(bytes, 0)?,+ _ => {}+ }+ // `None` only grows metadata and the file length: the new range reads+ // as zeroes because it maps nothing, even past a shorter backing file.+ self.image.resize_grow(bytes, PreallocateMode::None)?;+ self.disk_info.capacity_sectors = self.image.size() >> SECTOR_SHIFT;+ Ok(self.disk_info)+ }+fn completions(&mut self, _out: &mut Vec<CompletedRequest>) {}fn event_source(&mut self) -> Option<Box<dyn EventSource>> {@@ -96,3 +117,28 @@ impl DiskBackend for ImagoBackend {self.image.sync()}}++#[cfg(target_os = "linux")]+fn check_file_size_limit(bytes: u64, metadata_reserve: u64) -> io::Result<()> {+ let mut limit = libc::rlimit64 {+ rlim_cur: 0,+ rlim_max: 0,+ };+ // SAFETY: getrlimit64 writes the calling process's limits to this struct.+ if unsafe { libc::getrlimit64(libc::RLIMIT_FSIZE, &mut limit) } != 0 {+ return Err(io::Error::last_os_error());+ }+ let soft_limit = limit.rlim_cur;+ let required = u128::from(bytes) + u128::from(metadata_reserve);+ if soft_limit != u64::MAX && required > u128::from(soft_limit) {+ return Err(io::Error::new(+ io::ErrorKind::FileTooLarge,+ format!(+ "Resize to {bytes} bytes needs an estimated host file size of {required} bytes \+ (including {metadata_reserve} bytes for metadata), above the RLIMIT_FSIZE \+ soft limit of {soft_limit} bytes"+ ),+ ));+ }+ Ok(())+}diff --git a/src/vmm/src/virtio/blk/mod.rs b/src/vmm/src/virtio/blk/mod.rsindex 28a5e3d37..1d1f2eafb 100644--- a/src/vmm/src/virtio/blk/mod.rs+++ b/src/vmm/src/virtio/blk/mod.rs@@ -24,6 +24,7 @@ use crate::{pub(crate) mod backend;pub(crate) mod config;+pub(crate) mod control;pub(crate) mod device;pub(crate) mod imago;pub(crate) mod inflight;@@ -46,14 +47,15 @@ const CHIPSET_NAMES: [&str; MAX_DISKS] = [];/// Adds `disk` as a virtio-blk device behind a virtio-mmio transport in-/// `slot`, run by the VM's workers. `index` selects the chipset name.+/// `slot`, run by the VM's workers. `index` selects the chipset name;+/// the disk's configured ID registers its private control channel.#[cfg_attr(not(all(target_os = "linux", target_arch = "x86_64")),expect(dead_code, reason = "Only the Linux x86_64 Vm::new adds disks yet."))]pub(crate) fn add_disk(chipset: &mut ChipsetBuilder,- ctx: &DeviceContext<'_>,+ ctx: &mut DeviceContext<'_>,disk: &DiskConfig,index: usize,slot: Slot,@@ -68,8 +70,12 @@ pub(crate) fn add_disk(source,}})?;+ let controls = ctx+ .controls+ .register_disk(&disk.block_id)+ .map_err(Error::DiskControl)?;let device: Arc<Mutex<dyn VirtioDevice>> =- Arc::new(Mutex::new(VirtioBlk::new(Box::new(backend))));+ Arc::new(Mutex::new(VirtioBlk::new(Box::new(backend), controls)));mmio::add_device(chipset, ctx, name, slot, device)}diff --git a/src/vmm/src/virtio/mod.rs b/src/vmm/src/virtio/mod.rsindex fc5ec211e..a3cc0e6e5 100644--- a/src/vmm/src/virtio/mod.rs+++ b/src/vmm/src/virtio/mod.rs@@ -92,6 +92,8 @@ pub(crate) struct DeviceContext<'a> {pub(crate) memory: &'a Arc<GuestMemoryMmap>,/// The VM's virtio workers.pub(crate) workers: &'a VirtioWorkers,+ /// Device control channels registered during VM construction.+ pub(crate) controls: &'a mut crate::control::ControlRegistry,}/// What the workers ask a device to do.diff --git a/src/vmm/src/vm.rs b/src/vmm/src/vm.rsindex 3c20be9c9..7933d2032 100644--- a/src/vmm/src/vm.rs+++ b/src/vmm/src/vm.rs@@ -11,6 +11,7 @@ use boxlite_hypervisor::Vm as HostVm;use crate::{chipset::{Chipset, ChipsetBuilder},config::VmConfig,+ control::{ControlRegistry, VmControl},devices::console::ConsoleWorker,error::{Error, Result},events::{Event, EventLoop, EventSender},@@ -73,6 +74,7 @@ pub struct Vm<H: HostVm> {/// finishes it once every vCPU has stopped. The lock only makes `Vm`/// `Sync`; `run` reaches it through `&mut self`.console: Mutex<Option<ConsoleWorker>>,+ control: VmControl,events: Mutex<EventLoop>,sender: EventSender,boot_regs: BootRegisters,@@ -196,11 +198,13 @@ impl<H: HostVm> Vm<H> {// early return leaves nothing running.let workers = create_workers(sender.clone()).map_err(Error::VirtioWorker)?;let mut chipset = ChipsetBuilder::new(host_vm.clone(), sender.clone());+ let mut controls = ControlRegistry::default();devices(&mut chipset,DeviceContext {memory: ram.memory(),workers: &workers,+ controls: &mut controls,},&mut config,)?;@@ -221,6 +225,7 @@ impl<H: HostVm> Vm<H> {chipset: Some(chipset),workers: Some(workers),console: Mutex::new(None),+ control: controls.finish(),events: Mutex::new(events),sender,boot_regs: BootRegisters::default(),@@ -239,6 +244,11 @@ impl<H: HostVm> Vm<H> {pub fn stop_handle(&self) -> StopHandle {StopHandle(self.sender.clone())}++ /// Controls the VM from another thread, addressing disks by their configured IDs.+ pub fn control(&self) -> VmControl {+ self.control.clone()+ }}#[cfg(target_arch = "x86_64")]@@ -379,3 +389,7 @@ impl<H: HostVm> Drop for Vm<H> {#[cfg(test)]#[path = "../tests/vm/mod.rs"]mod tests;++#[cfg(all(test, target_arch = "x86_64"))]+#[path = "../tests/control/mod.rs"]+mod control_tests;diff --git a/src/vmm/tests/boot/disk_grow_init.c b/src/vmm/tests/boot/disk_grow_init.cnew file mode 100644index 000000000..73f78c521--- /dev/null+++ b/src/vmm/tests/boot/disk_grow_init.c@@ -0,0 +1,60 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++/* Freestanding init for the online disk grow test: it prints the size of vda+ * in sectors, waits until the host grows the disk, prints the new size, and+ * reboots. The host reads both lines from the console. */+typedef unsigned long word;+static long call(long n, long a, long b, long c, long d, long e, long f) {+ register long r10 __asm__("r10") = d;+ register long r8 __asm__("r8") = e;+ register long r9 __asm__("r9") = f;+ long result;+ __asm__ volatile("syscall" : "=a"(result) : "a"(n), "D"(a), "S"(b), "d"(c),+ "r"(r10), "r"(r8), "r"(r9) : "rcx", "r11", "memory");+ return result;+}+static void print(const char *text, word count) {+ call(1, 1, (long)text, count, 0, 0, 0);+}+__attribute__((noreturn)) static void finish(const char *line, word count) {+ print(line, count);+ call(16, 1, 0x5409, 1, 0, 0, 0); /* drain tty */+ call(169, 0xfee1dead, 0x28121969, 0x01234567, 0, 0, 0);+ for (;;) call(34, 0, 0, 0, 0, 0, 0);+}+/* Reads /sys/block/vda/size into text and returns its length. */+static word size(char *text) {+ long fd = call(2, (long)"/sys/block/vda/size", 0, 0, 0, 0, 0);+ if (fd < 0) finish("GROW_FAIL open\n", 15);+ long count = call(0, fd, (long)text, 31, 0, 0, 0);+ call(3, fd, 0, 0, 0, 0, 0);+ if (count <= 0) finish("GROW_FAIL read\n", 15);+ return (word)count;+}+static int same(const char *a, const char *b, word count) {+ for (word i = 0; i < count; i++)+ if (a[i] != b[i]) return 0;+ return 1;+}+__attribute__((used,noreturn)) void run(void) {+ char before[32], after[32];+ call(83, (long)"/sys", 0755, 0, 0, 0, 0);+ if (call(165, (long)"sysfs", (long)"/sys", (long)"sysfs", 0, 0, 0) < 0)+ finish("GROW_FAIL mount\n", 16);+ word first = size(before);+ print("GROW_BEFORE ", 12);+ print(before, first);+ word time[2] = {0, 20000000}; /* 20 ms */+ for (int i = 0; i < 1000; i++) { /* at most 20 s */+ word now = size(after);+ if (now != first || !same(before, after, now)) {+ print("GROW_AFTER ", 11);+ print(after, now);+ finish("GROW_OK\n", 8);+ }+ call(35, (long)time, 0, 0, 0, 0, 0);+ }+ finish("GROW_FAIL timeout\n", 18);+}+__asm__(".global _start\n_start:\n xor %rbp,%rbp\n and $-16,%rsp\n call run\n");diff --git a/src/vmm/tests/boot/virtio_blk.rs b/src/vmm/tests/boot/virtio_blk.rsindex 4809d4353..f7a725e6e 100644--- a/src/vmm/tests/boot/virtio_blk.rs+++ b/src/vmm/tests/boot/virtio_blk.rs@@ -14,6 +14,7 @@ use std::{atomic::{AtomicUsize, Ordering},},thread,+ time::{Duration, Instant},};use imago::{@@ -38,6 +39,7 @@ use crate::{blk::{VIRTIO_BLK_S_OK,backend::{DiskBackend, Request, RequestKind, SubmitOutcome},+ control,device::VirtioBlk,imago::ImagoBackend,},@@ -318,7 +320,7 @@ fn boots_linux_and_drives_virtio_blk_through_the_workers() {let observed = Observed::default();let backend = ImagoBackend::open(&image.0, DiskFormat::Raw, false).expect("open the image");let device: Arc<Mutex<dyn VirtioDevice>> = Arc::new(Mutex::new(Recording {- inner: VirtioBlk::new(Box::new(backend)),+ inner: VirtioBlk::new(Box::new(backend), control::channel().unwrap().1),observed: observed.clone(),}));let edges = Arc::new(Mutex::new(Vec::new()));@@ -397,6 +399,7 @@ fn boots_linux_with_a_raw_virtio_disk_through_the_public_api() {let log = SerialLog::default();let mut config = linux_config(1, CONSOLE_CMDLINE, Some(initramfs.0.clone()));config.disks = vec![DiskConfig {+ block_id: "container".into(),path: image.0.clone(),format: DiskFormat::Raw,read_only: false,@@ -430,6 +433,7 @@ fn boots_linux_with_a_qcow2_virtio_disk_over_a_backing_file() {let log = SerialLog::default();let mut config = linux_config(1, CONSOLE_CMDLINE, Some(initramfs.0.clone()));config.disks = vec![DiskConfig {+ block_id: "container".into(),path: image.0.clone(),format: DiskFormat::Qcow2,read_only: false,@@ -481,3 +485,71 @@ fn boots_linux_with_a_qcow2_virtio_disk_over_a_backing_file() {);eprintln!("blk public API, qcow2: {elapsed:?}");}++/// The host grows a qcow2 disk through `VmControl::resize_disk` while the guest+/// runs; the guest sees the new size in sysfs without a restart.+#[test]+#[ignore = "requires Linux x86_64 KVM, VMM_KERNEL and VMM_DISK_GROW_INIT"]+fn the_guest_sees_a_disk_grown_while_it_runs() {+ let init = std::fs::read(+ std::env::var_os("VMM_DISK_GROW_INIT")+ .expect("use make test:integration:vmm:linux for the guest init"),+ )+ .unwrap();+ let backing = raw_image("grow-backing.raw");+ let image = qcow2_over(&backing.0, "grow-overlay.qcow2");+ let initramfs = TempFile::new("grow.cpio", &newc_archive("init", &init));+ let log = SerialLog::default();+ let mut config = linux_config(1, CONSOLE_CMDLINE, Some(initramfs.0.clone()));+ config.disks = vec![DiskConfig {+ block_id: "container".into(),+ path: image.0.clone(),+ format: DiskFormat::Qcow2,+ read_only: false,+ }];+ let mut vm = crate::Vm::new(config, Box::new(log.clone())).expect("create the VM");+ let control = vm.control();+ assert_eq!(+ control+ .resize_disk("missing", 512, Duration::ZERO)+ .unwrap_err()+ .kind(),+ std::io::ErrorKind::InvalidInput+ );+ let grown_bytes = 2 * IMAGE_SECTORS * 512;+ let grower = {+ let log = log.clone();+ thread::spawn(move || {+ let deadline = Instant::now() + BOOT_TIMEOUT;+ while !log.text().contains("GROW_BEFORE") {+ if Instant::now() > deadline {+ return None;+ }+ thread::sleep(Duration::from_millis(10));+ }+ Some(control.resize_disk("container", grown_bytes, Duration::from_secs(5)))+ })+ };++ let (exit, elapsed) = run_with_watchdog(&mut vm, BOOT_TIMEOUT);+ let grown = grower.join().unwrap();+ drop(vm);++ let log = log.text();+ assert!(+ matches!(exit, Ok(VmExit::GuestReset)),+ "{exit:?} after {elapsed:?}; log:\n{log}"+ );+ let grown = grown.expect("the guest never printed its size");+ assert_eq!(grown.unwrap(), grown_bytes);+ assert!(+ log.contains(&format!("GROW_BEFORE {IMAGE_SECTORS}")),+ "the guest saw another starting size:\n{log}"+ );+ assert!(+ log.contains(&format!("GROW_AFTER {}", 2 * IMAGE_SECTORS)),+ "the guest did not see the grown size:\n{log}"+ );+ assert!(log.contains("GROW_OK"), "{log}");+ eprintln!("blk online grow: {elapsed:?}");+}diff --git a/src/vmm/tests/control/mod.rs b/src/vmm/tests/control/mod.rsnew file mode 100644index 000000000..14885c945--- /dev/null+++ b/src/vmm/tests/control/mod.rs@@ -0,0 +1,184 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++//! ID routing through VM construction, real block devices and worker events.++use std::{cell::Cell, fs::File, io, time::Duration};++use boxlite_hypervisor::VcpuExit;++use super::{BootRegisters, Vm};+use crate::{+ DiskConfig, DiskFormat, VmConfig,+ error::Error,+ mock_vm::MockVm,+ virtio::{blk, mmio::Slots},+};++const IMAGE_BYTES: u64 = 1 << 20;+const BASE: u64 = 0xd000_0000;+const TIMEOUT: Duration = Duration::from_secs(5);++fn config(disks: Vec<DiskConfig>) -> VmConfig {+ VmConfig {+ vcpu_count: 1,+ memory_mib: 2,+ kernel: "unused".into(),+ cmdline: String::new(),+ initramfs: None,+ disks,+ filesystem: None,+ vsock: None,+ network: None,+ virtio_console: false,+ }+}++fn disk(id: &str, path: std::path::PathBuf) -> DiskConfig {+ DiskConfig {+ block_id: id.into(),+ path,+ format: DiskFormat::Raw,+ read_only: false,+ }+}++fn write(vm: &Vm<MockVm>, base: u64, offset: u64, value: u32) {+ assert!(+ vm.chipset+ .as_ref()+ .unwrap()+ .dispatch(VcpuExit::MmioWrite {+ guest_addr: base + offset,+ bytes: &value.to_le_bytes(),+ })+ .is_none()+ );+}++fn read(vm: &Vm<MockVm>, base: u64, offset: u64) -> u32 {+ let mut bytes = [0; 4];+ assert!(+ vm.chipset+ .as_ref()+ .unwrap()+ .dispatch(VcpuExit::MmioRead {+ guest_addr: base + offset,+ bytes: &mut bytes,+ })+ .is_none()+ );+ u32::from_le_bytes(bytes)+}++fn activate(vm: &Vm<MockVm>, index: usize) {+ let base = BASE + index as u64 * 0x1000;+ let queue_base = 0x10000 * (index as u32 + 1);+ // Negotiate VERSION_1 and install an empty queue in zeroed guest RAM.+ for (offset, value) in [+ (0x070, 1),+ (0x070, 3),+ (0x024, 1),+ (0x020, 1),+ (0x070, 0xb),+ (0x030, 0),+ (0x038, 16),+ (0x080, queue_base),+ (0x090, queue_base + 0x1000),+ (0x0a0, queue_base + 0x2000),+ (0x044, 1),+ (0x070, 0xf),+ ] {+ write(vm, base, offset, value);+ }+ assert_eq!(read(vm, base, 0x070), 0xf);+}++#[test]+fn block_id_routes_growth_independently_of_disk_order() {+ for ids in [["archive", "data"], ["data", "archive"]] {+ let dir = tempfile::tempdir().unwrap();+ let disks: Vec<_> = ids+ .iter()+ .map(|id| {+ let path = dir.path().join(format!("{id}.raw"));+ File::create(&path).unwrap().set_len(IMAGE_BYTES).unwrap();+ disk(id, path)+ })+ .collect();+ let vm = Vm::with_devices(+ config(disks.clone()),+ || Ok(MockVm::new()),+ |_, _| Ok(BootRegisters::default()),+ |chipset, mut ctx, config| {+ let mut slots = Slots::new();+ for (index, disk) in config.disks.iter().enumerate() {+ blk::add_disk(chipset, &mut ctx, disk, index, slots.take()?)?;+ }+ Ok(())+ },+ )+ .unwrap();+ for index in 0..2 {+ activate(&vm, index);+ }+ let control = vm.control();+ assert_eq!(+ control+ .resize_disk("missing", 2 * IMAGE_BYTES, TIMEOUT)+ .unwrap_err()+ .kind(),+ io::ErrorKind::InvalidInput+ );+ assert_eq!(+ control+ .resize_disk("data", 2 * IMAGE_BYTES, TIMEOUT)+ .unwrap(),+ 2 * IMAGE_BYTES+ );+ for (index, disk) in disks.iter().enumerate() {+ let target = disk.block_id == "data";+ let expected = if target { 2 * IMAGE_BYTES } else { IMAGE_BYTES };+ assert_eq!(std::fs::metadata(&disk.path).unwrap().len(), expected);+ let base = BASE + index as u64 * 0x1000;+ assert_eq!(u64::from(read(&vm, base, 0x100)), expected / 512);+ assert_eq!(read(&vm, base, 0x104), 0);+ assert_eq!(read(&vm, base, 0x0fc), u32::from(target));+ }+ assert_eq!(+ control+ .clone()+ .resize_disk("data", 2 * IMAGE_BYTES, TIMEOUT)+ .unwrap(),+ 2 * IMAGE_BYTES+ );+ drop(vm);+ assert_eq!(+ control+ .resize_disk("data", 3 * IMAGE_BYTES, TIMEOUT)+ .unwrap_err()+ .kind(),+ io::ErrorKind::BrokenPipe+ );+ }+}++#[test]+fn invalid_block_ids_fail_before_host_creation() {+ for ids in [vec![""], vec!["same", "same"]] {+ let called = Cell::new(false);+ let result = Vm::with_backend(+ config(ids.iter().map(|id| disk(id, "unused".into())).collect()),+ || {+ called.set(true);+ Ok(MockVm::new())+ },+ |_, _| Ok(BootRegisters::default()),+ |_, _| Ok(()),+ );+ let error = result.unwrap_err();+ assert!(matches!(&error, Error::InvalidDiskId(id) if id == ids[0]));+ assert!(error.to_string().contains(ids[0]));+ assert!(!called.get());+ }+}diff --git a/src/vmm/tests/virtio/blk/mod.rs b/src/vmm/tests/virtio/blk/mod.rsindex ffd70290b..fd1e3c6b0 100644--- a/src/vmm/tests/virtio/blk/mod.rs+++ b/src/vmm/tests/virtio/blk/mod.rs@@ -14,6 +14,8 @@ use std::{Arc, Mutex,atomic::{AtomicU8, AtomicUsize, Ordering},},+ thread,+ time::Duration,};use imago::{@@ -32,6 +34,7 @@ use super::{VIRTIO_BLK_S_UNSUPP, VIRTIO_BLK_T_DISCARD, VIRTIO_BLK_T_FLUSH, VIRTIO_BLK_T_IN,VIRTIO_BLK_T_OUT,backend::{CompletedRequest, DiskBackend, DiskInfo, Request, RequestKind, SubmitOutcome},+ control::{self, DiskSender},device::VirtioBlk,imago::ImagoBackend,};@@ -108,6 +111,7 @@ fn file_at(path: &Path, offset: u64, len: usize) -> Vec<u8> {#[derive(Default)]struct TestInterrupt {raised: AtomicUsize,+ config_raised: AtomicUsize,status: AtomicU8,}@@ -128,7 +132,9 @@ impl VirtioInterrupt for TestInterrupt {0}- fn raise_config(&self) {}+ fn raise_config(&self) {+ self.config_raised.fetch_add(1, Ordering::SeqCst);+ }fn device_status(&self) -> u8 {0@@ -222,6 +228,11 @@ impl DiskBackend for FakeBackend {self.disk_info}+ fn resize_grow(&mut self, bytes: u64) -> io::Result<DiskInfo> {+ self.disk_info.capacity_sectors = bytes / SECTOR_SIZE;+ Ok(self.disk_info)+ }+fn submit(&mut self, token: u32, request: Request) -> SubmitOutcome {self.state.lock().unwrap().pending.push((token, request));SubmitOutcome::Pending@@ -256,6 +267,7 @@ struct Fixture {interrupt: Arc<TestInterrupt>,registrar: Arc<TestRegistrar>,fake: Option<Arc<Mutex<FakeState>>>,+ handle: DiskSender,}impl Fixture {@@ -298,7 +310,8 @@ impl Fixture {backend: Box<dyn DiskBackend>,fake: Option<Arc<Mutex<FakeState>>>,) -> Self {- let mut blk = VirtioBlk::new(backend);+ let (handle, controls) = control::channel().unwrap();+ let mut blk = VirtioBlk::new(backend, controls);let features = blk.spec().features;blk.set_features(features).unwrap();let leaked: &'static GuestMemoryMmap = Box::leak(Box::new(@@ -314,6 +327,7 @@ impl Fixture {interrupt: Arc::new(TestInterrupt::default()),registrar: Arc::new(TestRegistrar::default()),fake,+ handle,};fixture.activate().unwrap();fixture@@ -510,6 +524,31 @@ impl Fixture {self.blk.read_config(offset, &mut data).unwrap();data}++ /// The capacity in sectors that the configuration space reports.+ fn capacity(&mut self) -> u64 {+ u64::from_le_bytes(self.config_bytes(0, 8).try_into().unwrap())+ }++ fn config_raised(&self) -> usize {+ self.interrupt.config_raised.load(Ordering::SeqCst)+ }++ /// Grows the disk through its handle on another thread while this one+ /// plays the worker: it delivers the doorbell, which the device+ /// registered last, until the handle has its answer.+ fn grow(&mut self, bytes: u64) -> io::Result<u64> {+ let control = SourceId(self.registrar.registered.load(Ordering::SeqCst) as u32 - 1);+ let handle = self.handle.clone();+ let caller = thread::spawn(move || handle.grow(bytes, Duration::from_secs(10)));+ while !caller.is_finished() {+ self.blk+ .on_event(DeviceEvent::BackendReady(control))+ .unwrap();+ thread::sleep(Duration::from_millis(1));+ }+ caller.join().unwrap()+ }}#[test]@@ -815,7 +854,7 @@ fn an_empty_kick_does_not_interrupt() {#[test]fn a_pending_request_completes_when_the_backend_signals() {let mut fixture = Fixture::pending();- assert_eq!(fixture.registrar.registered.load(Ordering::SeqCst), 1);+ assert_eq!(fixture.registrar.registered.load(Ordering::SeqCst), 2);fixture.read(0, 512).unwrap();assert_eq!(fixture.used().0, 0, "a pending chain has no used entry");assert_eq!(fixture.raised(), 0);@@ -892,7 +931,7 @@ fn reset_fails_the_device_while_a_request_is_in_flight() {assert_eq!(fixture.fake().flushes, 0);assert_eq!(*fixture.registrar.deregistered.lock().unwrap(),- vec![SourceId(0)]+ vec![SourceId(0), SourceId(1)]);}@@ -903,14 +942,14 @@ fn reset_with_nothing_in_flight_flushes_and_a_rebind_registers_a_fresh_source()assert_eq!(fixture.fake().flushes, 1);assert_eq!(*fixture.registrar.deregistered.lock().unwrap(),- vec![SourceId(0)]+ vec![SourceId(0), SourceId(1)]);fixture.fresh_rings();let features = fixture.blk.spec().features;fixture.blk.set_features(features).unwrap();assert!(fixture.activate().is_ok());- assert_eq!(fixture.registrar.registered.load(Ordering::SeqCst), 2);+ assert_eq!(fixture.registrar.registered.load(Ordering::SeqCst), 4);fixture.read(0, 512).unwrap();let token = fixture.fake().pending[0].0;fixture.fake().complete(token, VIRTIO_BLK_S_OK, 0xCD);@@ -921,7 +960,7 @@ fn reset_with_nothing_in_flight_flushes_and_a_rebind_registers_a_fresh_source()assert_eq!(fixture.used().0, 0, "the old generation's id is stale");fixture.blk- .on_event(DeviceEvent::BackendReady(SourceId(1)))+ .on_event(DeviceEvent::BackendReady(SourceId(2))).unwrap();assert_eq!(fixture.used(), (1, vec![(0, 513)]));assert_eq!(fixture.data(512), vec![0xCD; 512]);@@ -971,3 +1010,173 @@ fn check_shutdown_flush(flush_error: Option<io::ErrorKind>) {}assert_eq!(state.lock().unwrap().flushes, 1);}++#[test]+fn a_grow_reaches_the_configuration_and_the_data_path_and_notifies_once() {+ let mut fixture = Fixture::qcow2();+ let old = IMAGE_BYTES / SECTOR_SIZE;+ // Past the old end, the guest is refused before the grow.+ fixture.read(old, 512).unwrap();+ assert_eq!(fixture.status(), VIRTIO_BLK_S_IOERR);++ assert_eq!(fixture.grow(2 * IMAGE_BYTES).unwrap(), 2 * IMAGE_BYTES);+ assert_eq!(fixture.capacity(), 2 * old);+ assert_eq!(fixture.config_raised(), 1);++ fixture.write(old, &[0x5A; 512]).unwrap();+ assert_eq!(fixture.status(), VIRTIO_BLK_S_OK);+ fixture.read(old, 512).unwrap();+ assert_eq!(fixture.status(), VIRTIO_BLK_S_OK);+ assert_eq!(fixture.data(512), vec![0x5A; 512]);+ // The grown range of a qcow2 overlay reads as zeroes, not as stale data.+ fixture.read(old + 1, 512).unwrap();+ assert_eq!(fixture.data(512), vec![0u8; 512]);+}++#[test]+fn a_raw_grow_extends_the_file() {+ let mut fixture = Fixture::raw(false);+ assert_eq!(fixture.grow(4 * IMAGE_BYTES).unwrap(), 4 * IMAGE_BYTES);+ assert_eq!(+ std::fs::metadata(&fixture.path).unwrap().len(),+ 4 * IMAGE_BYTES+ );+ assert_eq!(fixture.capacity(), 4 * IMAGE_BYTES / SECTOR_SIZE);+}++#[cfg(target_os = "linux")]+#[test]+fn grow_checks_the_process_file_size_limit() {+ const CHILD: &str = "BOXLITE_GROW_FILE_SIZE_LIMIT_CHILD";+ if std::env::var_os(CHILD).is_none() {+ let thread = thread::current();+ let status = std::process::Command::new(std::env::current_exe().unwrap())+ .args(["--exact", thread.name().unwrap(), "--nocapture"])+ .env(CHILD, "1")+ .status()+ .unwrap();+ assert!(status.success(), "isolated file-size test failed: {status}");+ return;+ }++ // SAFETY: Only the isolated child changes its signal disposition. Ignore+ // SIGXFSZ so a missing preflight surfaces as a kernel I/O error.+ assert_ne!(+ unsafe { libc::signal(libc::SIGXFSZ, libc::SIG_IGN) },+ libc::SIG_ERR+ );+ let mut fixture = Fixture::raw(false);+ let limit = 2 * IMAGE_BYTES;+ set_soft_file_size_limit(limit);++ let target = limit + SECTOR_SIZE;+ let error = fixture.grow(target).unwrap_err();+ assert_eq!(error.kind(), io::ErrorKind::FileTooLarge, "{error:?}");+ let message = error.to_string();+ assert!(message.contains("RLIMIT_FSIZE"), "got {error:?}");+ assert!(message.contains(&target.to_string()), "{message}");+ assert!(message.contains(&limit.to_string()), "{message}");+ assert_eq!(std::fs::metadata(&fixture.path).unwrap().len(), IMAGE_BYTES);+ assert_eq!(fixture.capacity(), IMAGE_BYTES / SECTOR_SIZE);+ assert_eq!(fixture.config_raised(), 0);++ assert_eq!(fixture.grow(limit).unwrap(), limit);+ assert_eq!(std::fs::metadata(&fixture.path).unwrap().len(), limit);+ assert_eq!(fixture.capacity(), limit / SECTOR_SIZE);+ assert_eq!(fixture.config_raised(), 1);++ let mut overlay = Fixture::qcow2();+ let overlay_file_size = std::fs::metadata(&overlay.path).unwrap().len();+ let target = (1 << 30) + SECTOR_SIZE;+ let one_mib = 1 << 20;+ let required = target + 2 * one_mib;+ let short_limit = target + one_mib;+ set_soft_file_size_limit(short_limit);++ let error = overlay.grow(target).unwrap_err();+ assert_eq!(error.kind(), io::ErrorKind::FileTooLarge, "{error:?}");+ let message = error.to_string();+ assert!(message.contains("RLIMIT_FSIZE"), "{message}");+ for value in [target, required, 2 * one_mib, short_limit] {+ assert!(message.contains(&value.to_string()), "{message}");+ }+ assert_eq!(+ std::fs::metadata(&overlay.path).unwrap().len(),+ overlay_file_size+ );+ assert_eq!(overlay.capacity(), IMAGE_BYTES / SECTOR_SIZE);+ assert_eq!(overlay.config_raised(), 0);++ set_soft_file_size_limit(required);+ assert_eq!(overlay.grow(target).unwrap(), target);+ assert_eq!(overlay.capacity(), target / SECTOR_SIZE);+ assert_eq!(overlay.config_raised(), 1);++ set_soft_file_size_limit(IMAGE_BYTES);+ assert_eq!(fixture.grow(limit).unwrap(), limit);+ assert_eq!(fixture.config_raised(), 1);+}++#[cfg(target_os = "linux")]+fn set_soft_file_size_limit(bytes: u64) {+ let mut limit = libc::rlimit64 {+ rlim_cur: 0,+ rlim_max: 0,+ };+ // SAFETY: getrlimit64 writes to a valid rlimit64 in this isolated process.+ assert_eq!(+ unsafe { libc::getrlimit64(libc::RLIMIT_FSIZE, &mut limit) },+ 0+ );+ limit.rlim_cur = bytes;+ // SAFETY: The isolated child updates its own soft limit.+ assert_eq!(unsafe { libc::setrlimit64(libc::RLIMIT_FSIZE, &limit) }, 0);+}++#[test]+fn invalid_grows_fail_without_a_change_or_an_interrupt() {+ let mut fixture = Fixture::qcow2();+ let sectors = fixture.capacity();+ for (bytes, kind) in [+ (IMAGE_BYTES - SECTOR_SIZE, io::ErrorKind::InvalidInput),+ (IMAGE_BYTES + 1, io::ErrorKind::InvalidInput),+ ] {+ assert_eq!(fixture.grow(bytes).unwrap_err().kind(), kind, "{bytes}");+ }+ // The current size is a successful no-op, so a retry is harmless.+ assert_eq!(fixture.grow(IMAGE_BYTES).unwrap(), IMAGE_BYTES);+ assert_eq!(fixture.capacity(), sectors);+ assert_eq!(fixture.config_raised(), 0);++ let mut read_only = Fixture::raw(true);+ assert_eq!(+ read_only.grow(2 * IMAGE_BYTES).unwrap_err().kind(),+ io::ErrorKind::PermissionDenied+ );+ assert_eq!(read_only.capacity(), IMAGE_BYTES / SECTOR_SIZE);+ assert_eq!(read_only.config_raised(), 0);+}++#[test]+fn a_grow_sent_while_inactive_waits_for_the_next_activation() {+ let mut fixture = Fixture::qcow2();+ fixture.blk.reset().unwrap();+ let late = fixture+ .handle+ .grow(2 * IMAGE_BYTES, Duration::from_millis(20))+ .unwrap_err();+ assert_eq!(late.kind(), io::ErrorKind::TimedOut);+ assert_eq!(fixture.capacity(), IMAGE_BYTES / SECTOR_SIZE);++ fixture.fresh_rings();+ let features = fixture.blk.spec().features;+ fixture.blk.set_features(features).unwrap();+ fixture.activate().unwrap();+ let control = SourceId(fixture.registrar.registered.load(Ordering::SeqCst) as u32 - 1);+ fixture+ .blk+ .on_event(DeviceEvent::BackendReady(control))+ .unwrap();+ assert_eq!(fixture.capacity(), 2 * IMAGE_BYTES / SECTOR_SIZE);+ assert_eq!(fixture.config_raised(), 1);+}diff --git a/src/vmm/tests/virtio/mmio.rs b/src/vmm/tests/virtio/mmio.rsindex e921772fb..1a3283c7e 100644--- a/src/vmm/tests/virtio/mmio.rs+++ b/src/vmm/tests/virtio/mmio.rs@@ -968,9 +968,11 @@ fn add_device_puts_each_device_in_its_own_slot() {let events = EventLoop::new().unwrap();let memory = Arc::new(GuestMemoryMmap::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap());let workers = VirtioWorkers::new(events.sender()).unwrap();+ let mut controls = crate::control::ControlRegistry::default();let ctx = DeviceContext {memory: &memory,workers: &workers,+ controls: &mut controls,};let mut slots = Slots::new();diff --git a/tests/scripts/test_vmm_boot_coverage.py b/tests/scripts/test_vmm_boot_coverage.pyindex 225062863..5cdc0233e 100644--- a/tests/scripts/test_vmm_boot_coverage.py+++ b/tests/scripts/test_vmm_boot_coverage.py@@ -32,6 +32,7 @@ class VmmBootCoverageTest(unittest.TestCase):makefile.write_text(f"PROJECT_ROOT := {root}\n""VMM_BALLOON_INIT :=\n"+ "VMM_DISK_GROW_INIT :=\n"f"include {COVERAGE_MAKEFILE}\n"".PHONY: _ensure-kvm _ensure-vmm-kernel vmm\\:guest-mount-init\n""_ensure-kvm _ensure-vmm-kernel:\n\t@true\n"