The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(vmm): grow and shrink guest RAM online with virtio-mem (#2906)
ltstrikerdc479cc0f59b
diff --git a/make/coverage.mk b/make/coverage.mkindex 1b3c9f3be..420927e2d 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_DISK_GROW_INIT) vmm\:guest-mount-init+coverage\:vmm\:boot: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT) $(VMM_DISK_GROW_INIT) $(VMM_HOTPLUG_INIT) vmm\:guest-mount-init@cargo llvm-cov nextest --no-report --no-tests=fail --profile ci --retries 0 --status-level pass \-p boxlite-vmm --lib --run-ignored only --test-threads=1 -E 'test(boot::tests::)'@cargo llvm-cov report $(COVERAGE_REPORT_ARGS) --lcov --output-path target/coverage/lcov.infodiff --git a/make/test.mk b/make/test.mkindex dc2c6e7ba..a4d223a8b 100644--- a/make/test.mk+++ b/make/test.mk@@ -323,9 +323,14 @@ export VMM_BALLOON_INITVMM_DISK_GROW_INIT ?= $(CURDIR)/target/vmm/boot/disk-grow-initexport VMM_DISK_GROW_INIT+# Freestanding virtio-mem grow and shrink scenario.+VMM_HOTPLUG_INIT ?= $(CURDIR)/target/vmm/boot/hotplug-init+export VMM_HOTPLUG_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):+$(VMM_HOTPLUG_INIT): $(PROJECT_ROOT)/src/vmm/tests/boot/hotplug_init.c+$(VMM_BALLOON_INIT) $(VMM_DISK_GROW_INIT) $(VMM_HOTPLUG_INIT):@mkdir -p "$(@D)"$(CC) -O2 -nostdlib -static -fno-pie -no-pie -fno-stack-protector -fno-builtin -Wl,--build-id=none "$<" -o "$@"@@ -346,7 +351,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) $(VMM_DISK_GROW_INIT)+test\:integration\:vmm\:linux: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT) $(VMM_DISK_GROW_INIT) $(VMM_HOTPLUG_INIT)@cargo test -p boxlite-vmm --lib --no-run@timeout $(VMM_BOOT_TESTS_TIMEOUT) cargo test -p boxlite-vmm --lib boot::tests:: -- --ignored --test-threads=1 --nocapture --skip boot::tests::guest_mounts::diff --git a/src/boxlite/src/vmm/native/engine.rs b/src/boxlite/src/vmm/native/engine.rsindex 1e12983d7..810bc1c37 100644--- a/src/boxlite/src/vmm/native/engine.rs+++ b/src/boxlite/src/vmm/native/engine.rs@@ -207,6 +207,7 @@ pub(crate) fn build_config(spec: &InstanceSpec) -> BoxliteResult<VmConfig> {}}),virtio_console: true,+ hotplug_mib: 0,})}@@ -257,6 +258,8 @@ pub(crate) fn map_vmm_error(error: boxlite_vmm::Error) -> BoxliteError {Error::InvalidVcpuCount(_)| Error::InvalidMemorySize(_)| Error::GuestMemoryAddressLimit { .. }+ | Error::InvalidHotplugSize(_)+ | Error::PlanHotplugMemory { .. }| Error::InvalidCommandLine(_)| Error::InvalidDiskCount(_)) {diff --git a/src/hypervisor/src/kvm/memory.rs b/src/hypervisor/src/kvm/memory.rsindex fcdf76aa5..d87c01e48 100644--- a/src/hypervisor/src/kvm/memory.rs+++ b/src/hypervisor/src/kvm/memory.rs@@ -12,6 +12,10 @@ use crate::MemoryRegion;/// KVM's limit on host pages in a single memory slot.pub(super) const MAX_PAGES_PER_SLOT: u64 = (1 << 31) - 1;+pub(super) fn slot_bytes(page_size: usize, max_pages: u64) -> usize {+ usize::try_from(max_pages.saturating_mul(page_size as u64)).unwrap_or(usize::MAX)+}+#[derive(Debug)]struct LogicalRegion {guest_addr: u64,@@ -131,9 +135,7 @@ impl MemorySlots {}self.validate_range(region)?;let region = *region;- let view_bytes = max_pages- .saturating_mul(self.page_size() as u64)- .min(region.size as u64) as usize;+ let view_bytes = slot_bytes(self.page_size(), max_pages).min(region.size);Ok((0..region.size.div_ceil(view_bytes)).map(move |index| {let offset = index * view_bytes;MemoryRegion {diff --git a/src/hypervisor/src/kvm/vm.rs b/src/hypervisor/src/kvm/vm.rsindex df6f254d8..e8b93970e 100644--- a/src/hypervisor/src/kvm/vm.rs+++ b/src/hypervisor/src/kvm/vm.rs@@ -15,7 +15,7 @@ use kvm_ioctls::{Cap, Kvm, VmFd};use super::KvmVcpu;use super::features::{build_snapshot_msr_indices, kvm_msr_index_list};-use super::memory::{MAX_PAGES_PER_SLOT, MemorySlots};+use super::memory::{MAX_PAGES_PER_SLOT, MemorySlots, slot_bytes};use super::vcpu::{CachedIoError, VcpuSnapshotShared};use crate::{Error, MemoryRegion, Result};@@ -63,6 +63,8 @@ pub struct PreparedKvm {kvm: Kvm,kick_signal: i32,cpuid: Vec<crate::X86CpuidEntry>,+ page_size: usize,+ memory_slots: usize,}impl PreparedKvm {@@ -100,10 +102,18 @@ impl PreparedKvm {}}let cpuid = super::features::supported_cpuid(&kvm)?;+ // SAFETY: sysconf has no pointer arguments and does not modify memory.+ let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };+ if page_size <= 0 {+ return Err(io::Error::other("cannot determine the host page size"));+ }+ let memory_slots = kvm.get_nr_memslots();Ok(Self {kvm,kick_signal,cpuid,+ page_size: page_size as usize,+ memory_slots,})}@@ -112,17 +122,24 @@ impl PreparedKvm {&self.cpuid}+ /// Slots left after registering the supplied page-aligned RAM regions.+ pub fn memory_slots_after(&self, region_sizes: impl IntoIterator<Item = usize>) -> usize {+ let bytes_per_slot = slot_bytes(self.page_size, MAX_PAGES_PER_SLOT);+ region_sizes+ .into_iter()+ .fold(self.memory_slots, |free, size| {+ free.saturating_sub(size.div_ceil(bytes_per_slot))+ })+ }+fn create(self) -> io::Result<KvmVm> {let Self {kvm,kick_signal,cpuid,+ page_size,+ memory_slots,} = self;- // SAFETY: sysconf has no pointer arguments and does not modify memory.- let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };- if page_size <= 0 {- return Err(io::Error::other("cannot determine the host page size"));- }let fd = kvm.create_vm().map_err(io::Error::from)?;// Intel KVM reserves three pages below 4 GiB for real-mode emulation.// Keep them in the architecture's MMIO hole, clear of RAM and devices.@@ -141,7 +158,7 @@ impl PreparedKvm {let vcpu_snapshot = Arc::new(VcpuSnapshotShared::new(Arc::clone(&fd), msr_indices));Ok(KvmVm {fd,- slots: Mutex::new(MemorySlots::new(kvm.get_nr_memslots(), page_size as usize)),+ slots: Mutex::new(MemorySlots::new(memory_slots, page_size)),run_size: kvm.get_vcpu_mmap_size().map_err(io::Error::from)?,kick_signal,cpuid,diff --git a/src/vmm/README.md b/src/vmm/README.mdindex 172c69720..a09a32a80 100644--- a/src/vmm/README.md+++ b/src/vmm/README.md@@ -277,8 +277,28 @@ Design: [#2882](https://github.com/boxlite-ai/boxlite/issues/2882).block unplugged. A failed unmap keeps the slot mapped and visible; `Drop`leaks a slot whose unmap fails.-The virtio-mem device and host control handle that drive it arrive next; the-`hotplug` tests use the recording backend.+### Virtio-mem device and control++On Linux x86_64, set `VmConfig.hotplug_mib` to the extra capacity above boot+RAM (`0` disables virtio-mem). `Vm::new` checks the window before building the VM.++BoxLite prepends `memhp_default_state=online` and+`memory_hotplug.online_policy=auto-movable` to the caller's command line.+Caller kernel parameters can override these defaults. Arguments after+`--` go to init.++`vm.control().set_memory_target_mib(256, timeout)` publishes a target of 256 MiB+above boot RAM and notifies the guest, which plugs or unplugs blocks afterward.+Targets are multiples of 128 MiB up to the configured capacity.++Use `memory_status(timeout)` to read the capacity, target, plugged and mapped+MiB. Shrinking is best effort, so the plugged size may stay above the target.++`WouldBlock` means the device is inactive or the control queue is full. An+accepted command can still run after the caller times out.++Reset discards queued commands. After VM exit, both operations return+`BrokenPipe` for an enabled device.## Kernel loadingdiff --git a/src/vmm/boot/README.md b/src/vmm/boot/README.mdindex 37e2d16e0..ad6131aa0 100644--- a/src/vmm/boot/README.md+++ b/src/vmm/boot/README.md@@ -46,7 +46,13 @@ caches it on `kernel.lock`, `kernel.config` and the build script.The fragment enables virtio-mmio, the reporting-only balloon and its selected`PAGE_REPORTING` dependency. Rebuild after a fragment change; an older M1-kernel cannot qualify reporting. The fragment carries no test-only setting: the+kernel cannot qualify reporting.++It also enables `VIRTIO_MEM` with memory hotplug and hot-remove.+`MEMORY_HOTPLUG` selects `MEMORY_ISOLATION`, which with `COMPACTION` gives the+`CONTIG_ALLOC` that virtio-mem needs to unplug.++The fragment carries no test-only setting: thequalification init reaches the host through its console, so nothing in theguest needs a capability the shipped kernel lacks. Reporting is deliberatelydisabled by the pinned driver under `init_on_free=1` without PAGE_POISONdiff --git a/src/vmm/boot/kernel.config b/src/vmm/boot/kernel.configindex 253b5c5d7..1ec0a4b2a 100644--- a/src/vmm/boot/kernel.config+++ b/src/vmm/boot/kernel.config@@ -96,3 +96,12 @@ CONFIG_SECCOMP_FILTER=y# Native hvc0 console output.CONFIG_VIRTIO_CONSOLE=y++# virtio-mem online memory grow and shrink. MEMORY_HOTPLUG selects+# MEMORY_ISOLATION, which with COMPACTION gives CONTIG_ALLOC.+CONFIG_SPARSEMEM_VMEMMAP=y+CONFIG_MEMORY_HOTPLUG=y+CONFIG_MIGRATION=y+CONFIG_MEMORY_HOTREMOVE=y+CONFIG_COMPACTION=y+CONFIG_VIRTIO_MEM=ydiff --git a/src/vmm/src/boot/mod.rs b/src/vmm/src/boot/mod.rsindex 5f1ded345..0e19b397f 100644--- a/src/vmm/src/boot/mod.rs+++ b/src/vmm/src/boot/mod.rs@@ -18,6 +18,8 @@ use crate::{memory::{GuestMemoryMmap, GuestRam},x86_boot_layout::{self, CheckedBootLeaf, PageSize},};+#[cfg(target_os = "linux")]+use crate::{cpu_features::X86MemoryCaps, hotplug::HotplugWindow, memory::ram_ranges};pub(crate) mod elf;pub(crate) mod entry;@@ -28,6 +30,35 @@ pub(crate) mod params;/// Internal leaf-size switch; any selected size must pass host preflight before use.pub(crate) const BOOT_LEAF: PageSize = PageSize::Mib;+/// Checks boot RAM and plans the optional hotplug window against the same host+/// limits and backed ranges before VM construction.+#[cfg(target_os = "linux")]+pub(crate) fn preflight(+ config: &VmConfig,+ kvm: &boxlite_hypervisor::PreparedKvm,+) -> Result<(CheckedBootLeaf, Option<HotplugWindow>)> {+ let caps =+ X86MemoryCaps::from_cpuid(kvm.supported_cpuid()).map_err(Error::HostMemoryCapability)?;+ let ranges = ram_ranges(config.memory_mib);+ let leaf = caps.check_boot_leaf(config.memory_mib, &ranges, BOOT_LEAF)?;+ if config.hotplug_mib == 0 {+ return Ok((leaf, None));+ }++ let available_slots = kvm.memory_slots_after(ranges.iter().map(|&(_, size)| size));+ let window = HotplugWindow::plan(+ &ranges,+ config.hotplug_mib,+ caps.physical_end,+ available_slots,+ )+ .map_err(|source| Error::PlanHotplugMemory {+ capacity_mib: config.hotplug_mib,+ source,+ })?;+ Ok((leaf, Some(window)))+}+/// The boot data the vCPU workers apply once [`prepare`] has filled guest RAM.#[derive(Debug)]pub(crate) struct BootSetup {diff --git a/src/vmm/src/config.rs b/src/vmm/src/config.rsindex 551f88b96..04e4cacbd 100644--- a/src/vmm/src/config.rs+++ b/src/vmm/src/config.rs@@ -67,6 +67,10 @@ pub struct VmConfig {pub network: Option<NetConfig>,/// Send hvc0 output to the supplied console sink.pub virtio_console: bool,+ /// Hotplug capacity in MiB above `memory_mib`. Zero disables virtio-mem.+ /// A positive capacity must fit the guest's memory block alignment,+ /// physical address limits and available KVM memory slots.+ pub hotplug_mib: u32,}/// One virtio-fs device exposing the configured host directories.@@ -139,6 +143,9 @@ impl VmConfig {{return Err(Error::InvalidCommandLine("not printable ASCII"));}+ if !(u64::from(self.hotplug_mib) << 20).is_multiple_of(crate::hotplug::SLOT_SIZE) {+ return Err(Error::InvalidHotplugSize(self.hotplug_mib));+ }Ok(())}}@@ -162,6 +169,7 @@ mod tests {vsock: None,network: None,virtio_console: false,+ hotplug_mib: 0,}}diff --git a/src/vmm/src/control.rs b/src/vmm/src/control.rsindex 001360d3d..9df239837 100644--- a/src/vmm/src/control.rs+++ b/src/vmm/src/control.rs@@ -5,12 +5,17 @@use std::{collections::HashMap, io, sync::Arc, time::Duration};+use crate::MemoryStatus;use crate::virtio::blk::control::{self, Controls, DiskSender};+mod memory;+pub(crate) use memory::{MemoryRequest, MemoryRequests};+/// Controls a VM from any thread without exposing its devices.#[derive(Clone, Debug)]pub struct VmControl {disks: Arc<HashMap<String, DiskSender>>,+ memory: Option<memory::MemorySender>,}impl VmControl {@@ -30,12 +35,45 @@ impl VmControl {})?.grow(bytes, timeout)}++ /// Sets the hotplug target above boot RAM, in MiB. Success means the+ /// effective target was published; the guest plugs or unplugs afterward.+ /// An inactive device or full queue returns `WouldBlock`. A timeout+ /// does not cancel an admitted command.+ pub fn set_memory_target_mib(&self, added_mib: u32, timeout: Duration) -> io::Result<()> {+ self.memory()?+ .request(timeout, |reply| MemoryRequest::SetTarget {+ added_mib,+ reply,+ })+ }++ /// Reads hotplug capacity, target, and actual sizes from the active device.+ pub fn memory_status(&self, timeout: Duration) -> io::Result<MemoryStatus> {+ self.memory()?.request(timeout, MemoryRequest::Status)+ }++ fn memory(&self) -> io::Result<&memory::MemorySender> {+ self.memory.as_ref().ok_or_else(|| {+ io::Error::new(+ io::ErrorKind::Unsupported,+ "the VM has no virtio-mem device",+ )+ })+ }++ pub(crate) fn close_memory(&self) {+ if let Some(memory) = &self.memory {+ memory.close();+ }+ }}/// Mutable only while the VM's devices are being built.#[derive(Default)]pub(crate) struct ControlRegistry {disks: HashMap<String, DiskSender>,+ memory: Option<memory::MemorySender>,}impl ControlRegistry {@@ -56,6 +94,20 @@ impl ControlRegistry {pub(crate) fn finish(self) -> VmControl {VmControl {disks: Arc::new(self.disks),+ memory: self.memory,+ }+ }++ #[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]+ pub(crate) fn register_memory(&mut self) -> io::Result<MemoryRequests> {+ if self.memory.is_some() {+ return Err(io::Error::new(+ io::ErrorKind::AlreadyExists,+ "the VM already has a memory control endpoint",+ ));}+ let (sender, requests) = memory::channel();+ self.memory = Some(sender);+ Ok(requests)}}diff --git a/src/vmm/src/control/memory.rs b/src/vmm/src/control/memory.rsnew file mode 100644index 000000000..2a61e16d6--- /dev/null+++ b/src/vmm/src/control/memory.rs@@ -0,0 +1,221 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++use std::{+ collections::VecDeque,+ io::{self, Read, Write},+ os::unix::net::UnixStream,+ sync::{+ Arc, Mutex, MutexGuard, PoisonError,+ mpsc::{self, RecvTimeoutError, SyncSender},+ },+ time::Duration,+};++use crate::{MemoryStatus, virtio::EventSource};++const CAPACITY: usize = 16;++pub(crate) enum MemoryRequest {+ SetTarget {+ added_mib: u32,+ reply: SyncSender<io::Result<()>>,+ },+ Status(SyncSender<io::Result<MemoryStatus>>),+}++#[derive(Default)]+struct Endpoint {+ closed: bool,+ activation: Option<Activation>,+}++struct Activation {+ token: Arc<()>,+ started: bool,+ read: UnixStream,+ write: UnixStream,+ pending: VecDeque<MemoryRequest>,+}++fn lock(endpoint: &Mutex<Endpoint>) -> MutexGuard<'_, Endpoint> {+ endpoint.lock().unwrap_or_else(PoisonError::into_inner)+}++fn closed() -> io::Error {+ io::Error::new(+ io::ErrorKind::BrokenPipe,+ "the memory control endpoint closed",+ )+}++#[derive(Clone)]+pub(super) struct MemorySender(Arc<Mutex<Endpoint>>);++impl std::fmt::Debug for MemorySender {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("MemorySender").finish_non_exhaustive()+ }+}++impl MemorySender {+ pub(super) fn request<T>(+ &self,+ timeout: Duration,+ build: impl FnOnce(SyncSender<io::Result<T>>) -> MemoryRequest,+ ) -> io::Result<T> {+ let (reply, done) = mpsc::sync_channel(1);+ self.submit(build(reply))?;+ done.recv_timeout(timeout).map_err(|error| match error {+ RecvTimeoutError::Timeout => io::Error::new(+ io::ErrorKind::TimedOut,+ "virtio-mem has not replied to the control request",+ ),+ RecvTimeoutError::Disconnected => closed(),+ })?+ }++ fn submit(&self, request: MemoryRequest) -> io::Result<()> {+ let mut endpoint = lock(&self.0);+ if endpoint.closed {+ return Err(closed());+ }+ let active = endpoint+ .activation+ .as_mut()+ .filter(|activation| activation.started)+ .ok_or_else(|| io::Error::new(io::ErrorKind::WouldBlock, "virtio-mem is inactive"))?;+ if active.pending.len() == CAPACITY {+ return Err(io::Error::new(+ io::ErrorKind::WouldBlock,+ "the memory control queue is full",+ ));+ }+ active.pending.push_back(request);+ // Enqueue and ring under the same lock used for the worker's drain+ // and snapshot. A full socket already signals readiness.+ if let Err(error) = (&active.write).write_all(&[1])+ && error.kind() != io::ErrorKind::WouldBlock+ {+ endpoint.activation = None;+ return Err(error);+ }+ Ok(())+ }++ pub(super) fn close(&self) {+ let mut endpoint = lock(&self.0);+ endpoint.closed = true;+ endpoint.activation = None;+ }+}++pub(crate) struct MemoryRequests(Arc<Mutex<Endpoint>>);++impl MemoryRequests {+ pub(crate) fn prepare(&self) -> io::Result<Box<dyn EventSource>> {+ let (read, write) = UnixStream::pair()?;+ read.set_nonblocking(true)?;+ write.set_nonblocking(true)?;+ let bell = mio::net::UnixStream::from_std(read.try_clone()?);+ let mut endpoint = lock(&self.0);+ if endpoint.closed {+ return Err(closed());+ }+ let token = Arc::new(());+ endpoint.activation = Some(Activation {+ token: token.clone(),+ started: false,+ read,+ write,+ pending: VecDeque::new(),+ });+ Ok(Box::new(Bell {+ bell,+ endpoint: self.0.clone(),+ token,+ }))+ }++ pub(crate) fn batch_len(&self) -> io::Result<usize> {+ let mut endpoint = lock(&self.0);+ let Some(active) = endpoint.activation.as_mut() else {+ return Ok(0);+ };+ if let Err(error) = drain(&active.read) {+ endpoint.activation = None;+ return Err(error);+ }+ Ok(active.pending.len())+ }++ pub(crate) fn claim(&self) -> Option<MemoryRequest> {+ lock(&self.0).activation.as_mut()?.pending.pop_front()+ }+}++impl Drop for MemoryRequests {+ fn drop(&mut self) {+ MemorySender(self.0.clone()).close();+ }+}++#[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]+pub(super) fn channel() -> (MemorySender, MemoryRequests) {+ let endpoint = Arc::new(Mutex::new(Endpoint::default()));+ (MemorySender(endpoint.clone()), MemoryRequests(endpoint))+}++fn drain(mut bell: impl Read) -> io::Result<()> {+ let mut bytes = [0; 64];+ loop {+ match bell.read(&mut bytes) {+ Ok(0) => return Err(closed()),+ Ok(_) => {}+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => return Ok(()),+ Err(error) => return Err(error),+ }+ }+}++struct Bell {+ bell: mio::net::UnixStream,+ endpoint: Arc<Mutex<Endpoint>>,+ token: Arc<()>,+}++impl EventSource for Bell {+ fn as_source(&mut self) -> &mut dyn mio::event::Source {+ &mut self.bell+ }++ fn worker_started(&mut self) {+ if let Some(active) = lock(&self.endpoint).activation.as_mut()+ && Arc::ptr_eq(&active.token, &self.token)+ {+ active.started = true;+ }+ }++ fn worker_stopped(&mut self) {+ let mut endpoint = lock(&self.endpoint);+ if endpoint+ .activation+ .as_ref()+ .is_some_and(|active| Arc::ptr_eq(&active.token, &self.token))+ {+ endpoint.activation = None;+ }+ }+}++impl Drop for Bell {+ fn drop(&mut self) {+ self.worker_stopped();+ }+}++#[cfg(test)]+#[path = "../../tests/control/memory.rs"]+mod tests;diff --git a/src/vmm/src/cpu_features.rs b/src/vmm/src/cpu_features.rsindex 334008dad..e9d592c65 100644--- a/src/vmm/src/cpu_features.rs+++ b/src/vmm/src/cpu_features.rs@@ -10,12 +10,16 @@use std::io;use boxlite_hypervisor::{X86CpuidEntry, X86Msr};+#[cfg(any(test, target_os = "linux"))]+use vm_memory::GuestAddress;use crate::config::MAX_VCPUS;+#[cfg(test)]+use crate::memory::ram_ranges;#[cfg(any(test, target_os = "linux"))]use crate::{error::{Error, Result},- memory::{check_ram_end, ram_ranges},+ memory::check_ram_end,x86_boot_layout::{CheckedBootLeaf, IDENTITY_END, PageSize},};@@ -113,29 +117,38 @@ impl X86MemoryCaps {pdpe1gb,})}++ /// Checks backed GPAs and the requested boot leaf before allocating RAM.+ pub(crate) fn check_boot_leaf(+ &self,+ memory_mib: u32,+ ranges: &[(GuestAddress, usize)],+ requested_leaf: PageSize,+ ) -> Result<CheckedBootLeaf> {+ let mut limits = [+ (self.physical_end, "KVM GPA"),+ (IDENTITY_END, "four-level identity map"),+ ];+ // Report the tighter limit, keeping KVM first if the limits are equal.+ limits.sort_by_key(|&(end, _)| end);+ for (end, name) in limits {+ check_ram_end(memory_mib, ranges, end, name)?;+ }+ requested_leaf+ .checked(self.pdpe1gb)+ .map_err(Error::HostMemoryCapability)+ }}-/// Checks backed GPAs and the requested boot leaf before allocating RAM.-#[cfg(any(test, target_os = "linux"))]+/// Checks the boot layout for tests that supply their own CPUID or page size.+#[cfg(test)]pub(crate) fn preflight_x86(memory_mib: u32,entries: &[X86CpuidEntry],requested_leaf: PageSize,) -> Result<CheckedBootLeaf> {let caps = X86MemoryCaps::from_cpuid(entries).map_err(Error::HostMemoryCapability)?;- let ranges = ram_ranges(memory_mib);- let mut limits = [- (caps.physical_end, "KVM GPA"),- (IDENTITY_END, "four-level identity map"),- ];- // Report the tighter limit, keeping KVM first if the limits are equal.- limits.sort_by_key(|&(end, _)| end);- for (end, name) in limits {- check_ram_end(memory_mib, &ranges, end, name)?;- }- requested_leaf- .checked(caps.pdpe1gb)- .map_err(Error::HostMemoryCapability)+ caps.check_boot_leaf(memory_mib, &ram_ranges(memory_mib), requested_leaf)}/// The CPUID of vCPU `index` of `count`: `supported` with APIC ID `index`, onediff --git a/src/vmm/src/devices/mem.rs b/src/vmm/src/devices/mem.rsnew file mode 100644index 000000000..0eeacea0f--- /dev/null+++ b/src/vmm/src/devices/mem.rs@@ -0,0 +1,353 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++//! The virtio-mem device (VIRTIO 1.4 §5.15) over [`HotplugMemory`].+//!+//! The host sets a target with [`crate::VmControl::set_memory_target_mib`]; the device publishes+//! it as `requested_size` and raises a configuration interrupt. The guest+//! driver then plugs or unplugs blocks through the request queue. A plug above+//! the target gets NACK, never ERROR: Linux marks the device broken after an+//! ERROR. Shrinking is best effort; [`crate::VmControl::memory_status`] reports what the+//! guest actually holds.++use std::{io, sync::Arc};++use boxlite_hypervisor::Vm;+use virtio_queue::DescriptorChain;+use vm_memory::Bytes;++use crate::{+ control::{MemoryRequest, MemoryRequests},+ hotplug::{BLOCK_SIZE, BlockState, HotplugMemory, SLOT_SIZE},+ memory::GuestMemoryMmap,+ virtio::{+ ActivationContext, DeviceError, DeviceEvent, DeviceSpec, FeatureError, SnapshotSupport,+ SourceId, VirtioDevice, queue::Completion,+ },+};++/// `VIRTIO_MEM_F_UNPLUGGED_INACCESSIBLE`: the driver never reads unplugged+/// memory, which the VMM leaves unmapped.+const UNPLUGGED_INACCESSIBLE: u64 = 1 << 1;+const SPEC: DeviceSpec = DeviceSpec {+ device_id: 24,+ name: "virtio-mem",+ features: UNPLUGGED_INACCESSIBLE,+ config_len: 56,+ queue_max: &[128],+ snapshot: SnapshotSupport::Unsupported,+};+const MIB: u64 = 1 << 20;++const PLUG: u16 = 0;+const UNPLUG: u16 = 1;+const UNPLUG_ALL: u16 = 2;+const STATE: u16 = 3;+const ACK: u16 = 0;+const NACK: u16 = 1;+const BUSY: u16 = 2;+const ERROR: u16 = 3;++/// What the guest holds, in MiB above the boot RAM.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct MemoryStatus {+ /// The configured hotplug capacity.+ pub capacity_mib: u32,+ /// The current host target.+ pub requested_mib: u32,+ /// Memory the guest has plugged.+ pub plugged_mib: u32,+ /// Host memory mapped for the guest; at least `plugged_mib`.+ pub mapped_mib: u32,+}++/// The virtio-mem device and the hotplug window it drives.+pub(crate) struct VirtioMem<H: Vm + ?Sized> {+ memory: HotplugMemory<H>,+ controls: MemoryRequests,+ requested: u64,+ features: u64,+ active: Option<Active>,+}++struct Active {+ context: ActivationContext,+ control: SourceId,+}++/// Adds the device on `slot` and registers its VM control endpoint.+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+pub(crate) fn add<H: Vm + Send + Sync + 'static>(+ chipset: &mut crate::chipset::ChipsetBuilder,+ ctx: &mut crate::virtio::DeviceContext<'_>,+ slot: crate::virtio::mmio::Slot,+ memory: HotplugMemory<H>,+) -> crate::Result<()> {+ let controls = ctx+ .controls+ .register_memory()+ .map_err(crate::Error::RegisterMemoryControl)?;+ let device = Arc::new(std::sync::Mutex::new(VirtioMem::new(memory, controls)));+ crate::virtio::mmio::add_device(chipset, ctx, SPEC.name, slot, device)+}++impl<H: Vm + ?Sized> VirtioMem<H> {+ pub(crate) fn new(memory: HotplugMemory<H>, controls: MemoryRequests) -> Self {+ Self {+ memory,+ controls,+ requested: 0,+ features: 0,+ active: None,+ }+ }++ fn apply_controls(&mut self) {+ let count = match self.controls.batch_len() {+ Ok(count) => count,+ Err(error) => {+ tracing::warn!(%error, "virtio-mem control wakeup failed");+ return;+ }+ };+ for _ in 0..count {+ match self.controls.claim() {+ Some(MemoryRequest::SetTarget { added_mib, reply }) => {+ let _ = reply.try_send(self.set_target(added_mib));+ }+ Some(MemoryRequest::Status(reply)) => {+ let _ = reply.try_send(Ok(self.status()));+ }+ None => break,+ }+ }+ }++ fn set_target(&mut self, added_mib: u32) -> io::Result<()> {+ let bytes = u64::from(added_mib) * MIB;+ if !bytes.is_multiple_of(SLOT_SIZE) || bytes > self.memory.size() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("invalid hotplug memory size: {added_mib} MiB"),+ ));+ }+ let active = self+ .active+ .as_ref()+ .expect("host controls run on the active device");+ self.requested = bytes;+ active.context.interrupt.raise_config();+ Ok(())+ }++ fn status(&self) -> MemoryStatus {+ let mib = |bytes: u64| (bytes / MIB) as u32;+ MemoryStatus {+ capacity_mib: mib(self.memory.size()),+ requested_mib: mib(self.requested),+ plugged_mib: mib(self.memory.plugged_bytes()),+ mapped_mib: mib(self.memory.mapped_bytes()),+ }+ }++ fn config(&self) -> [u8; 56] {+ let mut config = [0; 56];+ let fields = [+ (0, BLOCK_SIZE),+ (16, self.memory.base()),+ (24, self.memory.size()),+ (32, self.memory.size()),+ (40, self.memory.plugged_bytes()),+ (48, self.requested),+ ];+ for (offset, value) in fields {+ config[offset..offset + 8].copy_from_slice(&value.to_le_bytes());+ }+ config+ }++ /// Handles one request and returns the response type and block state.+ fn handle(&mut self, kind: u16, addr: u64, count: u16) -> (u16, u16) {+ if kind == UNPLUG_ALL {+ if let Err(error) = self.memory.unplug_all() {+ tracing::warn!(%error, "virtio-mem unplug-all left a slot mapped");+ }+ return (ACK, 0);+ }+ let Some(blocks) = self.memory.blocks(addr, count) else {+ return (ERROR, 0);+ };+ let state = self.memory.state(blocks.clone());+ match (kind, state) {+ (STATE, state) => (ACK, state_code(state)),+ (PLUG, BlockState::Unplugged) => {+ let added = blocks.len() as u64 * BLOCK_SIZE;+ if self.memory.plugged_bytes() + added > self.requested {+ (NACK, 0)+ } else if self.memory.plug(blocks).is_err() {+ (BUSY, 0)+ } else {+ (ACK, 0)+ }+ }+ (UNPLUG, BlockState::Plugged) => {+ if let Err(error) = self.memory.unplug(blocks.clone()) {+ tracing::warn!(%error, "virtio-mem unplug left a slot mapped");+ }+ // The blocks are unplugged even when a slot stays mapped.+ match self.memory.state(blocks) {+ BlockState::Unplugged => (ACK, 0),+ _ => (BUSY, 0),+ }+ }+ _ => (ERROR, 0),+ }+ }++ fn request(+ &mut self,+ mut chain: DescriptorChain<&GuestMemoryMmap>,+ ) -> std::result::Result<Completion, DeviceError> {+ let invalid = || DeviceError::NeedsReset("virtio-mem request descriptors");+ let request = chain.next().ok_or_else(invalid)?;+ let response = chain.next().ok_or_else(invalid)?;+ let memory = chain.memory();+ if request.is_write_only()+ || request.len() < 24+ || !response.is_write_only()+ || response.len() < 10+ || response.has_next()+ {+ return Err(invalid());+ }+ let mut bytes = [0u8; 24];+ memory+ .read_slice(&mut bytes, request.addr())+ .map_err(|_| invalid())?;+ let field = |range: std::ops::Range<usize>| -> [u8; 8] {+ let mut out = [0; 8];+ out[..range.len()].copy_from_slice(&bytes[range]);+ out+ };+ let kind = u64::from_le_bytes(field(0..2)) as u16;+ let addr = u64::from_le_bytes(field(8..16));+ let count = u64::from_le_bytes(field(16..18)) as u16;+ let (kind, state) = self.handle(kind, addr, count);+ let mut reply = [0u8; 10];+ reply[0..2].copy_from_slice(&kind.to_le_bytes());+ reply[8..10].copy_from_slice(&state.to_le_bytes());+ memory+ .write_slice(&reply, response.addr())+ .map_err(|_| invalid())?;+ Ok(Completion::Used(reply.len() as u32))+ }+}++impl<H: Vm + Send + Sync + ?Sized> VirtioDevice for VirtioMem<H> {+ fn spec(&self) -> &DeviceSpec {+ &SPEC+ }++ fn set_features(&mut self, negotiated: u64) -> std::result::Result<(), FeatureError> {+ let unsupported = negotiated & !UNPLUGGED_INACCESSIBLE;+ if unsupported != 0 {+ return Err(FeatureError { unsupported });+ }+ self.features = negotiated;+ Ok(())+ }++ fn read_config(+ &mut self,+ offset: u64,+ data: &mut [u8],+ ) -> std::result::Result<(), DeviceError> {+ let config = self.config();+ for (index, byte) in data.iter_mut().enumerate() {+ *byte = offset+ .checked_add(index as u64)+ .and_then(|address| config.get(address as usize))+ .copied()+ .unwrap_or(0);+ }+ Ok(())+ }++ fn write_config(&mut self, _: u64, _: &[u8]) -> std::result::Result<(), DeviceError> {+ // Every field is read-only for the driver.+ Ok(())+ }++ fn activate(&mut self, ctx: ActivationContext) -> std::result::Result<(), DeviceError> {+ if self.active.is_some()+ || self.features & UNPLUGGED_INACCESSIBLE == 0+ || ctx.queues.len() != 1+ || !ctx.queues.is_ready(0)+ {+ return Err(DeviceError::NeedsReset("virtio-mem activation"));+ }+ let control = self+ .controls+ .prepare()+ .and_then(|source| ctx.events.register(source).map_err(io::Error::other))+ .map_err(|error| {+ tracing::warn!(%error, "virtio-mem control source was not registered");+ DeviceError::NeedsReset("virtio-mem control source")+ })?;+ self.active = Some(Active {+ context: ctx,+ control,+ });+ Ok(())+ }++ fn reset(&mut self) -> std::result::Result<(), DeviceError> {+ // Plugged blocks survive a reset: a reprobing driver unplugs them all.+ self.features = 0;+ if let Some(active) = self.active.take() {+ active.context.events.deregister(active.control);+ }+ Ok(())+ }++ fn on_event(&mut self, event: DeviceEvent) -> std::result::Result<(), DeviceError> {+ if let DeviceEvent::BackendReady(id) = event+ && self+ .active+ .as_ref()+ .is_some_and(|active| active.control == id)+ {+ self.apply_controls();+ return Ok(());+ }+ let DeviceEvent::QueueKick(0) = event else {+ return Err(DeviceError::Unsupported("virtio-mem event"));+ };+ let mut active = self+ .active+ .take()+ .ok_or(DeviceError::NeedsReset("inactive virtio-mem"))?;+ let result = active.context.queues.drain(0, |chain| self.request(chain));+ let interrupt = Arc::clone(&active.context.interrupt);+ self.active = Some(active);+ if result? {+ interrupt.raise();+ }+ Ok(())+ }+}++/// The VIRTIO STATE response code for `state`.+fn state_code(state: BlockState) -> u16 {+ match state {+ BlockState::Plugged => 0,+ BlockState::Unplugged => 1,+ BlockState::Mixed => 2,+ }+}++// The file lives under `tests/` so the suite stays out of the crate's counted+// source; it is still a unit-test module with access to crate-private items.+#[cfg(test)]+#[path = "../../tests/mem/mod.rs"]+mod tests;diff --git a/src/vmm/src/devices/mod.rs b/src/vmm/src/devices/mod.rsindex a72c688eb..6c9301c62 100644--- a/src/vmm/src/devices/mod.rs+++ b/src/vmm/src/devices/mod.rs@@ -9,6 +9,7 @@ pub(crate) mod cmos;pub(crate) mod console;#[cfg(target_arch = "x86_64")]pub(crate) mod i8042;+pub(crate) mod mem;#[cfg(unix)]pub(crate) mod net;#[cfg(target_arch = "x86_64")]@@ -27,6 +28,7 @@ use crate::{chipset::ChipsetBuilder,config::VmConfig,error::Result,+ hotplug::{HotplugMemory, HotplugWindow},memory::ReclaimPolicy,virtio::{DeviceContext, blk, fs,@@ -34,15 +36,22 @@ use crate::{},};+/// Defaults for automatically onlining hotplugged memory in removable zones.+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+const HOTPLUG_CMDLINE: &str =+ "memhp_default_state=online memory_hotplug.online_policy=auto-movable";+/// Adds every device the configuration names, in slot order: the legacy/// platform devices, disks, reporting balloon, and optional filesystem,-/// vsock, network and console.+/// vsock, network, console and virtio-mem.#[cfg(all(target_os = "linux", target_arch = "x86_64"))]-pub(crate) fn add_all(+pub(crate) fn add_all<H: boxlite_hypervisor::Vm + Send + Sync + 'static>(chipset: &mut ChipsetBuilder,mut ctx: DeviceContext<'_>,config: &mut VmConfig,console: ConsoleWriter,+ host_vm: &Arc<H>,+ hotplug_window: Option<HotplugWindow>,) -> Result<()> {add_legacy_devices(chipset, console.clone(), Box::new(cmos::host_clock))?;@@ -88,6 +97,17 @@ pub(crate) fn add_all(mmio::add_device(chipset, &ctx, "virtio-console", slot, device)})?;}+ if let Some(window) = hotplug_window {+ let hotplug = HotplugMemory::new(Arc::clone(host_vm), ctx.memory.clone(), window);+ add_slot_device(&mut slots, &mut used, |slot| {+ mem::add(chipset, &mut ctx, slot, hotplug)+ })?;+ // Keep the defaults before the caller's kernel and init arguments.+ config.cmdline = match config.cmdline.as_str() {+ "" => HOTPLUG_CMDLINE.to_owned(),+ caller => format!("{HOTPLUG_CMDLINE} {caller}"),+ };+ }// The next device is one more `add_slot_device` line here. A device that// must keep slot 0 goes before the disk loop.mmio::announce(&mut config.cmdline, &used)diff --git a/src/vmm/src/error.rs b/src/vmm/src/error.rsindex 9b6c8dfb8..c29b6cb56 100644--- a/src/vmm/src/error.rs+++ b/src/vmm/src/error.rs@@ -32,6 +32,14 @@ pub enum Error {},/// The host's guest-memory capabilities are invalid or insufficient.HostMemoryCapability(io::Error),+ /// A hotplug capacity or target in MiB is not a multiple of 128 MiB, or+ /// does not fit the configured capacity.+ InvalidHotplugSize(u32),+ /// The requested hotplug window does not fit the guest or KVM layout.+ PlanHotplugMemory {+ capacity_mib: u32,+ source: io::Error,+ },/// Allocating the guest RAM failed.AllocateMemory { bytes: u64, source: io::Error },/// A host hypervisor operation failed.@@ -46,6 +54,8 @@ pub enum Error {OpenDisk { path: PathBuf, source: io::Error },/// Creating the channel that grows a disk failed.DiskControl(io::Error),+ /// The VM already has a memory control endpoint.+ RegisterMemoryControl(io::Error),/// Every virtio-mmio window and interrupt line is taken.VirtioSlotsExhausted,/// Devices claimed resources the chipset cannot give them.@@ -110,6 +120,16 @@ impl fmt::Display for Error {Self::HostMemoryCapability(source) => {write!(f, "guest memory capability check failed: {source}")}+ Self::InvalidHotplugSize(mib) => write!(f, "invalid hotplug memory size: {mib} MiB"),+ Self::PlanHotplugMemory {+ capacity_mib,+ source,+ } => {+ write!(+ f,+ "cannot plan {capacity_mib} MiB of hotplug memory: {source}"+ )+ }Self::AllocateMemory { bytes, .. } => {write!(f, "failed to allocate {bytes} bytes of guest RAM")}@@ -120,6 +140,7 @@ impl fmt::Display for Error {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::RegisterMemoryControl(_) => f.write_str("failed to register memory control"),Self::OpenDisk { path, .. } => {write!(f, "failed to open the disk image {}", path.display())}@@ -170,6 +191,7 @@ impl error::Error for Error {Self::InvalidVcpuCount(_)| Self::InvalidMemorySize(_)| Self::GuestMemoryAddressLimit { .. }+ | Self::InvalidHotplugSize(_)| Self::InvalidCommandLine(_)| Self::InvalidDiskCount(_)| Self::InvalidDiskId(_)@@ -183,9 +205,11 @@ impl error::Error for Error {Self::Vsock(source)| Self::Filesystem(source)| Self::HostMemoryCapability(source)+ | Self::PlanHotplugMemory { source, .. }| Self::AllocateMemory { source, .. }| Self::OpenDisk { source, .. }| Self::DiskControl(source)+ | Self::RegisterMemoryControl(source)| Self::LoadKernel { source, .. }| Self::LoadInitramfs { source, .. }| Self::WriteBootData { source, .. }diff --git a/src/vmm/src/lib.rs b/src/vmm/src/lib.rsindex 38712b2a5..8ce3cf6a0 100644--- a/src/vmm/src/lib.rs+++ b/src/vmm/src/lib.rs@@ -45,11 +45,8 @@ mod error;)]mod events;#[cfg_attr(- not(test),- expect(- dead_code,- reason = "The virtio-mem device that drives hotplug memory comes next."- )+ not(any(test, all(target_os = "linux", target_arch = "x86_64"))),+ expect(dead_code, reason = "Only the Linux x86_64 Vm::new adds devices yet."))]mod hotplug;#[cfg_attr(@@ -87,6 +84,7 @@ pub use config::{DiskConfig, DiskFormat, FsConfig, FsShareConfig, NetConfig, VmConfig, VsockConfig,};pub use control::VmControl;+pub use devices::mem::MemoryStatus;pub use error::{Error, Result};pub use memory::ReclaimPolicy;#[cfg(all(target_os = "linux", target_arch = "x86_64"))]diff --git a/src/vmm/src/virtio/mod.rs b/src/vmm/src/virtio/mod.rsindex eac6f04b9..73f03aa22 100644--- a/src/vmm/src/virtio/mod.rs+++ b/src/vmm/src/virtio/mod.rs@@ -114,6 +114,12 @@ pub(crate) struct SourceId(pub(crate) u32);pub(crate) trait EventSource: Send {/// The source the workers register with their poller.fn as_source(&mut self) -> &mut dyn mio::event::Source;++ /// Opens admission for host commands once dispatch can run.+ fn worker_started(&mut self) {}++ /// Closes host admission before dispatch stops. Must not wait for the worker.+ fn worker_stopped(&mut self) {}}/// The interface a device uses to register background sources with thediff --git a/src/vmm/src/virtio/worker/shared.rs b/src/vmm/src/virtio/worker/shared.rsindex e42451f59..7f2ff75d0 100644--- a/src/vmm/src/virtio/worker/shared.rs+++ b/src/vmm/src/virtio/worker/shared.rs@@ -155,10 +155,17 @@ impl Slot {.unwrap_or(Err(DeviceError::Fatal("quiesce panicked")))}+ fn stop_sources(state: &mut SlotState) {+ for registered in state.sources.values_mut() {+ registered.source.worker_stopped();+ }+ }+/// Ends the open generation: drops its kicks, deregisters and drops its/// sources, and moves to `phase`.fn close(&self, state: &mut SlotState, registry: &Registry, phase: Phase) {state.phase = phase;+ Self::stop_sources(state);self.kicks.store(0, Ordering::SeqCst);for (_, mut registered) in state.sources.drain() {if let Err(error) = registry.deregister(registered.source.as_source()) {@@ -209,6 +216,7 @@ impl Slot {Err(DeviceError::NeedsReset(_)) => {if current && state.phase == Phase::Running {state.phase = Phase::Halted;+ Self::stop_sources(&mut state);}}Err(DeviceError::Fatal(reason)) => {@@ -415,6 +423,9 @@ impl WorkerRuntime for SharedRuntime {return Err(DeviceError::Fatal("virtio worker is not prepared"));}state.phase = Phase::Running;+ for registered in state.sources.values_mut() {+ registered.source.worker_started();+ }drop(state);// Readiness marked while the slot was prepared runs in the next pass.wake(&self.shared.waker);@@ -444,6 +455,7 @@ impl WorkerRuntime for SharedRuntime {}Phase::Running | Phase::Stopping => state.phase = Phase::Stopping,}+ Slot::stop_sources(&mut state);let (mut state, wait) = slot.idle.wait_timeout_while(state, self.shared.timeouts.stop, |state| state.in_flight)diff --git a/src/vmm/src/vm.rs b/src/vmm/src/vm.rsindex 7933d2032..8c21b6ece 100644--- a/src/vmm/src/vm.rs+++ b/src/vmm/src/vm.rs@@ -97,8 +97,8 @@ impl<H: HostVm> std::fmt::Debug for Vm<H> {#[cfg(all(target_os = "linux", target_arch = "x86_64"))]impl Vm<boxlite_hypervisor::KvmVm> {- /// Validates `config` and preflights the RAM layout and boot leaf against- /// KVM before spawning the console worker and building the 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/// per disk, taking each disk's virtio-mmio slot and naming it on the/// command line; `config.cmdline` must leave room for those arguments,@@ -106,15 +106,11 @@ impl Vm<boxlite_hypervisor::KvmVm> {/// COM1 output goes to `console` through a queue, so a slow sink never/// stalls the guest.pub fn new(config: VmConfig, console: Box<dyn std::io::Write + Send>) -> Result<Self> {- use crate::{boot, cpu_features::preflight_x86, devices::console::DEFAULT_QUEUE_BYTES};+ use crate::{boot, devices::console::DEFAULT_QUEUE_BYTES};config.validate()?;let prepared = boxlite_hypervisor::KvmVm::prepare()?;- let leaf = preflight_x86(- config.memory_mib,- prepared.supported_cpuid(),- boot::BOOT_LEAF,- )?;+ let (leaf, hotplug_window) = boot::preflight(&config, &prepared)?;let (writer, worker) =ConsoleWorker::spawn(console, DEFAULT_QUEUE_BYTES).map_err(Error::SpawnConsole)?;let mut vm = Self::build(@@ -123,7 +119,9 @@ impl Vm<boxlite_hypervisor::KvmVm> {true,VirtioWorkers::new,move |ram, config| boot::prepare(ram, config, leaf).map(|setup| setup.boot_regs),- |chipset, ctx, config| crate::devices::add_all(chipset, ctx, config, writer),+ |chipset, ctx, config, host_vm| {+ crate::devices::add_all(chipset, ctx, config, writer, host_vm, hotplug_window)+ },)?;vm.console = Mutex::new(Some(worker));Ok(vm)@@ -143,7 +141,7 @@ impl<H: HostVm> Vm<H> {whereH: 'static,{- Self::with_devices(config, host_vm, boot, |chipset, ctx, _| {+ Self::with_devices(config, host_vm, boot, |chipset, ctx, _, _| {devices(chipset, ctx)})}@@ -153,7 +151,12 @@ impl<H: HostVm> Vm<H> {config: VmConfig,host_vm: impl FnOnce() -> boxlite_hypervisor::Result<H>,boot: impl FnOnce(&GuestRam, &VmConfig) -> Result<BootRegisters>,- devices: impl FnOnce(&mut ChipsetBuilder, DeviceContext<'_>, &mut VmConfig) -> Result<()>,+ devices: impl FnOnce(+ &mut ChipsetBuilder,+ DeviceContext<'_>,+ &mut VmConfig,+ &Arc<H>,+ ) -> Result<()>,) -> Result<Self>whereH: 'static,@@ -164,8 +167,8 @@ impl<H: HostVm> Vm<H> {/// Validates `config`, allocates the RAM layout, creates the host VM with/// `host_vm`, builds the chipset from the devices `devices` adds,/// registers every RAM range and writes the boot data with `boot`.- /// `devices` also gets the guest memory, the virtio workers and the- /// mutable configuration. Invalid configuration fails before `host_vm`+ /// `devices` also gets the guest memory, the virtio workers, the mutable+ /// configuration and the host VM. Invalid configuration fails before `host_vm`/// runs, and a chipset conflict before any RAM is registered./// `fresh_vm` requires a newly created VM with no independent vCPUs.#[cfg_attr(@@ -181,7 +184,12 @@ impl<H: HostVm> Vm<H> {fresh_vm: bool,create_workers: impl FnOnce(EventSender) -> std::io::Result<VirtioWorkers>,boot: impl FnOnce(&GuestRam, &VmConfig) -> Result<BootRegisters>,- devices: impl FnOnce(&mut ChipsetBuilder, DeviceContext<'_>, &mut VmConfig) -> Result<()>,+ devices: impl FnOnce(+ &mut ChipsetBuilder,+ DeviceContext<'_>,+ &mut VmConfig,+ &Arc<H>,+ ) -> Result<()>,) -> Result<Self>whereH: 'static,@@ -207,6 +215,7 @@ impl<H: HostVm> Vm<H> {controls: &mut controls,},&mut config,+ &host_vm,)?;let chipset = chipset.build()?;if let Err(error) = ram.map(&*host_vm) {@@ -245,7 +254,7 @@ impl<H: HostVm> Vm<H> {StopHandle(self.sender.clone())}- /// Controls the VM from another thread, addressing disks by their configured IDs.+ /// Controls the VM from another thread.pub fn control(&self) -> VmControl {self.control.clone()}@@ -316,6 +325,7 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {});// 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 console = self@@ -354,6 +364,7 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {impl<H: HostVm> Drop for Vm<H> {fn drop(&mut self) {+ self.control.close_memory();// 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");diff --git a/src/vmm/tests/boot/balloon.rs b/src/vmm/tests/boot/balloon.rsindex be80d9fc0..f3b042e8e 100644--- a/src/vmm/tests/boot/balloon.rs+++ b/src/vmm/tests/boot/balloon.rs@@ -110,9 +110,9 @@ fn run_reporting_guest(init_on_free: bool) -> (Evidence, String) {config,move || boxlite_hypervisor::KvmVm::from_prepared(prepared),move |ram, config| prepare(ram, config, leaf).map(|setup| setup.boot_regs),- |chipset, ctx, config| {+ |chipset, ctx, config, host_vm| {sampler_memory = Some(ctx.memory.memory().into_inner());- crate::devices::add_all(chipset, ctx, config, writer).map(|_| ())+ crate::devices::add_all(chipset, ctx, config, writer, host_vm, None)},).unwrap();diff --git a/src/vmm/tests/boot/hotplug.rs b/src/vmm/tests/boot/hotplug.rsnew file mode 100644index 000000000..305c05e7a--- /dev/null+++ b/src/vmm/tests/boot/hotplug.rs@@ -0,0 +1,123 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++//! virtio-mem on KVM with the pinned kernel: the host grows a 512 MiB or+//! 6 GiB guest by 1024 MiB, the guest writes 640 MiB, then the host shrinks+//! the target back to 256 MiB. The 6 GiB guest exercises high boot RAM.++use std::sync::atomic::AtomicBool;++use super::*;++/// Drives the target from the guest's console markers until `stop` is set.+fn control(+ log: &SerialLog,+ control: &crate::VmControl,+ done: &AtomicBool,+ stop: &crate::StopHandle,+) -> Option<crate::MemoryStatus> {+ let timeout = Duration::from_secs(2);+ let (mut grew, mut shrank) = (false, false);+ while !done.load(Ordering::SeqCst) {+ let text = log.text();+ if !grew && text.contains("HOTPLUG_BASE") {+ match control.set_memory_target_mib(1024, timeout) {+ Ok(()) => grew = true,+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}+ Err(error) => panic!("set grow target: {error}"),+ }+ }+ if !shrank && text.contains("HOTPLUG_USED") {+ control.set_memory_target_mib(256, timeout).unwrap();+ shrank = true;+ }+ if shrank && text.contains("HOTPLUG_GUEST_OK") {+ let status = control.memory_status(timeout).unwrap();+ if status.plugged_mib == 256 {+ stop.stop();+ return Some(status);+ }+ }+ std::thread::sleep(Duration::from_millis(100));+ }+ None+}++#[test]+#[ignore = "requires Linux x86_64 KVM, a virtio-mem VMM_KERNEL and VMM_HOTPLUG_INIT"]+fn virtio_mem_grows_and_shrinks_a_real_guest() {+ grow_and_shrink(512, 4 << 30);+}++#[test]+#[ignore = "requires Linux x86_64 KVM, a virtio-mem VMM_KERNEL and VMM_HOTPLUG_INIT"]+fn virtio_mem_grows_and_shrinks_with_high_boot_ram() {+ grow_and_shrink(6144, 7 << 30);+}++fn grow_and_shrink(boot_mib: u32, window_base: u64) {+ let init = fs::read(+ std::env::var_os("VMM_HOTPLUG_INIT")+ .expect("use make test:integration:vmm:linux for the guest init"),+ )+ .unwrap();+ let initramfs = TempFile::new(+ &format!("hotplug-{boot_mib}.cpio"),+ &newc_archive("init", &init),+ );+ let log = SerialLog::default();+ let cmdline = format!("{CONSOLE_CMDLINE} -- --hotplug-test");+ let mut config = linux_config(1, &cmdline, Some(initramfs.0.clone()));+ config.memory_mib = boot_mib;+ config.hotplug_mib = 1024;+ let mut vm = crate::Vm::new(config, Box::new(log.clone())).unwrap();+ let control_handle = vm.control();+ let vm_stop = vm.stop_handle();+ let done = Arc::new(AtomicBool::new(false));+ let controller = {+ let (log, done) = (log.clone(), Arc::clone(&done));+ std::thread::spawn(move || control(&log, &control_handle, &done, &vm_stop))+ };+ let (exit, elapsed) = run_with_watchdog(&mut vm, Duration::from_secs(120));+ done.store(true, Ordering::SeqCst);+ let after_shrink = controller.join().unwrap();+ let log = log.text();+ eprintln!("virtio-mem KVM elapsed={elapsed:?} status={after_shrink:?}\n{log}");++ assert!(!log.contains("HOTPLUG_FAIL"), "{log}");+ assert_eq!(exit.unwrap(), VmExit::StopRequested, "{log}");+ let expected_base = format!("{window_base:#x}");+ assert!(+ log.lines().any(|line| {+ line.starts_with("virtio_mem ")+ && line+ .split_once(": start address: ")+ .is_some_and(|(_, address)| address.trim() == expected_base)+ }),+ "virtio-mem window should start at {expected_base}\n{log}"+ );+ for marker in [+ "HOTPLUG_GROWN",+ "HOTPLUG_USED",+ "HOTPLUG_SHRUNK",+ "HOTPLUG_GUEST_OK",+ ] {+ assert!(log.contains(marker), "{marker} missing: {log}");+ }+ let used_gpa = log.lines().find_map(|line| {+ line.trim()+ .strip_prefix("HOTPLUG_GPA 0x")+ .and_then(|value| u64::from_str_radix(value, 16).ok())+ });+ assert!(+ used_gpa.is_some_and(|gpa| (window_base..window_base + (1 << 30)).contains(&gpa)),+ "guest write/readback should use the hotplug window: {log}"+ );+ let after_shrink = after_shrink.expect("recorded while the worker was still active");+ assert_eq!(after_shrink.requested_mib, 256);+ assert_eq!(after_shrink.plugged_mib, 256, "the guest returned the rest");+ assert_eq!(+ after_shrink.mapped_mib, 256,+ "emptied slots must leave KVM and the host mapping"+ );+}diff --git a/src/vmm/tests/boot/hotplug_init.c b/src/vmm/tests/boot/hotplug_init.cnew file mode 100644index 000000000..1e1cee887--- /dev/null+++ b/src/vmm/tests/boot/hotplug_init.c@@ -0,0 +1,117 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++/* Freestanding virtio-mem init: grow, use the new RAM, then shrink. */+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);+}+static void number(word value) {+ char text[19] = "0x0000000000000000\n";+ for (unsigned i = 0; i < 16; i++)+ text[17-i] = "0123456789abcdef"[(value >> (4*i)) & 15];+ print(text, sizeof(text));+}+__attribute__((noreturn)) static void finish(unsigned error) {+ if (error) { print("HOTPLUG_FAIL ", 13); number(error); }+ else print("HOTPLUG_GUEST_OK\n", 17);+ call(16, 1, 0x5409, 1, 0, 0, 0); /* drain tty */+ if (error) call(169, 0xfee1dead, 0x28121969, 0x01234567, 0, 0, 0);+ /* On success the host takes a live status sample before stopping the VM. */+ for (;;) call(34, 0, 0, 0, 0, 0, 0);+}+static void check(long value, unsigned error) { if (value < 0) finish(error); }+static void sleep_seconds(word seconds) {+ word time[2] = {seconds, 0};+ check(call(35, (long)time, 0, 0, 0, 0, 0), 1);+}+static word capacity(void) {+ word info[16];+ check(call(99, (long)info, 0, 0, 0, 0, 0), 2);+ return info[4]; /* sysinfo.totalram with mem_unit 1 on x86_64 */+}+/* Waits up to `seconds` for `ready` and returns the last capacity. */+static word wait_for(int (*ready)(word, word), word base, word seconds) {+ word now = capacity();+ for (word i = 0; i < seconds && !ready(now, base); i++) {+ sleep_seconds(1);+ now = capacity();+ }+ return now;+}+static const word MIB = 1UL << 20;+static int grown(word now, word base) { return now >= base + 896 * MIB; }+static int shrunk(word now, word base) { return now <= base + 384 * MIB; }++/* x86_64 pagemap: 4 KiB pages with the PFN in bits 0–54 and present in bit 63. */+static void check_written_gpa(word address, word length) {+ const word page = 4096, pfn_mask = (1UL << 55) - 1;+ check(call(83, (long)"/proc", 0755, 0, 0, 0, 0), 8);+ check(call(165, (long)"proc", (long)"/proc", (long)"proc", 0, 0, 0), 9);+ long fd = call(2, (long)"/proc/self/pagemap", 0, 0, 0, 0, 0);+ check(fd, 10);+ word entries[128], highest = 0, offset = 0;+ for (word first = 0; first < length / page; first += 128) {+ long read = call(17, fd, (long)entries, sizeof(entries),+ (address / page + first) * sizeof(word), 0, 0);+ if (read != sizeof(entries)) finish(11);+ for (word i = 0; i < 128; i++) {+ word pfn = entries[i] & pfn_mask;+ if ((entries[i] >> 63) && pfn > highest) {+ highest = pfn;+ offset = (first + i) * page;+ }+ }+ }+ if (!highest) finish(12);+ volatile word *sample = (volatile word *)(address + offset);+ *sample = 0xb07117e;+ if (*sample != 0xb07117e) finish(13);+ long read = call(17, fd, (long)entries, sizeof(word),+ (address + offset) / page * sizeof(word), 0, 0);+ if (read != sizeof(word) || !(entries[0] >> 63) ||+ (entries[0] & pfn_mask) != highest) finish(14);+ check(call(3, fd, 0, 0, 0, 0, 0), 15);+ print("HOTPLUG_GPA ", 12); number(highest * page);+}++__attribute__((used,noreturn)) void run(word argc, const char *const *argv) {+ const char expected[] = "--hotplug-test";+ /* A kernel option after the separator would arrive as an extra argument. */+ if (argc != 2) finish(16);+ for (word i = 0; i < sizeof(expected); i++)+ if (argv[1][i] != expected[i]) finish(16);++ const word use_bytes = 640 * MIB;+ word base = capacity();+ print("HOTPLUG_BASE ", 13); number(base);+ /* The host requests +1024 MiB once it reads the base line. */+ word now = wait_for(grown, base, 30);+ print("HOTPLUG_GROWN ", 14); number(now);+ if (!grown(now, base)) finish(3);+ /* Exercise allocation after the new RAM comes online. */+ long address = call(9, 0, use_bytes, 3, 0x22, -1, 0);+ check(address, 4);+ word *memory = (word *)address;+ for (word i = 0; i < use_bytes / sizeof(word); i++) memory[i] = i ^ 0x5a5a;+ for (word i = 0; i < use_bytes / sizeof(word); i++)+ if (memory[i] != (i ^ 0x5a5a)) finish(5);+ check_written_gpa(address, use_bytes);+ check(call(11, address, use_bytes, 0, 0, 0, 0), 6);+ print("HOTPLUG_USED\n", 13);+ /* The host lowers the target to +256 MiB once it reads the line above. */+ now = wait_for(shrunk, base, 60);+ print("HOTPLUG_SHRUNK ", 15); number(now);+ finish(shrunk(now, base) ? 0 : 7);+}+__asm__(".global _start\n_start:\n xor %rbp,%rbp\n"+ " mov (%rsp),%rdi\n lea 8(%rsp),%rsi\n and $-16,%rsp\n call run\n");diff --git a/src/vmm/tests/boot/mod.rs b/src/vmm/tests/boot/mod.rsindex 40181e08e..d3ad7039e 100644--- a/src/vmm/tests/boot/mod.rs+++ b/src/vmm/tests/boot/mod.rs@@ -41,6 +41,7 @@ use crate::{};mod balloon;+mod hotplug;#[cfg(target_os = "linux")]#[path = "virtio_blk.rs"]mod virtio_blk;@@ -81,6 +82,7 @@ fn config(kernel: PathBuf, cmdline: &str) -> VmConfig {vsock: None,network: None,virtio_console: false,+ hotplug_mib: 0,}}@@ -221,6 +223,7 @@ fn linux_config(vcpu_count: u8, cmdline: &str, initramfs: Option<PathBuf>) -> Vmvsock: None,network: None,virtio_console: false,+ hotplug_mib: 0,};config.validate().unwrap();configdiff --git a/src/vmm/tests/control/memory.rs b/src/vmm/tests/control/memory.rsnew file mode 100644index 000000000..67c2e68f0--- /dev/null+++ b/src/vmm/tests/control/memory.rs@@ -0,0 +1,151 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++use std::net::Shutdown;+use std::sync::mpsc::{Receiver, TryRecvError};++use super::*;++fn queue(sender: &MemorySender) -> io::Result<Receiver<io::Result<()>>> {+ let (reply, done) = mpsc::sync_channel(1);+ sender.submit(MemoryRequest::SetTarget {+ added_mib: 128,+ reply,+ })?;+ Ok(done)+}++#[test]+fn stop_discards_unclaimed_commands_and_prevents_late_activation() {+ let (sender, device) = channel();+ let mut old = device.prepare().unwrap();+ assert_eq!(+ queue(&sender).unwrap_err().kind(),+ io::ErrorKind::WouldBlock+ );+ old.worker_started();++ let claimed = queue(&sender).unwrap();+ let pending = queue(&sender).unwrap();+ assert_eq!(device.batch_len().unwrap(), 2);+ let Some(MemoryRequest::SetTarget { reply, .. }) = device.claim() else {+ panic!("expected the admitted command");+ };+ old.worker_stopped();+ old.worker_started();+ assert_eq!(pending.try_recv().unwrap_err(), TryRecvError::Disconnected);+ assert_eq!(+ queue(&sender).unwrap_err().kind(),+ io::ErrorKind::WouldBlock+ );+ assert!(device.claim().is_none());+ reply.send(Ok(())).unwrap();+ claimed.try_recv().unwrap().unwrap();++ let mut current = device.prepare().unwrap();+ current.worker_started();+ drop(old);+ assert_eq!(device.batch_len().unwrap(), 0);+ let new_command = queue(&sender).unwrap();+ drop(device);+ assert_eq!(+ queue(&sender).unwrap_err().kind(),+ io::ErrorKind::BrokenPipe+ );+ assert_eq!(+ new_command.try_recv().unwrap_err(),+ TryRecvError::Disconnected+ );+}++#[test]+fn admission_is_bounded_and_post_snapshot_work_rings_again() {+ let (sender, device) = channel();+ let mut source = device.prepare().unwrap();+ let mut poll = mio::Poll::new().unwrap();+ let mut events = mio::Events::with_capacity(4);+ poll.registry()+ .register(source.as_source(), mio::Token(0), mio::Interest::READABLE)+ .unwrap();+ source.worker_started();+ let replies: Vec<_> = (0..CAPACITY).map(|_| queue(&sender).unwrap()).collect();+ assert_eq!(+ queue(&sender).unwrap_err().kind(),+ io::ErrorKind::WouldBlock+ );+ poll.poll(&mut events, Some(Duration::from_secs(1)))+ .unwrap();+ assert!(!events.is_empty());+ let batch = device.batch_len().unwrap();+ assert_eq!(batch, CAPACITY);+ assert!(device.claim().is_some());+ let late = queue(&sender).unwrap();+ for _ in 1..batch {+ assert!(device.claim().is_some());+ }+ poll.poll(&mut events, Some(Duration::from_secs(1)))+ .unwrap();+ assert!(!events.is_empty());+ assert!(+ replies+ .iter()+ .all(|reply| matches!(reply.try_recv(), Err(TryRecvError::Disconnected)))+ );+ assert_eq!(device.batch_len().unwrap(), 1);+ assert!(matches!(late.try_recv(), Err(TryRecvError::Empty)));+ assert!(device.claim().is_some());+}++#[test]+fn hard_wake_errors_close_admission_and_drop_queued_replies() {+ for read_error in [false, true] {+ let (sender, device) = channel();+ let mut source = device.prepare().unwrap();+ source.worker_started();+ let pending = queue(&sender).unwrap();+ {+ let endpoint = lock(&device.0);+ let active = endpoint.activation.as_ref().unwrap();+ if read_error {+ active.read.shutdown(Shutdown::Read).unwrap();+ } else {+ active.write.shutdown(Shutdown::Write).unwrap();+ }+ }+ if read_error {+ assert_eq!(+ device.batch_len().unwrap_err().kind(),+ io::ErrorKind::BrokenPipe+ );+ } else {+ assert_eq!(+ queue(&sender).unwrap_err().kind(),+ io::ErrorKind::BrokenPipe+ );+ }+ assert_eq!(pending.try_recv().unwrap_err(), TryRecvError::Disconnected);+ assert!(device.claim().is_none());+ assert_eq!(+ queue(&sender).unwrap_err().kind(),+ io::ErrorKind::WouldBlock+ );+ }+}++#[test]+fn doorbell_drain_retries_interruptions_until_empty() {+ let mut reads = [+ Err(io::Error::from(io::ErrorKind::Interrupted)),+ Ok(1),+ Err(io::Error::from(io::ErrorKind::WouldBlock)),+ ]+ .into_iter();+ struct Scripted<'a>(&'a mut dyn Iterator<Item = io::Result<usize>>);+ impl Read for Scripted<'_> {+ fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {+ self.0.next().unwrap()+ }+ }+ drain(Scripted(&mut reads)).unwrap();+ assert!(reads.next().is_none());+}diff --git a/src/vmm/tests/control/mod.rs b/src/vmm/tests/control/mod.rsindex 14885c945..767d8b072 100644--- a/src/vmm/tests/control/mod.rs+++ b/src/vmm/tests/control/mod.rs@@ -31,6 +31,7 @@ fn config(disks: Vec<DiskConfig>) -> VmConfig {vsock: None,network: None,virtio_console: false,+ hotplug_mib: 0,}}@@ -110,7 +111,7 @@ fn block_id_routes_growth_independently_of_disk_order() {config(disks.clone()),|| Ok(MockVm::new()),|_, _| Ok(BootRegisters::default()),- |chipset, mut ctx, config| {+ |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()?)?;diff --git a/src/vmm/tests/mem/mod.rs b/src/vmm/tests/mem/mod.rsnew file mode 100644index 000000000..c262d6800--- /dev/null+++ b/src/vmm/tests/mem/mod.rs@@ -0,0 +1,284 @@+// Copyright 2026 BoxLite Contributors+// SPDX-License-Identifier: Apache-2.0++//! virtio-mem device tests: request responses, the configuration layout, the+//! host target, activation and one request through a real queue.++use std::{+ sync::{+ Arc, Mutex,+ atomic::{AtomicUsize, Ordering},+ },+ time::Duration,+};++use virtio_queue::{Queue, QueueT, desc::split::Descriptor};+use vm_memory::{GuestAddress, GuestAddressSpace, GuestMemoryBackend};++use super::*;+use crate::{+ events::EventLoop,+ hotplug::{BLOCK_SIZE, HotplugWindow},+ memory::{GuestMemoryMmap, GuestMemoryView},+ mock_vm::MockVm,+ virtio::{+ EventError, EventRegistrar, EventSource, SourceId, VirtioInterrupt, queue::VirtQueues,+ },+};++const DESC: u64 = 0x1000;+const AVAIL: u64 = 0x2000;+const USED: u64 = 0x3000;+const REQUEST: u64 = 0x4000;+const RESPONSE: u64 = 0x5000;+const HOTPLUG_START: u64 = 1 << 32;+const WRITE: u16 = 2;+const NEXT: u16 = 1;++fn view() -> GuestMemoryView {+ GuestMemoryView::new(GuestMemoryMmap::from_ranges(&[(GuestAddress(0), 0x1_0000)]).unwrap())+}++fn device(capacity_mib: u32) -> (GuestMemoryView, VirtioMem<MockVm>) {+ let view = view();+ let window =+ HotplugWindow::plan(&[(GuestAddress(0), 0x1_0000)], capacity_mib, 1 << 36, 16).unwrap();+ let memory = HotplugMemory::new(Arc::new(MockVm::new()), view.clone(), window);+ let mut registry = crate::control::ControlRegistry::default();+ (+ view,+ VirtioMem::new(memory, registry.register_memory().unwrap()),+ )+}++fn block(index: u64) -> u64 {+ HOTPLUG_START + index * BLOCK_SIZE+}++#[test]+fn a_plug_above_the_target_is_nacked_not_an_error() {+ let (_, mut mem) = device(256);+ assert_eq!(mem.handle(PLUG, block(0), 1), (NACK, 0));+ mem.requested = 128 * MIB;+ assert_eq!(mem.handle(PLUG, block(0), 64), (ACK, 0));+ assert_eq!(mem.handle(PLUG, block(64), 1), (NACK, 0));+ assert_eq!(mem.memory.plugged_bytes(), 128 * MIB);+}++#[test]+fn requests_on_the_wrong_state_or_range_are_errors() {+ let (_, mut mem) = device(128);+ mem.requested = 128 * MIB;+ assert_eq!(mem.handle(UNPLUG, block(0), 1), (ERROR, 0));+ assert_eq!(mem.handle(PLUG, block(0) + 4096, 1), (ERROR, 0));+ assert_eq!(mem.handle(PLUG, block(64), 1), (ERROR, 0));+ assert_eq!(mem.handle(PLUG, block(0), 0), (ERROR, 0));+ assert_eq!(mem.handle(7, block(0), 1), (ERROR, 0));+ assert_eq!(mem.handle(PLUG, block(0), 2), (ACK, 0));+ assert_eq!(mem.handle(PLUG, block(1), 1), (ERROR, 0));+}++#[test]+fn state_unplug_and_unplug_all_follow_the_blocks() {+ let (_, mut mem) = device(128);+ mem.requested = 128 * MIB;+ mem.handle(PLUG, block(0), 2);+ assert_eq!(mem.handle(STATE, block(0), 2), (ACK, 0));+ assert_eq!(mem.handle(STATE, block(1), 2), (ACK, 2));+ assert_eq!(mem.handle(STATE, block(2), 2), (ACK, 1));+ assert_eq!(mem.handle(UNPLUG, block(1), 1), (ACK, 0));+ assert_eq!(mem.memory.plugged_bytes(), BLOCK_SIZE);+ assert_eq!(mem.handle(UNPLUG_ALL, 0, 0), (ACK, 0));+ assert_eq!(+ (mem.memory.plugged_bytes(), mem.memory.mapped_bytes()),+ (0, 0)+ );+ assert_eq!(mem.requested, 128 * MIB, "unplug-all keeps the host target");+}++#[test]+fn the_configuration_follows_the_virtio_layout() {+ let (_, mut mem) = device(256);+ mem.requested = 128 * MIB;+ mem.handle(PLUG, block(0), 1);+ let mut config = [0u8; 56];+ mem.read_config(0, &mut config).unwrap();+ let field = |offset: usize| u64::from_le_bytes(config[offset..offset + 8].try_into().unwrap());+ assert_eq!(field(0), BLOCK_SIZE);+ assert_eq!(field(16), HOTPLUG_START);+ assert_eq!((field(24), field(32)), (256 * MIB, 256 * MIB));+ assert_eq!((field(40), field(48)), (BLOCK_SIZE, 128 * MIB));+ let mut tail = [0xffu8; 4];+ mem.read_config(54, &mut tail).unwrap();+ assert_eq!(tail, [0, 0, 0, 0]);+}++#[test]+fn the_device_accepts_slot_multiples_within_capacity_in_both_directions() {+ let (view, mut mem) = device(256);+ mem.set_features(UNPLUGGED_INACCESSIBLE).unwrap();+ mem.activate(context(&view, Arc::default())).unwrap();+ for bad in [64, 384] {+ assert_eq!(+ mem.set_target(bad).unwrap_err().kind(),+ io::ErrorKind::InvalidInput+ );+ }+ mem.set_target(256).unwrap();+ mem.set_target(128).unwrap();+ assert_eq!(+ mem.status(),+ MemoryStatus {+ capacity_mib: 256,+ requested_mib: 128,+ plugged_mib: 0,+ mapped_mib: 0,+ }+ );+}++#[test]+fn features_other_than_unplugged_inaccessible_are_refused() {+ let (_, mut mem) = device(128);+ assert_eq!(mem.set_features(1).unwrap_err().unsupported, 1);+ mem.set_features(UNPLUGGED_INACCESSIBLE).unwrap();+}++#[derive(Default)]+struct Interrupt {+ raised: AtomicUsize,+ config: AtomicUsize,+}++impl VirtioInterrupt for Interrupt {+ fn raise(&self) {+ self.raised.fetch_add(1, Ordering::SeqCst);+ }+ fn interrupt_status(&self) -> u8 {+ 0+ }+ fn ack_interrupt(&self, _: u8) {}+ fn config_generation(&self) -> u8 {+ 0+ }+ fn raise_config(&self) {+ self.config.fetch_add(1, Ordering::SeqCst);+ }+ fn device_status(&self) -> u8 {+ 0+ }+ fn set_device_status(&self, _: u8) {}+ fn set_needs_reset(&self) {}+}++#[derive(Default)]+struct Sources(Mutex<Option<Box<dyn EventSource>>>);+impl EventRegistrar for Sources {+ fn register(&self, source: Box<dyn EventSource>) -> std::result::Result<SourceId, EventError> {+ assert!(self.0.lock().unwrap().replace(source).is_none());+ Ok(SourceId(1))+ }+ fn deregister(&self, _: SourceId) {+ self.0.lock().unwrap().take();+ }+}++fn context(view: &GuestMemoryView, interrupt: Arc<Interrupt>) -> ActivationContext {+ let mut queue = Queue::new(128).unwrap();+ queue.try_set_size(8).unwrap();+ queue+ .try_set_desc_table_address(GuestAddress(DESC))+ .unwrap();+ queue+ .try_set_avail_ring_address(GuestAddress(AVAIL))+ .unwrap();+ queue.try_set_used_ring_address(GuestAddress(USED)).unwrap();+ queue.set_ready(true);+ ActivationContext {+ memory: view.clone(),+ queues: VirtQueues::prepare(vec![queue], SPEC.queue_max, false, false, view.clone())+ .unwrap(),+ interrupt,+ events: Arc::new(Sources::default()),+ waker: Arc::new(|| {}),+ sender: EventLoop::new().unwrap().sender(),+ }+}++#[test]+fn activation_requires_unplugged_inaccessible() {+ let (view, mut mem) = device(128);+ mem.set_features(0).unwrap();+ assert!(mem.activate(context(&view, Arc::default())).is_err());+ mem.set_features(UNPLUGGED_INACCESSIBLE).unwrap();+ mem.activate(context(&view, Arc::default())).unwrap();+}++#[test]+fn a_timed_out_control_command_can_still_publish_its_target() {+ let view = view();+ let window = HotplugWindow::plan(&[(GuestAddress(0), 0x1_0000)], 256, 1 << 36, 16).unwrap();+ 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 sources = Arc::new(Sources::default());+ let interrupt = Arc::new(Interrupt::default());+ let mut context = context(&view, interrupt.clone());+ context.events = sources.clone();+ mem.set_features(UNPLUGGED_INACCESSIBLE).unwrap();+ mem.activate(context).unwrap();+ sources.0.lock().unwrap().as_mut().unwrap().worker_started();+ let timeout = Duration::ZERO;+ assert_eq!(+ control+ .set_memory_target_mib(128, timeout)+ .unwrap_err()+ .kind(),+ io::ErrorKind::TimedOut+ );+ assert_eq!(mem.status().requested_mib, 0);+ assert_eq!(interrupt.config.load(Ordering::SeqCst), 0);+ mem.on_event(DeviceEvent::BackendReady(SourceId(1)))+ .unwrap();+ assert_eq!(mem.status().requested_mib, 128);+ assert_eq!(interrupt.config.load(Ordering::SeqCst), 1);+}++#[test]+fn a_plug_request_through_the_queue_maps_the_slot_and_answers_ack() {+ let (view, mut mem) = device(128);+ let interrupt = Arc::new(Interrupt::default());+ mem.set_features(UNPLUGGED_INACCESSIBLE).unwrap();+ mem.activate(context(&view, Arc::clone(&interrupt)))+ .unwrap();+ mem.set_target(128).unwrap();+ assert_eq!(interrupt.config.load(Ordering::SeqCst), 1);++ let ram = view.memory();+ let mut request = [0u8; 24];+ request[8..16].copy_from_slice(&block(0).to_le_bytes());+ request[16..18].copy_from_slice(&1u16.to_le_bytes());+ ram.write_slice(&request, GuestAddress(REQUEST)).unwrap();+ ram.write_obj(Descriptor::new(REQUEST, 24, NEXT, 1), GuestAddress(DESC))+ .unwrap();+ ram.write_obj(+ Descriptor::new(RESPONSE, 10, WRITE, 0),+ GuestAddress(DESC + 16),+ )+ .unwrap();+ ram.write_obj(0u16, GuestAddress(AVAIL + 4)).unwrap();+ ram.write_obj(1u16, GuestAddress(AVAIL + 2)).unwrap();+ ram.write_obj(0xffffu16, GuestAddress(RESPONSE)).unwrap();+ drop(ram);++ mem.on_event(DeviceEvent::QueueKick(0)).unwrap();++ let ram = view.memory();+ assert_eq!(ram.read_obj::<u16>(GuestAddress(RESPONSE)).unwrap(), ACK);+ assert_eq!(ram.read_obj::<u16>(GuestAddress(USED + 2)).unwrap(), 1);+ assert_eq!(ram.read_obj::<u32>(GuestAddress(USED + 8)).unwrap(), 10);+ assert_eq!(interrupt.raised.load(Ordering::SeqCst), 1);+ assert_eq!(mem.status().plugged_mib, 2);+ assert!(view.memory().address_in_range(GuestAddress(block(0))));+}diff --git a/src/vmm/tests/params/mod.rs b/src/vmm/tests/params/mod.rsindex 037657383..0e0e0fbfb 100644--- a/src/vmm/tests/params/mod.rs+++ b/src/vmm/tests/params/mod.rs@@ -182,6 +182,7 @@ fn agrees_with_validate_on_command_line_limits() {vsock: None,network: None,virtio_console: false,+ hotplug_mib: 0,};assert_eq!(config.validate().is_ok(), accepted, "{config:?}");}diff --git a/src/vmm/tests/vm/mod.rs b/src/vmm/tests/vm/mod.rsindex ba698285e..640d84f8f 100644--- a/src/vmm/tests/vm/mod.rs+++ b/src/vmm/tests/vm/mod.rs@@ -64,6 +64,7 @@ fn config(vcpu_count: u8, memory_mib: u32) -> VmConfig {vsock: None,network: None,virtio_console: false,+ hotplug_mib: 0,}}@@ -307,7 +308,7 @@ fn with_fresh_backend<H: HostVm + 'static>(true,VirtioWorkers::new,boot,- |chipset, ctx, _| devices(chipset, ctx),+ |chipset, ctx, _, _| devices(chipset, ctx),)}@@ -687,7 +688,7 @@ fn failed_boot_keeps_registration_and_backing_when_workers_fail_to_join() {true,|_| Ok(VirtioWorkers::with_runtime(runtime.clone())),failed_boot,- |_, ctx, _| {+ |_, ctx, _, _| {backing = Some(Arc::downgrade(&ctx.memory.memory().into_inner()));Ok(())},@@ -1831,7 +1832,9 @@ fn rtc_coexists_with_max_disks_balloon_and_aggregate_filesystem() {configuration,|| Ok(MockVm::new()),|ram, config| crate::boot::prepare(ram, config, leaf).map(|setup| setup.boot_regs),- |chipset, ctx, config| crate::devices::add_all(chipset, ctx, config, writer),+ |chipset, ctx, config, host_vm| {+ crate::devices::add_all(chipset, ctx, config, writer, host_vm, None)+ },).expect("real RTC and all configured virtio devices must compose without conflicts");@@ -1923,7 +1926,9 @@ fn aggregate_filesystem_is_announced_and_exposes_its_transport_config() {);Ok(BootRegisters::default())},- |chipset, ctx, config| crate::devices::add_all(chipset, ctx, config, writer).map(|_| ()),+ |chipset, ctx, config, host_vm| {+ crate::devices::add_all(chipset, ctx, config, writer, host_vm, None)+ },).unwrap();let mut id = [0; 4];@@ -1943,3 +1948,188 @@ fn aggregate_filesystem_is_announced_and_exposes_its_transport_config() {console.finish();std::fs::remove_dir(path).unwrap();}++#[test]+fn an_invalid_hotplug_capacity_fails_before_the_host_vm_exists() {+ for capacity in [64, 129, u32::MAX] {+ let mut configuration = config(1, 2);+ configuration.hotplug_mib = capacity;+ let built = Cell::new(false);+ let error = bare(configuration, || {+ built.set(true);+ Ok(MockVm::new())+ })+ .expect_err("invalid hotplug capacity");+ assert!(matches!(error, Error::InvalidHotplugSize(mib) if mib == capacity));+ assert!(!built.get());+ }+ let mut configuration = config(1, 2);+ configuration.hotplug_mib = 128;+ configuration.validate().unwrap();+}++#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+#[test]+fn a_hotplug_capacity_adds_virtio_mem_and_registers_its_control() {+ use crate::devices::console::{ConsoleWorker, DEFAULT_QUEUE_BYTES};+ use boxlite_hypervisor::VcpuExit;+ let caller_cmdline = "console=ttyS0 memhp_default_state=offline \+ memory_hotplug.online_policy=contig-zones -- --listen vsock://2695";+ let defaults = "memhp_default_state=online memory_hotplug.online_policy=auto-movable";+ for (capacity, activate, cmdline, expected_tail) in [+ (+ 256,+ true,+ caller_cmdline,+ format!("{defaults} {caller_cmdline}"),+ ),+ (128, false, "", defaults.to_owned()),+ (0, false, caller_cmdline, caller_cmdline.to_owned()),+ ] {+ let present = capacity != 0;+ let mut configuration = config(1, 2);+ configuration.hotplug_mib = capacity;+ configuration.cmdline = cmdline.to_owned();+ let window = present.then(|| {+ crate::hotplug::HotplugWindow::plan(+ &ram_ranges(configuration.memory_mib),+ capacity,+ 1 << 36,+ 2,+ )+ .unwrap()+ });+ let (writer, mut console) =+ ConsoleWorker::spawn(Box::new(io::sink()), DEFAULT_QUEUE_BYTES).unwrap();+ let mut vm = Vm::with_devices(+ configuration,+ || Ok(MockVm::new()),+ |_, config| {+ // The balloon keeps slot 0; virtio-mem takes the next slot.+ let boot_args = config+ .cmdline+ .strip_prefix("virtio_mmio.device=4K@0xd0000000:5 ")+ .expect("the balloon is the first slot");+ let boot_args = if present {+ boot_args+ .strip_prefix("virtio_mmio.device=4K@0xd0001000:6 ")+ .expect("virtio-mem is the second slot")+ } else {+ boot_args+ };+ assert_eq!(boot_args, expected_tail);+ Ok(BootRegisters::default())+ },+ |chipset, ctx, config, host_vm| {+ crate::devices::add_all(chipset, ctx, config, writer, host_vm, window)+ },+ )+ .unwrap();+ let control = vm.control();+ let expected = if present {+ io::ErrorKind::WouldBlock+ } else {+ io::ErrorKind::Unsupported+ };+ let timeout = std::time::Duration::ZERO;+ assert_eq!(+ control+ .set_memory_target_mib(128, timeout)+ .unwrap_err()+ .kind(),+ expected+ );+ assert_eq!(control.memory_status(timeout).unwrap_err().kind(), expected);+ if present {+ let mut id = [0; 4];+ vm.chipset.as_ref().unwrap().dispatch(VcpuExit::MmioRead {+ guest_addr: 0xd000_1008,+ bytes: &mut id,+ });+ assert_eq!(u32::from_le_bytes(id), 24);+ }+ if activate {+ let write = |offset: u64, value: u32| {+ assert!(+ vm.chipset+ .as_ref()+ .unwrap()+ .dispatch(VcpuExit::MmioWrite {+ guest_addr: 0xd000_1000 + offset,+ bytes: &value.to_le_bytes(),+ })+ .is_none()+ );+ };+ let activate = [+ (0x070, 1),+ (0x070, 3),+ (0x024, 0),+ (0x020, 2),+ (0x024, 1),+ (0x020, 1),+ (0x070, 0xb),+ (0x038, 16),+ (0x080, 0x10000),+ (0x090, 0x11000),+ (0x0a0, 0x12000),+ (0x044, 1),+ (0x070, 0xf),+ ];+ for (offset, value) in activate {+ write(offset, value);+ }+ let budget = std::time::Duration::from_secs(1);+ assert_eq!(control.memory_status(budget).unwrap().requested_mib, 0);+ assert_eq!(+ control+ .set_memory_target_mib(64, budget)+ .unwrap_err()+ .kind(),+ io::ErrorKind::InvalidInput+ );+ control.set_memory_target_mib(128, budget).unwrap();+ let status = control.memory_status(budget).unwrap();+ assert_eq!(+ (+ status.capacity_mib,+ status.requested_mib,+ status.plugged_mib+ ),+ (capacity, 128, 0)+ );+ write(0x070, 0x80);+ assert_eq!(+ control.memory_status(timeout).unwrap_err().kind(),+ io::ErrorKind::WouldBlock+ );+ write(0x070, 0);+ for (offset, value) in activate {+ write(offset, value);+ }+ assert_eq!(control.memory_status(budget).unwrap().requested_mib, 128);+ write(0x070, 0);+ assert_eq!(+ control.memory_status(timeout).unwrap_err().kind(),+ io::ErrorKind::WouldBlock+ );+ }+ vm.stop_handle().stop();+ vm.run().unwrap();+ if present {+ assert_eq!(+ control.memory_status(timeout).unwrap_err().kind(),+ io::ErrorKind::BrokenPipe+ );+ assert_eq!(+ control+ .set_memory_target_mib(128, timeout)+ .unwrap_err()+ .kind(),+ io::ErrorKind::BrokenPipe+ );+ }+ drop(vm);+ console.finish();+ }+}diff --git a/tests/scripts/test_vmm_boot_coverage.py b/tests/scripts/test_vmm_boot_coverage.pyindex 5cdc0233e..06d1b993c 100644--- a/tests/scripts/test_vmm_boot_coverage.py+++ b/tests/scripts/test_vmm_boot_coverage.py@@ -33,6 +33,7 @@ class VmmBootCoverageTest(unittest.TestCase):f"PROJECT_ROOT := {root}\n""VMM_BALLOON_INIT :=\n""VMM_DISK_GROW_INIT :=\n"+ "VMM_HOTPLUG_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"